Python Unittest参数化parameterized之数据驱动

一、parameterized介绍

之前我们写过

Unittest第三方库parameterized类似Unittest的DDT、[email protected],可以实现参数化用户数据驱动,避免写多个方法(冗余)

二、安装

pip  install  parameterized

三、导入

from parameterized import parameterized,param

四、实例

1、实现2个参数相加等于第3个参数,我们可以看到,参数是以列表形式传入的,根据参数个数,迭代不同次数



from parameterized import parameterized,param
import unittest
import requests
class Test(unittest.TestCase):
    @parameterized.expand([param(1,2,3),param('he','llo','hello')])
    def test(self,test1,test2,test3):
        self.assertEqual((test1+test2),test3)

if __name__ == '__main__':
    unittest.main()

Testing started at 12:36 ...
"C:\Program Files\Python35\python.exe" "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.4\helpers\pycharm\_jb_unittest_runner.py" --path C:/Users/wangli/PycharmProjects/Test/test/test01.py
Launching unittests with arguments python -m unittest C:/Users/wangli/PycharmProjects/Test/test/test01.py in C:\Users\wangli\PycharmProjects\Test\test


Ran 2 tests in 0.001s

OK

Process finished with exit code 0

2、我们可以通过上面方法实现我们测试用例的迭代,将测试用例的请求参数组装成列表形式,传给@parameterized.expand([参数1,参数2,参数3]),实现测试用例的多次迭代,避免写多个测试方法


from parameterized import parameterized,param
import unittest
import requests
class Test(unittest.TestCase):
    @parameterized.expand([param('url','headers','data1'),param('url','headers','data2')])
    def test(self,url,headers,data):
        print(url,headers,data)
        r=requests.post(url=url,headers=headers,json=data)

if __name__ == '__main__':
    unittest.main()

Testing started at 12:46 ...
"C:\Program Files\Python35\python.exe" "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.4\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 1145 --file "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.4\helpers\pycharm\_jb_unittest_runner.py" --path C:/Users/wangli/PycharmProjects/Test/test/test01.py
pydev debugger: process 24756 is connecting

Connected to pydev debugger (build 182.4505.26)
Launching unittests with arguments python -m unittest C:/Users/wangli/PycharmProjects/Test/test/test01.py in C:\Users\wangli\PycharmProjects\Test\test



Ran 2 tests in 0.004s

OK
url headers data1
url headers data2

Process finished with exit code 0

 

你可能感兴趣的:(Python接口自动化,Python,unittest框架)