Module Scope Fixture in pytest: What It Is and How It Works
module scope fixture is a setup function that runs once per Python module, sharing its result across all tests in that module. It helps save time by avoiding repeated setup for each test function within the same file.How It Works
Imagine you have a toolbox you need for several tasks in the same room. Instead of bringing a new toolbox for each task, you bring it once and use it for all tasks in that room. A module scope fixture works similarly in pytest.
When you mark a fixture with scope='module', pytest runs the fixture setup only once when the first test in that module starts. Then, all tests in that module use the same fixture instance. After all tests finish, pytest runs the fixture teardown once.
This saves time and resources when the setup is expensive or slow, like opening a database connection or preparing a large dataset, because it avoids repeating the setup for every test function.
Example
This example shows a module scope fixture that creates a list once for all tests in the module.
import pytest @pytest.fixture(scope='module') def sample_list(): print('Setup: Creating list') return [1, 2, 3] def test_sum(sample_list): assert sum(sample_list) == 6 def test_len(sample_list): assert len(sample_list) == 3 def test_contains(sample_list): assert 2 in sample_list
When to Use
Use a module scope fixture when you want to share a setup across multiple tests in the same Python file to save time and resources. It is ideal when the setup is costly or slow, such as:
- Opening a database connection once for all tests in a module
- Loading a large configuration or dataset
- Starting a server or service needed by all tests in the module
This scope reduces redundant setup and teardown, making tests faster and more efficient.
Key Points
- A
modulescope fixture runs once per Python module (file). - All tests in the module share the same fixture instance.
- Setup runs before the first test; teardown runs after the last test.
- Helps optimize tests by avoiding repeated expensive setup.
- Defined by adding
scope='module'in the@pytest.fixturedecorator.