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

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

一组数据
"""
------------------------------------
@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, 3],
    [4, 5, 9]
]  # 列表嵌套列表
# data_tuple = [
#     (1, 2, 3),
#     (4, 5, 9)
# ]  # 列表嵌套元组
@pytest.mark.parametrize('a, b, expect', data)
def test_parametrize_1(a, b, expect):  # 一个参数接收一个数据
    print('\n测试数据为\n{},{},{}'.format(a, b, expect))
    actual = a + b
    assert actual == expect
@pytest.mark.parametrize('value', data)
def test_parametrize_2(value):  # 一个参数接收一组数据
    print('\n测试数据为\n{}'.format(value))
    actual = value[0] + value[1]
    assert actual == value[2]
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 4 items
test_parametrize.py 
测试数据为
1,2,3
.
测试数据为
4,5,9
.
测试数据为
[1, 2, 3]
.
测试数据为
[4, 5, 9]
.
========================== 4 passed in 0.17 seconds ===========================
Process finished with exit code 0

说明
测试用例需要多个数据时,我们可以使用嵌套序列(嵌套元组&嵌套列表)的列表来存放测试数据。
装饰器@pytest.mark.parametrize()可以使用单个变量接收数据,也可以使用多个变量接收,同样,测试用例函数也需要与其保持一致。
当使用单个变量接收时,测试数据传递到测试函数内部时为列表中的每一个元素或者小列表,需要使用索引的方式取得每个数据。
当使用多个变量接收数据时,那么每个变量分别接收小列表或元组中的每个元素
列表嵌套多少个多组小列表或元组,测生成多少条测试用例。
图解对应关系:

TAG: pytest 测试框架

 

评分:0

我来说两句

Open Toolbar