0
0
PyTesttesting~10 mins

Fixture scope with parallel tests in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test demonstrates how a pytest fixture with module scope behaves when running tests in parallel. It verifies that the fixture is created once per module and shared across parallel test functions.

Test Code - pytest
PyTest
import pytest

@pytest.fixture(scope="module")
def resource():
    print("Setup resource")
    yield "resource_data"
    print("Teardown resource")

@pytest.mark.parametrize("input", [1, 2])
def test_parallel(resource, input):
    assert resource == "resource_data"
    assert input in [1, 2]
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test runner starts and collects testsTwo test cases found: test_parallel with input=1 and input=2-PASS
2Pytest initializes fixture 'resource' with scope='module'Fixture setup prints 'Setup resource'Fixture resource is created once for the modulePASS
3Tests run in parallel threads/processes for input=1 and input=2Both tests receive the same fixture instance 'resource_data'Each test asserts resource == 'resource_data' and input in [1, 2]PASS
4After all tests complete, fixture teardown runsFixture teardown prints 'Teardown resource'Fixture teardown happens once after all testsPASS
Failure Scenario
Failing Condition: Fixture is not shared properly and recreated for each test in parallel causing inconsistent state
Execution Trace Quiz - 3 Questions
Test your understanding
How many times is the fixture 'resource' set up when running these tests in parallel?
AOnce per test parameter
BOnce for the whole module
COnce per test function
DOnce per test thread
Key Result
Using a fixture with module scope in pytest ensures the resource is created once and shared across parallel tests in the same module, improving efficiency and consistency.