Session Scope Fixture in pytest: What It Is and How It Works
pytest, a session scope fixture is a setup function that runs once per test session, sharing its result across all tests. It helps save time by initializing resources only once for all tests instead of repeating setup for each test.How It Works
A session scope fixture in pytest runs only once when the entire test session starts. Imagine you are preparing coffee for a group of friends. Instead of making a new cup for each friend, you make one big pot and share it with everyone. Similarly, a session scope fixture creates a resource once and shares it with all tests.
This fixture stays alive until all tests finish, then it cleans up. This saves time and resources, especially when setup is slow or expensive, like connecting to a database or starting a server.
Example
This example shows a session scope fixture that creates a list once and shares it with two tests.
import pytest @pytest.fixture(scope="session") def shared_list(): print("Setup: Creating list") return [1, 2, 3] def test_sum(shared_list): assert sum(shared_list) == 6 def test_length(shared_list): assert len(shared_list) == 3
When to Use
Use session scope fixtures when you have setup steps that are costly or slow and can be shared safely across all tests. Examples include:
- Opening a database connection once for all tests
- Starting a web server or API service once
- Loading large test data or configuration files
This reduces test time and avoids repeated setup and teardown, making your tests faster and more efficient.
Key Points
- Session scope means the fixture runs once per test session.
- Its result is shared across all tests that use it.
- It is useful for expensive or slow setup tasks.
- Cleanup happens after all tests finish.