PyTest Fixtures & Scope Management (session, module, function)
1Concept
Fixtures (`@pytest.fixture`) provide reusable test setup and teardown. The `scope` parameter controls lifecycle: `function` (default, fresh per test), `class`, `module` (once per file), or `session` (once per entire test run).
2Architecture Diagram
@pytest.fixture(scope="session") ---> DB container initialized ONCE for all tests @pytest.fixture(scope="function") ---> Table cleaned before every individual test
3Code Example
Python 3.12
fixture_sample = '''
import pytest
@pytest.fixture(scope="module")
def database_client():
client = {"connected": True}
yield client # Setup
client["connected"] = False # Teardown after all module tests complete
def test_query(database_client):
assert database_client["connected"] is True
'''
print("=== PyTest Fixture Lifecycle ===")
print(fixture_sample.strip())4Expected Output
=== PyTest Fixture Lifecycle ===
import pytest
@pytest.fixture(scope="module")
def database_client():
client = {"connected": True}
yield client # Setup
client["connected"] = False # Teardown after all module tests complete
def test_query(database_client):
assert database_client["connected"] is True5Key Takeaways
- ✓Code before `yield` is setup; code after `yield` is teardown.
- ✓`autouse=True` executes fixtures automatically without explicit argument passing.
- ✓`conftest.py` defines fixtures shared across all test files in a directory.