覆盖pytest参数化函数名称

Som*_*ter 13 python rename parameterized fixtures pytest

我的参数确定了参数化pytest的名称.我将使用一些随机化的参数进行这些测试.为了使我在junit中的报告名称不被搞砸,我想为每个参数化测试创建一个静态名称.

可能吗?

JUnit似乎有一个参数:更改参数化测试的名称

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

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

我几乎肯定我需要写一个插件或夹具.您认为最好的方法是什么?

vau*_*tah 15

你正在寻找以下ids论点pytest.mark.parametrize:

字符串ID列表或可调用字符串.如果字符串,则每个字符串对应于argvalues,以便它们是测试ID的一部分.如果是可调用的,它应该采用一个参数(单个argvalue)并返回一个字符串或返回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):
Run Code Online (Sandbox Code Playgroud)


net*_*vah 10

您还可以使用 pytest 参数化包装器: https: //github.com/singular-labs/parametrization或在 pypi 上

pip install pytest-parametrization
Run Code Online (Sandbox Code Playgroud)

你的代码看起来像:

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):
        ...
Run Code Online (Sandbox Code Playgroud)

这等于:

class TestMe:
    @pytest.mark.parametrize(
        ("op", "value"),
        [
            ("plus", "3"),
            ("minus", "1"),
        ],
        ids=['testA', 'testB']
    )
    def test_ops(self, op, value):
        ...
Run Code Online (Sandbox Code Playgroud)