17

I have a test which currently runs with a single fixture like this:

@pytest.fixture() def foo(): return 'foo' def test_something(foo): # assert something about foo 

Now I am creating a slightly different fixture, say

@pytest.fixture def bar(): return 'bar' 

I need to repeat the exact same test against this second fixture. How can I do that without just copy/pasting the test and changing the parameter name?

2
  • 1
    I couldn't be bothered to figure out the details, but this looks like it might be helpful: docs.pytest.org/en/latest/… Commented Sep 14, 2017 at 16:05
  • @wim That looks like it might work for my purposes. Thanks for the link. Commented Sep 14, 2017 at 16:11

1 Answer 1

17

Beside the test generation, you can do it the "fixture-way" for any number of sub-fixtures applied dynamically. For this, define the actual fixture to be used as a parameter:

@pytest.fixture def arg(request): return request.getfuncargvalue(request.param) 

The define a test with am indirect parametrization (the param name arg and the fixture name arg must match):

@pytest.mark.parametrize('arg', ['foo', 'bar'], indirect=True) def test_me(arg): print(arg) 

Lets also define those fixtures we refer to:

@pytest.fixture def foo(): return 'foo' @pytest.fixture def bar(): return 'bar' 

Observe how nicely parametrized and identified these tests are:

$ pytest test_me.py -s -v -ra collected 2 items test_me.py::test_me[foo] foo PASSED test_me.py::test_me[bar] bar PASSED 
Sign up to request clarification or add additional context in comments.

3 Comments

getfuncargvalue is deprecated. Is there a "modern" way to do this?
getfixturevalue()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.