覆盖 pytest 参数化函数名称

Override a pytest parameterized functions name

我的参数决定了我的参数化 pytest 的名称。我将为这些测试使用一些随机参数。为了不让我在 junit 中的报告名称混乱,我想为每个参数化测试创建一个静态名称。

可能吗?

JUnit 好像有一个参数:Changing names of parameterized tests

class TestMe:
    @pytest.mark.parametrize(
        ("testname", "op", "value"),
        [
            ("testA", "plus", "3"),
            ("testB", "minus", "1"),
        ]
    )
    def test_ops(self, testname, op, value):

我尝试覆盖 request.node.name 但是我只能在测试执行期间重命名它。

我几乎可以肯定,我要么需要编写一个插件,要么需要一个固定装置。您认为解决此问题的最佳方法是什么?

您正在查找 pytest.mark.parametrizeids 参数:

list of string ids, or a callable. If strings, each is corresponding to the argvalues so that they are part of the test id. If callable, it should take one argument (a single argvalue) and return a string or return None.

你的代码看起来像

@pytest.mark.parametrize(
    ("testname", "op", "value"),
    [
        ("testA", "plus", "3"),
        ("testB", "minus", "1"),
    ],
    ids=['testA id', 'testB id']
)
def test_industry(self, testname, op, value):

您还可以使用来自 https://github.com/singular-labs/parametrization 或 pypi

的 pytest 参数化包装器
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):
        ...