简体   繁体   English

覆盖 pytest 参数化函数名称

[英]Override a pytest parameterized functions name

My parameters determine the name of my parameterized pytest.我的参数决定了我的参数化 pytest 的名称。 I will be using a some randomized params for these tests.我将使用一些随机参数进行这些测试。 In order for my reporting names in junit to not get messed up, I'd like to create a static name for each parameterized test.为了让我在 junit 中的报告名称不被弄乱,我想为每个参数化测试创建一个静态名称。

Is it possible?有可能吗?

JUnit seems to have a parameter: Changing names of parameterized tests JUnit 似乎有一个参数: 更改参数化测试的名称

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

I tried overwriting request.node.name however I can only rename it during test execution.我尝试覆盖request.node.name但是我只能在测试执行期间重命名它。

I'm almost positive I either need to write a plugin or a fixture.我几乎肯定我需要编写插件或夹具。 What do you think would be the best way to go about this?你认为最好的方法是什么?

You're looking for the ids argument ofpytest.mark.parametrize :您正在寻找pytest.mark.parametrizeids参数:

list of string ids, or a callable.字符串 ID 列表或可调用对象。 If strings, each is corresponding to the argvalues so that they are part of the test id.如果是字符串,则每个都对应于 argvalues,因此它们是测试 ID 的一部分。 If callable, it should take one argument (a single argvalue) and return a string or return None .如果可调用,它应该接受一个参数(单个 argvalue)并返回一个字符串或返回None

Your code would look like你的代码看起来像

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

you can also use pytest parametrize wrapper from: https://github.com/singular-labs/parametrization or on pypi您还可以使用来自以下位置的 pytest 参数包装器: https : //github.com/singular-labs/parametrization或 pypi

pip install pytest-parametrization

your code would look like:您的代码如下所示:

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):
        ...

which is equals to:这等于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM