36

My parameters determine the name of my parameterized 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.

Is it possible?

JUnit seems to have a parameter: 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):

I tried overwriting request.node.name however I can only rename it during test execution.

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?

Community
  • 1
  • 1
SomeGuyOnAComputer
  • 5,414
  • 6
  • 40
  • 72

2 Answers2

62

You're looking for the ids argument of pytest.mark.parametrize:

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.

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):
MatthewG
  • 8,583
  • 2
  • 25
  • 27
vaultah
  • 44,105
  • 12
  • 114
  • 143
  • How would I go about addressing the individual test cases `pytest -k test_industry[testA id]` doesn't work... – orange Feb 07 '20 at 03:00
  • 1
    or use a lambda function to generate some IDs `ids=lambda t: str(t).lstrip()[0:8],` – Jos Verlinde Jul 06 '21 at 13:29
  • 1
    Doc examples using `ids` (`pytest.mark.parametrize`) and `id` (`pytest.param`) parameters -- https://docs.pytest.org/en/latest/example/parametrize.html#different-options-for-test-ids – Ian Thompson Jan 03 '23 at 16:11
10

you can also use pytest parametrize wrapper from: https://github.com/singular-labs/parametrization or on 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):
        ...
netanelrevah
  • 337
  • 4
  • 12