'Is there any way to print the pytest parameter names

Whenever pytest is outputting the tests that it has, it always prints out the parameter values, but never the names of the variables.

For example:

PASSED test_create_patient.py::test_create_patient[False-True]

What I would like it to output is:

PASSED test_create_patient.py::test_create_patient[arg1=False-arg2=True]

Is this possible? I have tried various pytest flags like -vvv but nothing seems to work for this. It would be very helpful for debugging purposes.

I've looked into answers like this https://stackoverflow.com/a/18496751/8903959 but I don't understand them.



Solution 1:[1]

Generally, you can use the ids parameter in pytest.mark.parametrize to customize the parameter ids. In your case, this is inconvenient. While ids allows you to provide a custom function to adapt the output, this function only gets the parameter value as argument, not the parameter name, so you cannot use it to compose your wanted output. Instead, you would have to provide a list of ids:

@pytest.mark.parametrize("arg1, arg2", [(False, True), (True, False)],
                         ids=["arg1=False-arg2=True",
                              "arg1=True-arg2=False"])
def test_create_patient(arg1, arg2):
    pass

To avoid this, you can use the hook function pytest_make_parametrize_id instead, which gets both the parameter name and the value. You have to put it in a conftest.py visible to your test. In your case, you can write:

conftest.py

def pytest_make_parametrize_id(config, val, argname):
    return f"{argname}={val}"

and you would get the wanted notation for each test.

If you want to have this notation only for verbose output (say, with the option -vv or more), you can use config.option to check the verbosity and adapt the id accordingly:

conftest.py

def pytest_make_parametrize_id(config, val, argname):
    if config.option.verbose >= 2:  # -vv or -vvv
        return f"{argname}={val}"
    return repr(val)  # the default

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1