0

Given a test function that has both fixtures and parametrized arguments, how to get a dict of parametrized arguments together with their values? I can access serialized list of values with request.node.name or os.environ.get('PYTEST_CURRENT_TEST'), but this doesn't give the corresponding names of the parameters. PyTest prints them, but I need to access them in a custom error-handling hook.

@pytest.mark.parametrize('a', [False, True])
@pytest.mark.parametrize('b', [1, 2])
def test_foo(request, fixt_y, fixt_z, a, b):  # fixt_y/z are some fixtures
    print(request.node.name)  # e.g., test_foo[0-1-False]
    print(os.environ.get('PYTEST_CURRENT_TEST'))  # e.g., test_file.py::test_foo[0-1-False] (call)

What I want is to somehow get {'a': False, 'b': 1} inside test_foo.

Viacheslav Kroilov
  • 1,561
  • 1
  • 12
  • 23

1 Answers1

3

I am not sure if there is an easier method, but this works

@pytest.mark.parametrize('a', [False, True])
@pytest.mark.parametrize('b', [1, 2])
def test_foo(request, fixt_y, fixt_z, a, b):  # fixt_y/z are some fixtures
    mark_param_names = [
        mark.args[0]
        for mark in reversed(request.node.keywords["pytestmark"])
    ]
    # the params dict below contains the params names and their values
    params = {p: request.getfixturevalue(p) for p in mark_param_names}
    print(request.node.name)  # e.g., test_foo[0-1-False]
    print(os.environ.get('PYTEST_CURRENT_TEST'))  # e.g., test_file.py::test_foo[0-1-False] (call)
hamdanal
  • 477
  • 3
  • 10