0

I have parameterized pytest tests. How to add an additional parameter to the tests that is passed to pytest as a command line argument?

I tried adding an option xyz to the parser and put return the command line argument as a fixture, like so..

conftest.py:

def pytest_addoption(parser):
    parser.addoption(
        "--some_other_option", action="store_true", default=True, help="Skip some tests"
    )
    parser.addoption(
        "--xyz", action="store_true", default=True, help="Test xyz"
    )


@pytest.fixture
def xyz(config):
    return config.getoption('--xyz')

test file:

@pytest.mark.parametrize('arg1, arg2, arg3, arg4, arg5', [
(asdf', 1, 1, 0, [0.64]),
...
])
def test_stuff(arg1, arg2, arg3, arg4, arg5, xyz):
    if xyz:  # only do this if xyz is True
        assert func(arg3) == 42 
    ....

I have also tried it like this.

In both cases, the issue is that pytest returns an error for every test

`E fixture 'config' not found

What am I doing wrong? `

Hauptideal
  • 123
  • 5
  • 1
    Does this answer your question? [How to pass arguments in pytest by command line](https://stackoverflow.com/questions/40880259/how-to-pass-arguments-in-pytest-by-command-line) – Kache May 22 '23 at 16:27

1 Answers1

1

The config object is accessible from the pytest_configure hook (https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.hookspec.pytest_configure). But with request it is enough.

So if you want xyz as a fixture, you could try:

    
@pytest.fixture
def xyz(request):
    return request.config.getoption('--xyz')

  • thanks! when doing it exactly like in your example, it works. I tried this with other names than request before but it ddidn't work - does the name "request" play a critical role here? – Hauptideal May 23 '23 at 12:51
  • 1
    Yes, it is a special fixture initialize by Pytest itself, see https://docs.pytest.org/en/7.1.x/reference/reference.html#request, therefore you have to call it `request`. – Christophe Brun May 23 '23 at 14:31