signed

QiShunwang

“诚信为本、客户至上”

Python使用Unittest读取xml文件(单元测试)

2021/6/3 17:00:28   来源:

我们一共有三个文件

  1. 123.xml
  2. testxml.py
  3. readxml.py

读取xml文件代码(死格式)

from xml.dom import minidom
class Readxml():
    def read_xml(self,filename,onename,twoname):
        root =minidom.parse(filename)
        firstnode =root.getElementsByTagName(onename)[0]
        secondnode=firstnode.getElementsByTagName(twoname)[0].firstChild.data
        return secondnode
readxml = Readxml()   # 实例化对象

Demo

123.xml
xml文件demo

<echo>
    <cheng>
        <num1>2</num1>
        <num2>4</num2>
        <num3>8</num3>
    </cheng>
    <chu>
        <num1>2</num1>
        <num2>4</num2>
        <num3>8</num3>
    </chu>
</echo>

readxml.py
py文件,这个文件用来读取xml文件,获取xml文件的数据。

from xml.dom import minidom
class Readxml():
    def read_xml(self,filename,onename,twoname):
        root =minidom.parse(filename)
        firstnode =root.getElementsByTagName(onename)[0]	# 获取到cheng标签
        secondnode=firstnode.getElementsByTagName(twoname)[0].firstChild.data
        return secondnode

if __name__ == '__main__':
    readxml = Readxml()
    print(readxml.read_xml("123.xml","cheng","num1"))		# 获取xml文件数据
    print(readxml.read_xml("123.xml", "cheng", "num2"))
    print(readxml.read_xml("123.xml", "cheng", "num3"))

testxml.py
这个文件使用unittest模块,测试数据预期结果和实际结果。

import unittest									# 导入unittest模块
from Unittest.demotest import Testsdemo			# 导入开发写的函数,要测的函数
from Unittest.xmldemo.readxml import Readxml	# 导入读取xml文件
readxml = Readxml()			# 实例化对象
testdemo = Testsdemo()		# 实例化对象


class TestXml(unittest.TestCase):    # 继承unittest类
    def test001(self):				# 测试用例001
        num1 = int(readxml.read_xml("xmldemo/123.xml","cheng","num1")) # 获取xml文件中的数据
        num2 = int(readxml.read_xml("xmldemo/123.xml","cheng","num2"))
        num3 = int(readxml.read_xml("xmldemo/123.xml","cheng","num3"))
        a = testdemo.cf(num1,num2)		# 开发写的函数,进行传参并赋值
        self.assertEqual(a,num3)		# unittest模块比较预期结果和实际结果
if __name__ == '__main__':
    unittest.main()						# 启动测试用例

文件路径注意修改