[英]Parametrized tests in pytest with varying marks for different test functions
I am currently trying to use pytest's parameterization feature in the following context:我目前正在尝试在以下上下文中使用 pytest 的参数化功能:
I have multiple functions that should be tested with a universal set of test cases.我有多个函数应该用一组通用的测试用例进行测试。 Depending on the tested function, the same test case should either pass or xfail.根据测试的功能,相同的测试用例应该通过或 xfail。 I came up with a silly example to illustrate this:我想出了一个愚蠢的例子来说明这一点:
import pytest
# Functions to test
def sum_int(a, b):
assert isinstance(a, int)
assert isinstance(b, int)
return a + b
def sum_any(a, b):
return a + b
# Universal test cases
TESTCASES = [
"a,b,result", [
(1, 1, 2),
("a", "a", "aa")
]
]
class Tests:
@pytest.mark.parametrize(*TESTCASES, ids=["int_pass", "str_fail"])
def test_sum_int(self, a, b, result):
assert sum_int(a, b) == result
@pytest.mark.parametrize(*TESTCASES, ids=["int_pass", "str_pass"])
def test_sum_any(self, a, b, result):
assert sum_any(a, b) == result
Unfortunately, it seems not to be possible to just pass additional marks (like pytest.mark.xfail(reason=AssertionError)
to parametrize()
like it can be done with IDs.不幸的是,似乎不可能像使用 ID 那样将额外的标记(如pytest.mark.xfail(reason=AssertionError)
传递给parametrize()
。
# Does not work
@pytest.mark.parametrize(*TESTCASES,
ids=["int_pass", "str_fail"],
marks=[None, pytest.mark.xfail(reason=AssertionError)])
def test_sum_int(self, a, b, result):
assert sum_int(a, b) == result
What could be a good way to achieve this?什么是实现这一目标的好方法?
If you are trying to mark only the sum of string test you can do it like this:如果您只想标记字符串测试的总和,您可以这样做:
# Universal test cases
TESTCASES = [
"a,b,result", [
(1, 1, 2),
pytest.mark.xfail(("a", "a", "aa"))
]
]
Have a read here https://docs.pytest.org/en/2.8.7/parametrize.html#:~:text=#%20content%20of%20test_expectation.py在这里阅读https://docs.pytest.org/en/2.8.7/parametrize.html#:~:text=#%20content%20of%20test_expectation.py
I had to discover that the answer to my problem is relatively simple.我不得不发现我的问题的答案相对简单。 The pytest.param
mechanism allows to specify marks for specific test cases: pytest.param
机制允许为特定的测试用例指定标记:
@pytest.mark.parametrize(
TESTCASES[0],
[
pytest.param(*args, marks=marks)
for args, marks
in zip(TESTCASES[1], [[], [pytest.mark.xfail(reason=AssertionError)]])
],
ids=["int_pass", "str_fail"],
)
def test_sum_int(self, a, b, result):
assert sum_int(a, b) == result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.