In pytest, when running tests in parallel using pytest-xdist, which fixture scope ensures that a fixture is created once per worker process?
Think about the widest scope that pytest-xdist respects per worker.
The session scope creates the fixture once per worker process when running tests in parallel with pytest-xdist. Other scopes like module or function create fixtures more frequently.
Consider this pytest code run with 2 parallel workers using pytest-xdist:
import pytest
@pytest.fixture(scope='module')
def resource():
print('Setup resource')
yield
print('Teardown resource')
def test_one(resource):
pass
def test_two(resource):
passHow many times will 'Setup resource' be printed?
Remember that each worker runs tests independently and module scope is per module per worker.
With 2 workers, each runs the module's tests once, so the module-scoped fixture setup runs once per worker, totaling 2 times.
You want to assert that a fixture with 'session' scope is created exactly once per worker when running 3 parallel pytest workers.
Which assertion correctly verifies this if setup_count tracks the number of fixture setups?
def test_fixture_count(setup_count): # assert here pass
Each worker runs its own session-scoped fixture instance.
With 3 workers, each creates its own session-scoped fixture, so the total setup count should be 3.
You have a fixture with 'session' scope but notice it runs multiple times when running tests in parallel with pytest-xdist. What is the most likely cause?
Think about how pytest-xdist manages processes.
pytest-xdist runs tests in separate worker processes, each with its own session. So session-scoped fixtures run once per worker, not globally.
You have an expensive setup fixture that you want to share across all parallel pytest workers to avoid repeated setup. Which approach is best?
Think about sharing state beyond process boundaries.
pytest fixtures run per worker process; to share expensive setup, use external shared resources or locks combined with session scope.