When running tests in parallel, why must the order of tests be carefully managed?
Think about what happens if two tests change the same file or database at the same time.
Tests that share resources or state can interfere with each other if run simultaneously. Proper ordering or isolation prevents flaky failures.
Given the following pytest code where two tests write to the same file without synchronization, what is the likely outcome when run with pytest-xdist parallel execution?
import pytest @pytest.mark.parametrize('content', ['A', 'B']) def test_write_file(tmp_path, content): file = tmp_path / 'shared.txt' with open(file, 'a') as f: f.write(content) with open(file) as f: data = f.read() assert content in data
Consider what happens if two tests append to the same file at the same time.
Appending to the same file concurrently can cause race conditions, leading to unpredictable file content and test failures.
Which assertion best verifies that a test run in parallel does not affect the shared resource state?
def test_resource_isolation(shared_resource): # shared_resource is reset before each test shared_resource.modify('test') # What assertion ensures isolation?
Isolation means the resource state should be fresh at test start.
To confirm isolation, the resource state should be the initial state before modification, ensuring no leftover changes from other tests.
Given this pytest code snippet, tests sometimes fail when run with pytest-xdist. What is the most likely cause?
import pytest shared_counter = 0 def increment(): global shared_counter temp = shared_counter temp += 1 shared_counter = temp @pytest.mark.parametrize('n', range(5)) def test_increment(n): increment() assert shared_counter >= n + 1
Think about what happens when multiple tests update the same variable at the same time.
Multiple tests incrementing a shared variable without locks cause race conditions, leading to flaky test results.
Which pytest fixture scope ensures each parallel test worker gets its own fresh resource instance, preventing cross-test interference?
Consider which scope creates a new fixture instance for every test function.
The 'function' scope creates a new fixture instance for each test function, ensuring isolation in parallel runs. Other scopes share instances across multiple tests, risking interference.