Pytest参数化-你不知道的使用技巧(一)

上一篇 / 下一篇  2021-05-11 17:07:26 / 个人分类:单元测试

前言
unittest单元测试框架使用DDT进行数据驱动测试,那么身为功能更加强大且更加灵活的Pytest框架怎么可能没有数据驱动的概念呢?其实Pytest是使用@pytest.mark.parametrize装饰器来实现数据驱动测试的,那么今天我们就简单来说说在它是如何进行数据驱动测试的。

装饰测试类
"""
------------------------------------
@Time : 2019/7/25 19:18
@Auth : linux超
@File : test_parametrize.py
@IDE  : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
@QQ   : 28174043@qq.com
@GROUP: 878565760
------------------------------------
"""
import pytest
data_1 = [
    (1, 2, 3),
    (4, 5, 9)
]
def add(a, b):
    return a + b
@pytest.mark.parametrize('a, b, expect', data_1)
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(['-sv'])

输出
collecting ... collected 4 items
test_parametrize.py::TestParametrize::test_parametrize_1[1-2-3] 
测试函数1测试数据为
1-2
PASSED
test_parametrize.py::TestParametrize::test_parametrize_1[4-5-9] 
测试函数1测试数据为
4-5
PASSED
test_parametrize.py::TestParametrize::test_parametrize_2[1-2-3] 
测试函数2数据为
1-2
PASSED
test_parametrize.py::TestParametrize::test_parametrize_2[4-5-9] 
测试函数2数据为
4-5
PASSED
========================== 4 passed in 0.21 seconds ===========================
Process finished with exit code 0

说明
当装饰器装饰测试类时,给数据集合会被传递给给类的所有方法。

装饰测试函数
单个数据
"""
------------------------------------
@Time : 2019/7/25 19:18
@Auth : linux超
@File : test_parametrize.py
@IDE  : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
@QQ   : 28174043@qq.com
@GROUP: 878565760
------------------------------------
"""
import pytest
data = [1, 2]
@pytest.mark.parametrize('a', data)
def test_parametrize(a):
    print('\n被加载测试数据为\n{}'.format(a))
if __name__ == '__main__':
    pytest.main(['-s'])

输出
============================= test session starts =============================
platform win32 -- Python 3.7.2, pytest-4.3.1, py-1.8.0, pluggy-0.9.0
rootdir: E:\CnblogCode\pytest_parametrize, inifile:
plugins: rerunfailures-7.0, metadata-1.8.0, html-1.20.0
collected 2 items
test_parametrize.py 
被加载测试数据为
1
.
被加载测试数据为
2
.
========================== 2 passed in 0.16 seconds ===========================
Process finished with exit code 0

说明
测试用例只需要一个参数时,我们存放数据的列表无序嵌套序列,@pytest.mark.parametrize('a', data)装饰器的第一个参数也只需要一个变量接收列表中的每个元素,第二个参数传递存储数据的列表,那么测试用例需要使用同名的字符串接收测试数据(实例中的a)且列表有多少个元素就会生成并执行多少个测试用例。


TAG: pytest 测试框架

 

评分:0

我来说两句

Open Toolbar