It is possible to apply a fixture to all of the tests in a hierarchy, even if the tests don't explicitly request a fixture, by passing autouse=True to the @pytest.fixture decorator. This is useful when we need to apply a side-effect before and/or after each test unconditionally.
@pytest.fixture(autouse=True)
def setup_dev_environment():
previous = os.environ.get('APP_ENV', '')
os.environ['APP_ENV'] = 'TESTING'
yield
os.environ['APP_ENV'] = previous
An autouse fixture is applied to all tests which the fixture is available for use with:
- Same module as the fixture
- Same class as the fixture, in the case of a fixture defined by a method
- Tests in the same directory or below, if the fixture is defined in a conftest.py file
In other words, if a test can access an autouse fixture by declaring it in the parameter...