Verify tests run in correct order to avoid parallel execution conflicts
Preconditions (3)
✅ Expected Result: Tests run in the specified order without resource conflicts or failures caused by parallel execution
Jump into concepts and practice - no test required
import pytest @pytest.mark.order(1) def test_setup(): global resource resource = [] resource.append('setup done') assert 'setup done' in resource @pytest.mark.order(2) def test_action(): resource.append('action done') assert resource == ['setup done', 'action done'] @pytest.mark.order(3) def test_cleanup(): resource.clear() assert resource == [] # To run tests in parallel use: # pytest -n 3 --dist=loadscope
This script uses the pytest-order plugin to control the order of test execution explicitly. The @pytest.mark.order decorator sets the order: test_setup runs first, test_action second, and test_cleanup last.
The tests share a global resource list to simulate shared state. Each test asserts the expected state to ensure no conflicts occur.
Running with pytest -n 3 enables parallel execution with 3 workers. The ordering ensures tests do not run out of sequence, preventing race conditions.
This approach demonstrates how to safely order tests when running in parallel to avoid conflicts.
Now add data-driven testing with 3 different resource states to verify ordering safety
@pytest.mark.order(n) where n is the order number.@pytest.mark.order(3).import pytest
@pytest.mark.order(2)
def test_second():
assert True
@pytest.mark.order(1)
def test_first():
assert True
import pytest
@pytest.mark.order(1)
def test_write_db():
# writes data
assert True
@pytest.mark.order(2)
def test_read_db():
# reads data
assert True