pytest参数化:@pytest.mark.parametrize详解
pytest参数化:@pytest.mark.parametrize
内置的pytest.mark.parametrize装饰器可以用来对测试函数进行参数化处理。
下面是一个典型的范例
检查特定的输入所期望的输出是否匹配:
- test_expectation.py
import pytest
@pytest.mark.parametrize("test_input, expected", [("3+5", 8), ("2+4", 6), ("6*9", 42),])
def test_eval(test_input, expected):
assert eval(test_input) == expected
装饰器@parametrize定义了三组不同的(test_input, expected)数据,test_eval则会使用这三组数据
执行三次:
$ pytest
=========================== test session starts ============================
platform linux ‐‐ Python 3.x.y, pytest‐4.x.y, py‐1.x.y, pluggy‐0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
collected 3 items
test_expectation.py ..F [100%]
================================= FAILURES =================================
____________________________ test_eval[6*9‐42] _____________________________
test_input = '6*9', expected = 42
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_eval(test_input, expected):
> assert eval(test_input) == expected
E AssertionError: assert 54 == 42
E + where 54 = eval('6*9')
test_expectation.py:8: AssertionError
==================== 1 failed, 2 passed in 0.12 seconds ====================
该示例中,只有一组数据是失败的
通常情况下你可以在traceback中看到作为函数参数的input和output。
注意:
你也可以对模块或者class使用参数化的marker来让多个测试函数在不同的测试集下运行。
你也可以对参数集中的某个参数使用mark,比如下面使用了内置的mark.xfail:
- test_exception.py
import pytest
@pytest.mark.parametrize("test_input, expected", [("3+5", 8), ("2+4", 6), ("6*9", 42, marks=pytest.mark.xfail),])
def test_eval(test_input, expected):
assert eval(test_input) == expected
运行结果如下:
$ pytest
=========================== test session starts ============================
platform linux ‐‐ Python 3.x.y, pytest‐4.x.y, py‐1.x.y, pluggy‐0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
collected 3 items
test_expectation.py ..x [100%]
=================== 2 passed, 1 xfailed in 0.12 seconds ====================
之前结果是失败的用例在这里已经被标记为xfailed了。
如果参数化的列表是一个空列表,比如参数是某个函数动态生成的,请参考empty_parameter_set_mark选项。
可以对一个函数使用多个parametrize的装饰器,这样多个装饰器的参数会组合进行调用:
import pytest
@pytest.mark.parametrize("x", [0, 1])
@pytest.mark.parametrize("y", [2, 3])
def test_foo(x, y):
pass
这会穷举x和y的所有组合并进行调用。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Python pip通过requirements.txt 文件安装依赖
requirements.txt是定义项目依赖的python包,可通过工具生成,本文主要介绍了Python pip通过requirements.txt文件安装依赖,具有一定的参考价值,感兴趣的可以了解一下2024-03-03
python使用 multiprocessing 多进程处理批量数据的示例代码
这篇文章主要介绍了使用 multiprocessing 多进程处理批量数据的示例代码,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-09-09
python email smtplib模块发送邮件代码实例
本篇文章给大家分享了python email smtplib模块发送邮件的相关代码分享,有需要的朋友参考学习下。2018-04-04


最新评论