0
0
PyTesttesting~7 mins

Fixture scope with parallel tests in PyTest

Choose your learning style9 modes available
Introduction

Fixtures help prepare things your tests need. Using fixture scope with parallel tests controls how often setup runs, saving time and avoiding conflicts.

When you want to share a setup like a database connection across multiple tests running at the same time.
When tests run in parallel and you want to avoid running the same setup multiple times.
When you want to clean up resources only once after many tests finish.
When you want to speed up tests by reusing expensive setup steps.
When you want to control if fixtures are created per test, per module, or once for all tests.
Syntax
PyTest
@pytest.fixture(scope='scope_name')
def fixture_name():
    # setup code
    yield resource
    # teardown code

Scope can be 'function' (default), 'class', 'module', or 'session'.

For parallel tests, 'session' scope means fixture runs once per worker process for all tests in that worker.

Examples
This fixture runs before and after each test function.
PyTest
@pytest.fixture(scope='function')
def setup_func():
    print('Setup for each test')
    yield
    print('Teardown for each test')
This fixture runs once before all tests in a module and tears down after all finish.
PyTest
@pytest.fixture(scope='module')
def setup_module():
    print('Setup once per module')
    yield
    print('Teardown once per module')
This fixture runs once for the entire test run, useful for expensive setups.
PyTest
@pytest.fixture(scope='session')
def setup_session():
    print('Setup once per test session')
    yield
    print('Teardown once per session')
Sample Program

This test uses a session-scoped fixture. The setup runs once before all tests in a worker, even if tests run in parallel. Each test uses the same resource.

PyTest
import pytest

@pytest.fixture(scope='session')
def resource():
    print('Setup resource')
    yield 'resource data'
    print('Teardown resource')

@pytest.mark.parametrize('i', range(3))
def test_example(resource, i):
    print(f'Test {i} uses {resource}')
    assert resource == 'resource data'
OutputSuccess
Important Notes

When running tests in parallel (e.g., with pytest-xdist), session-scoped fixtures run once per worker process, not globally.

Use the 'scope' carefully to avoid conflicts or repeated expensive setups.

For truly global fixtures in parallel runs, consider external setup or plugins that support shared fixtures.

Summary

Fixture scope controls how often setup and teardown run.

Session scope runs once per test session, saving time for expensive setups.

In parallel tests, session scope runs once per worker, not globally.