How to Use autouse Fixture in pytest for Automatic Setup
In pytest, use
autouse=True in a fixture to make it run automatically for tests without needing to be explicitly requested. This is useful for setup or teardown code that should apply to many or all tests in a module or session.Syntax
The autouse parameter in a pytest fixture makes the fixture run automatically for tests in its scope without needing to be passed as an argument.
Key parts:
@pytest.fixture(autouse=True): Decorator to mark the fixture as automatic.scope: Defines how often the fixture runs (e.g.,function,module,session).- The fixture function contains setup or teardown code.
python
@pytest.fixture(autouse=True, scope='function') def my_fixture(): # setup code here yield # teardown code here
Example
This example shows a fixture with autouse=True that prints messages before and after each test automatically, without the tests needing to mention the fixture.
python
import pytest @pytest.fixture(autouse=True) def auto_setup(): print("Setup before test") yield print("Teardown after test") def test_one(): print("Running test_one") assert True def test_two(): print("Running test_two") assert True
Output
Setup before test
Running test_one
Teardown after test
Setup before test
Running test_two
Teardown after test
Common Pitfalls
Common mistakes when using autouse fixtures include:
- Forgetting that the fixture runs for every test in its scope, which can slow tests if the setup is heavy.
- Using
autouse=Trueunintentionally, causing unexpected side effects in tests. - Not specifying the correct
scope, leading to repeated setup or teardown when not needed.
Always keep autouse fixtures simple and fast to avoid slowing down your test suite.
python
import pytest # Wrong: heavy setup runs before every test @pytest.fixture(autouse=True) def heavy_setup(): print("Heavy setup") yield # Right: limit scope to module to run once per module @pytest.fixture(autouse=True, scope='module') def module_setup(): print("Module setup") yield
Quick Reference
Summary tips for using autouse fixtures:
- Use
autouse=Trueto run fixtures automatically without explicit test arguments. - Set
scopewisely:function(default),module, orsession. - Keep autouse fixtures lightweight to avoid slowing tests.
- Use for common setup/teardown like database connections, environment setup, or mocks.
Key Takeaways
Use @pytest.fixture(autouse=True) to run setup code automatically for tests without explicit calls.
Choose the fixture scope carefully to control how often the fixture runs.
Keep autouse fixtures simple and fast to avoid slowing down your tests.
Autouse fixtures are great for common setup or teardown shared by many tests.
Avoid unintended side effects by using autouse fixtures only when necessary.