0
0
PyTesttesting~5 mins

Ordering tests for parallel safety in PyTest

Choose your learning style9 modes available
Introduction

Sometimes tests run at the same time can interfere with each other. Ordering tests helps keep them safe and reliable.

When tests share resources like files or databases and might change data at the same time.
When one test depends on the result or setup of another test.
When running tests in parallel causes failures that don't happen when running them one by one.
When you want to speed up testing but keep tests from breaking each other.
Syntax
PyTest
import pytest

@pytest.mark.order(1)
def test_first():
    pass

@pytest.mark.order(2)
def test_second():
    pass

Use @pytest.mark.order(n) to set the order where n is a number.

Lower numbers run first. Tests without order run after ordered tests.

Examples
This example runs test_setup first, then test_main, and finally test_cleanup.
PyTest
import pytest

@pytest.mark.order(1)
def test_setup():
    assert True

@pytest.mark.order(3)
def test_cleanup():
    assert True

@pytest.mark.order(2)
def test_main():
    assert True
Tests with no order run after tests with order numbers.
PyTest
import pytest

def test_no_order():
    assert True

@pytest.mark.order(1)
def test_ordered():
    assert True
Sample Program

This test suite uses ordering to safely add, check, and clear a shared list. Running in order prevents errors from parallel access.

PyTest
import pytest

shared_resource = []

@pytest.mark.order(1)
def test_add_item():
    shared_resource.append('item')
    assert 'item' in shared_resource

@pytest.mark.order(2)
def test_check_item():
    assert 'item' in shared_resource

@pytest.mark.order(3)
def test_clear_resource():
    shared_resource.clear()
    assert shared_resource == []
OutputSuccess
Important Notes

Ordering tests can help but avoid making tests depend too much on each other.

Use fixtures to share setup and teardown instead of relying only on order.

Parallel test runners like pytest-xdist may still run tests in parallel; ordering helps but does not guarantee isolation.

Summary

Ordering tests helps avoid conflicts when tests share resources.

Use @pytest.mark.order(n) to control test run order.

Keep tests independent when possible for easier maintenance.