Fork me on GitHub

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的所有组合并进行调用。

posted @ 2023-02-16 20:44  流柯  阅读(336)  评论(0编辑  收藏  举报
访客: 浏览: