找回密码
 立即注册

QQ登录

只需一步,快速开始

pytest参数化:@pytest.mark.parametrize详解

2024-11-5 02:09| 发布者: db4d5a85| 查看: 418| 评论: 0

摘要: 目录pytest参数化:@pytest.mark.parametrize下面是一个典范的范例该示例中,只有一组数据是失败的总结pytest参数化:@pytest.mark.parametrize 内置的pytest.mark.parametrize装饰器可以用来对测试函数进行参数化处置
目录

pytest参数化:@pytest.mark.parametrize

内置的pytest.mark.parametrize装饰器可以用来对测试函数进行参数化处置惩罚。

下面是一个典范的范例

检查特定的输入所盼望的输出是否匹配:

  • test_expectation.py
[code]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 [/code]

装饰器@parametrize定义了三组不同的(test_input, expected)数据,test_eval则会使用这三组数据

实行三次:

[code]$ pytest=========================== test session starts ============================platform linux ‐‐ Python 3.x.y, pytest‐4.x.y, py‐1.x.y, pluggy‐0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIR, inifile:collected 3 itemstest_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) == expectedE AssertionError: assert 54 == 42E + where 54 = eval('6*9')test_expectation.py:8: AssertionError==================== 1 failed, 2 passed in 0.12 seconds ====================[/code]

该示例中,只有一组数据是失败的

通常情况下你可以在traceback中看到作为函数参数的input和output。

留意:

你也可以对模块大概class使用参数化的marker来让多个测试函数在不同的测试集下运行。

你也可以对参数会合的某个参数使用mark,比如下面使用了内置的mark.xfail:

  • test_exception.py
[code]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 [/code]

运行结果如下:

[code]$ pytest=========================== test session starts ============================platform linux ‐‐ Python 3.x.y, pytest‐4.x.y, py‐1.x.y, pluggy‐0.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIR, inifile:collected 3 itemstest_expectation.py ..x [100%]=================== 2 passed, 1 xfailed in 0.12 seconds ====================[/code]

之前结果是失败的用例在这里已经被标志为xfailed了。

如果参数化的列表是一个空列表,比如参数是某个函数动态生成的,请参考empty_parameter_set_mark选项。

可以对一个函数使用多个parametrize的装饰器,这样多个装饰器的参数会组合进行调用:

[code]import pytest @pytest.mark.parametrize("x", [0, 1]) @pytest.mark.parametrize("y", [2, 3]) def test_foo(x, y): pass [/code]

这会穷举x和y的全部组合并进行调用。

总结

以上为个人经验,盼望能给大家一个参考,也盼望大家多多支持脚本之家。


来源:https://www.jb51.net/python/328829r2w.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

最新评论

关闭

站长推荐上一条 /6 下一条

QQ|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )|网站地图

GMT+8, 2025-7-1 18:34 , Processed in 0.035173 second(s), 19 queries .

Powered by Mxzdjyxk! X3.5

© 2001-2025 Discuz! Team.

返回顶部