pytest-race is a plugin for the pytest testing framework that helps detect and test race conditions in your Python codebase. It introduces a `start_race` fixture, allowing you to easily run a target callable function multiple times concurrently in separate threads. The current version is 0.2.0, with a slow release cadence, last updated in June 2022.
pip install pytest-raceVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use the `start_race` fixture to test a simple race condition involving a global accumulator. The `actual_test_target` function is executed concurrently by multiple threads, and an assertion is used to detect if the race condition leads to unexpected results. The `sleep` call helps simulate conditions where race conditions are more likely to occur.
Ensure that shared resources in your `target` callable are either properly locked/synchronized or designed to be thread-safe. Alternatively, craft your assertions to reflect the non-deterministic but acceptable outcomes of concurrent operations, or to specifically catch the race condition you expect.
Perform thread-safe logging or accumulate results within the `target` callable, and then perform final assertions on the collected data in the main test function (after `start_race` completes).
Design assertions to be robust against expected timing variations, and consider using techniques like `pytest.approx()` for numerical comparisons or implementing retries/waits with timeouts within the target function before making assertions, if appropriate for your use case. Reproduce flaky tests repeatedly to confirm the issue.