Class Scope Fixture in pytest: What It Is and How It Works
class scope fixture in pytest is a setup function that runs once for all tests inside a test class. It helps share setup and cleanup code efficiently across multiple test methods within the same class.How It Works
Imagine you have a group of tests inside a class, like a team working on related tasks. A class scope fixture sets up something once for the whole team before any test runs, and cleans it up after all tests finish. This saves time because you don’t repeat the setup for each test.
In pytest, when you mark a fixture with scope='class', pytest runs that fixture once before the first test method in the class and tears it down after the last test method. This is like preparing a shared workspace for the whole team instead of setting it up for each member individually.
Example
This example shows a class scope fixture that creates a resource once for all tests in the class.
import pytest @pytest.fixture(scope='class') def resource(): print('\nSetup resource') yield {'data': 123} print('\nTeardown resource') class TestExample: def test_one(self, resource): assert resource['data'] == 123 def test_two(self, resource): assert resource['data'] > 100
When to Use
Use a class scope fixture when multiple tests in the same class need the same setup that is expensive or time-consuming to create. For example, opening a database connection or preparing a test file once for all tests in that class.
This approach speeds up tests and keeps your code clean by avoiding repeated setup and teardown for each test method.
Key Points
- A
classscope fixture runs once per test class. - It shares setup and teardown for all tests in that class.
- Helps improve test speed and organization.
- Use it for expensive or common setup tasks.