0
0
PyTesttesting~15 mins

Ordering tests for parallel safety in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify tests run in correct order to avoid parallel execution conflicts
Preconditions (3)
Step 1: Create three test functions: test_setup, test_action, test_cleanup
Step 2: Mark test_setup to run first, test_cleanup to run last
Step 3: Run tests in parallel using pytest-xdist with 3 workers
Step 4: Observe the order of test execution and resource conflicts
✅ Expected Result: Tests run in the specified order without resource conflicts or failures caused by parallel execution
Automation Requirements - pytest
Assertions Needed:
Verify test_setup runs before test_action
Verify test_cleanup runs after test_action
Verify no test fails due to resource conflicts
Best Practices:
Use pytest-ordering or pytest-dependency to control test order
Avoid shared mutable state between tests
Use fixtures with proper scope to manage setup and cleanup
Use explicit waits or locks if needed to prevent race conditions
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Not controlling test order when tests share state
Using global variables without proper synchronization
Assuming tests run sequentially by default
Bonus Challenge

Now add data-driven testing with 3 different resource states to verify ordering safety

Show Hint