Python+Unittest参数化之parameterized数据驱动

2019-11-28 23:26:55 浏览数 (2)

一、parameterized介绍

Unittest第三方库parameterized类似Python数据驱动模块DDT、Pytest@pytest.mark.parametrize【Pytest篇】装饰器@pytest.mark.parametrize多样参数化(二)Pytest装饰器@pytest.mark.parametrize数据驱动(三)可以实现参数化用户数据驱动,避免写多个方法(冗余)

二、安装

pip install parameterized

三、导入

from parameterized import parameterized,param

四、实例

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

代码语言:javascript复制
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 FilesPython35python.exe" "C:Program FilesJetBrainsPyCharm Community Edition 2018.2.4helperspycharm_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:UserswangliPycharmProjectsTesttest
 
 
Ran 2 tests in 0.001s
 
OK
 
Process finished with exit code 0

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

代码语言:javascript复制
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 FilesPython35python.exe" "C:Program FilesJetBrainsPyCharm Community Edition 2018.2.4helperspydevpydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 1145 --file "C:Program FilesJetBrainsPyCharm Community Edition 2018.2.4helperspycharm_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:UserswangliPycharmProjectsTesttest
 
 
 
Ran 2 tests in 0.004s
 
OK
url headers data1
url headers data2
 
Process finished with exit code 0

0 人点赞