当前位置: 代码网 > it编程>前端脚本>Python > pytest参数化:@pytest.mark.parametrize详解

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

2024年11月03日 Python 我要评论
pytest参数化:@pytest.mark.parametrize内置的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的所有组合并进行调用。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com