我的参数决定了我的参数化 pytest 的名称。我将使用一些随机参数进行这些测试。为了使 junit 中的报告名称不会混乱,我想为每个参数化测试创建一个静态名称。
可以吗?
JUnit 似乎有一个参数:更改参数化测试的名称
class TestMe:
@pytest.mark.parametrize(
("testname", "op", "value"),
[
("testA", "plus", "3"),
("testB", "minus", "1"),
]
)
def test_ops(self, testname, op, value):
我尝试覆盖
request.node.name
但是我只能在测试执行期间重命名它。
我几乎肯定我要么需要编写一个插件,要么需要一个固定装置。您认为解决这个问题的最佳方法是什么?
您正在寻找
ids
的
pytest.mark.parametrize
参数:
字符串 id 列表或可调用列表。如果是字符串,则每一个都是对应的 到 argvalues,以便它们成为测试 id 的一部分。如果可调用,则 应该采用一个参数(单个参数值)并返回一个字符串或 返回无。
你的代码看起来像这样
@pytest.mark.parametrize(
("testname", "op", "value"),
[
("testA", "plus", "3"),
("testB", "minus", "1"),
],
ids=['testA id', 'testB id']
)
def test_industry(self, testname, op, value):
您还可以使用 pytest 参数化包装器:https://github.com/singular-labs/parametrization 或在 pypi 上
pip install pytest-parametrization
你的代码看起来像:
from parametrization import Parametrization
class TestMe:
@Parametrization.autodetect_parameters()
@Parametrization.case(name="testA", op='plus', value=3)
@Parametrization.case(name="testB", op='minus', value=1)
def test_ops(self, op, value):
...
等于:
class TestMe:
@pytest.mark.parametrize(
("op", "value"),
[
("plus", "3"),
("minus", "1"),
],
ids=['testA', 'testB']
)
def test_ops(self, op, value):
...
如果您使用自己的自定义类进行参数化,我发现继承
str
类很有用。这样你就可以在课堂上控制ID
,而不需要每次都重复ids=str
。
class TestMode(str):
__test__ = False
def __new__(cls, name: str, op: str, value: int):
obj = super().__new__(cls, name)
obj.name = name
obj.op = op
obj.value = value
...
return obj
M1 = TestMode("M1", "plus", 3)
M2 = TestMode("M1", "minus", 1)
@pytest.mark.parametrize("mode", (M1, M2))
def test_good_exbytes_fail_over(mode: TestMode):
pass