How to ‘autouse’ a pytest fixture only within a specific class
In pytest, the autouse
parameter in a fixture automatically applies the fixture
to all tests in the scope where the fixture is defined. However, if you want to
use an autouse
fixture specifically for tests within a particular class, you can
define the fixture within the class itself. Here’s how you can do it:
Define the Fixture Inside the Class: Place the fixture method inside the class where you want it to be automatically used. By doing so, it will be scoped to the class.
Set
autouse=True
: In the fixture decorator, setautouse=True
. This will ensure that the fixture is automatically used for each test method in the class.
Here’s an example to illustrate this:
import logging
import pytest
logger = logging.getLogger(__name__)
class TestClass:
# Define the fixture inside the class
@pytest.fixture(autouse=True)
def setup_fixture(self):
# Your setup code here
Book.objects.create(name="Dune")
Author.objects.create(name="Frank Herbert")
logger.info("Running setup for each test in TestClass")
def test_one(self):
# This test will automatically use the setup_fixture fixture
assert Books.objects.filter(name="Dune")
def test_two(self):
# This test will also automatically use the setup_fixture fixture
assert Author.objects.filter(name="Frank Herbert")
# This test is outside the class and won't use the setup_fixture fixture
def test_outside_class():
assert not Books.objects.filter(name="Dune")
In this example, test_one and test_two will automatically use the setup_fixture fixture, whereas test_outside_class will not. This approach confines the automatic usage of the fixture to the tests within TestClass.
All done!