Fixtures help prepare things your tests need. Using fixture scope with parallel tests controls how often setup runs, saving time and avoiding conflicts.
Fixture scope with parallel tests in 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.
@pytest.fixture(scope='function') def setup_func(): print('Setup for each test') yield print('Teardown for each test')
@pytest.fixture(scope='module') def setup_module(): print('Setup once per module') yield print('Teardown once per module')
@pytest.fixture(scope='session') def setup_session(): print('Setup once per test session') yield print('Teardown once per session')
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.
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'
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.
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.