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:

  1. 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.

  2. Set autouse=True: In the fixture decorator, set autouse=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
    def setup_fixture(self):
        # Your setup code here
        Author.objects.create(name="Frank Herbert")"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!