Search code examples
pythonfixturespytest

Autousing pytest fixtures defined in a separate module


I have the following file tree in my project:

...
tests/
    __init__.py
    test_abc.py
...

I have a fixture defined in __init__.py:

@pytest.fixture(autouse=True)
def client():
    return TestClient()

I want to use this fixture in test_abc.py:

from . import client

def test_def():
    client.get(...) # Throws an error

How can I use my autouse fixture in my test methods from another modules without passing an explicit reference to the fixture, or using a pytest decorator?


Solution

  • Autouse is meant for fixtures which do some setup required by all tests, and may or may not return something still useful as a fixture to be used by tests.

    Tests which want to access what is returned by the fixture have to declare the fixture as a parameter, so they can access it. So if your tests want to access the fixture, they have to declare it as a parameter, that's how pytest works. Hope this helps.