装饰器@pytest.mark.parametrize()可以使用单个变量接收数据,也可以使用多个变量接收,测试用例函数需要与其保持一致
例子:
import pytest data1 = [[1,2,3],[4,5,9]] def add(a,b): return a+b @pytest.mark.parametrize("a,b,expect",data1) def test_add1(a,b,expect): print("测试函数1测试数据为 {}-{}".format(a,b)) assert add(a,b) == expect @pytest.mark.parametrize("value",data1) def test_add2(value): print("测试函数2测试数据为{}".format(value)) assert add(value[0],value[1]) == value[2] if __name__ == "__main__": pytest.main(["-sv", "test_2.py"])
测试数据组合
import pytest data_1 = [1, 2] data_2 = [3, 4] @pytest.mark.parametrize('a', data_1) @pytest.mark.parametrize('b', data_2) def test_parametrize_1(a, b): print('\n测试数据为\n{},{}'.format(a, b)) if __name__ == '__main__': pytest.main(["-s", "test_3.py"])
标记用例
参数化装饰器可以标记用例失败(xfail)或者跳过(skip或skipif)
import pytest data_1 = [[1,2,3], pytest.param(3,4,8,marks=pytest.mark.skip)] def add(a,b): return a+b @pytest.mark.parametrize("a,b,expect",data_1) def test_pa(a,b,expect): print('测试数据为{},{}'.format(a,b)) assert add(a,b)== expect if __name__ == '__main__': pytest.main(['-s','test_4.py'])
标记为失败(xfail)
import pytest data_1 = [[1,2,3], pytest.param(3,4,8,marks=pytest.mark.xfail)] def add(a,b): return a+b @pytest.mark.parametrize("a,b,expect",data_1) def test_pa(a,b,expect): print('测试数据为{},{}'.format(a,b)) assert add(a,b)== expect if __name__ == '__main__': pytest.main(['-s','test_4.py'])
增加可读行:使用参数ids
import pytest data_1 = [ (1, 2, 3), (4, 5, 9) ] ids = ["a:{} + b:{} = expect:{}".format(a, b, expect) for a, b, expect in data_1] def add(a, b): return a + b @pytest.mark.parametrize('a, b, expect', data_1, ids=ids) class TestParametrize(object): def test_parametrize_1(self, a, b, expect): print('\n测试函数1测试数据为\n{}-{}'.format(a, b)) assert add(a, b) == expect def test_parametrize_2(self, a, b, expect): print('\n测试函数2数据为\n{}-{}'.format(a, b)) assert add(a, b) == expect if __name__ == '__main__': pytest.main(['-v','test_4.py']) # -v : 更加详细的输出测试结果
说明:我运行了但是并没有打印出更详细的结果
自定义id做标识
import pytest data_1 = [ pytest.param(1, 2, 3, id="(a+b):pass"), # id的值可以自定义, 只要方便理解每个用例是干什么的即可 pytest.param(4, 5, 10, id="(a+b):fail") ] def add(a, b): return a + b class TestParametrize(object): @pytest.mark.parametrize('a, b, expect', data_1) def test_parametrize_1(self, a, b, expect): assert add(a, b) == expect if __name__ == '__main__': pytest.main(['-v','test_4.py'])
总结
Pytest中实现数据驱动就是如此了
掌握
1.装饰器与测试用例使用单个变量接收多组数据与多个变量接收多个数据的访问方法
2.不同测试数据形式(列表嵌套元组,列表,字典等)时,如何传递数据及访问数据
3.装饰器装饰测试类和测试函数的不同之处:装饰测试类时,类内所有的方法必须接送测试数据,否则会报错,装饰测试函数时比较灵活,如果函数不使用数据就可以不装饰
4.为了输出结果的可读性,可以选择使用ids参数,与测试数据中定义id参数值来标识测试用例
注意
1. 装饰器的第一个参数是一个列表形式的字符串参数"a, b, c" 不能写成"a", "b", "c"
2. ids是个字符串列表,它的长度需要与测试数据列表的长度一致
pytest参数化:pytest.mark.parametrize
https://www.cnblogs.com/peiminer/p/9507111.html
https://www.cnblogs.com/linuxchao/archive/2019/07/25/linuxchao-pytest-parametrize.html
unittest参数化:paramunittest
https://www.cnblogs.com/yoyoketang/p/8856362.html