bad_coder
bad_coder

Reputation: 12880

How to execute a parameterized fixture for only some of the parameters?

From the official documentation, in the example about parametrizing fixtures:

Parametrizing fixtures

Extending the previous example, we can flag the fixture to create two smtp_connection fixture instances which will cause all tests using the fixture to run twice.

@pytest.fixture(scope="module", params=["smtp.gmail.com", "mail.python.org"])
def smtp_connection(request):

I wrote a parametrized fixture like the above example, but now my problem is I want to use the fixture in a different test function that should only execute once for one of the parameters...Like so:

def my_test_function(smtp_connection)
    # I want this function to execute only once for the first or the second parameter...

So my question is: Can a test function use the fixture and be executed only for some parameters using pytest API? Or is this use case already a mistake and should both the fixture or the test functions be implemented differently in such case? If so, what would conceptually be the correct design alternative?

I am looking for a programmatic solution that doesn't require using command-line flags when I run pytest.

Upvotes: 1

Views: 1895

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16815

You could use indirect fixture parametrization - in this case you would define the parameters you want to use in the test instead of the fixture:

@pytest.fixture(scope="module")
def smtp_connection(request):
    url = request.param
    ...

pytest.mark.parametrize("smtp_connection", ["smtp.gmail.com", "mail.python.org"], indirect=True)
def def my_test_function(smtp_connection):
    ...

pytest.mark.parametrize("smtp_connection", ["smtp.gmail.com"], indirect=True)
def def my_other_test_function(smtp_connection):
    ...

This will parametrize the fixture with each of the parameters you provide in the list for a specific test. You can read the parameter from request.param as shown above.

Of course, if you have many tests that use the same parameters you are probably better off using specific fixtures instead.

Upvotes: 1

Related Questions