Naming a fixture is the most straight-forward way to use fixtures. However, it also requires that we have to add the fixture name to every test that we want to use the fixture.
There are times when we want something to happen before every test, and the test itself doesn’t really need to know about it. For that, we can use autouse
.
If you add autouse=True
as a parameter to @pytest.fixture()
, then all tests that have access to this fixture will use the fixture.
That should be pretty clear with the name.
However, it can be surprising, as there’s no indication at the point of test definition that a fixture will be called.
Still, it’s a pretty useful feature at times.
An autouse example
Let’s change our simple example to use autouse
:
# test_autouse.py
import pytest
@pytest.fixture(autouse=True)
def before():
print('\nbefore each test')
def test_1():
print('test_1()')
def test_2():
print('test_2()')
If we were to run the following test file, the output would look just like the previous test run:
$ pytest -s test_autouse.py
=========== test session starts ============
collected 2 items
test_autouse.py
before each test
test_1()
.
before each test
test_2()
.
============ 2 passed in 0.04s =============
However, that’s a pretty silly example
A better example for autouse
Let’s say we want to note the start and end time of each test.
We can do that with a fixure.
# test_autouse_header.py
import pytest
from datetime import datetime
def format_time():
return datetime.now().strftime("%H:%M:%S")
@pytest.fixture(scope="function", autouse=True)
def func_header(request):
name = request.function.__name__
print('\n-----------------')
print(f'{name} started: {format_time()}')
yield
print(f'\n{name} ended: {format_time()}')
print('-----------------')
def test_1():
...
def test_2():
...
Now, when we run it, we can see the start and end time.
$ pytest -s test_autouse_header.py
=========== test session starts ============
collected 2 items
test_autouse_header.py
-----------------
test_1 started: 21:32:24
.
test_1 ended: 21:32:24
-----------------
-----------------
test_2 started: 21:32:24
.
test_2 ended: 21:32:24
-----------------
============ 2 passed in 0.04s =============
This post is part of a series on pytest fixtures
- pytest fixtures nuts and bolts
- pytest xunit-style fixtures
- Basic pytest fixtures example
- Using pytest fixtures by naming them
- Using pytest autouse fixtures - this post
- Using pytest fixtures with mark.usefixtures
- pytest fixture return value
- pytest fixture teardown
- pytest fixture scope
- Parametrizing pytest fixtures with param
- Using multiple pytest fixtures
- Modularity: pytest fixtures using other fixtures
- pytest session scoped fixtures
- Mixing pytest fixture scope