How can I alias a pytest fixture?

Viewed 464

I have a few pytest fixtures I use from third-party libraries and sometimes their names are overly long and cumbersome. Is there a way to create a short alias for them?

For example: the django_assert_max_num_queries fixture from pytest-django. I would like to call this max_queries in my tests.

1 Answers

You cannot just add an alias in the form of

max_queries = django_assert_max_num_queries

because fixtures are looked up by name at run-time and not imported (and even if they can be imported in some cases, this is not recommended).

But you can always write your own fixture that just yields another fixture:

@pytest.fixture
def max_queries(django_assert_max_num_queries):
    yield django_assert_max_num_queries

Done this way, max_queries will behave exactly the same as django_assert_max_num_queries.
Note that you should use yield and not return, to make sure that the control is returned to the fixture.

Related