pytest-retry
pytest-retry is a plugin for Pytest that adds the ability to retry flaky tests, improving the consistency of test suite results. It currently supports Python 3.9+ and pytest 7.0.0+. The library maintains an active release cadence with regular updates.
Warnings
- breaking Behavioral change in `flaky` mark argument fallback in version 1.4.0. Previously, arguments not specified in a `flaky` mark would fall back to default plugin values. From 1.4.0 onwards, unspecified arguments now fall back to your global defaults (e.g., from command line or `pytest.ini`) if specified, before falling back to plugin defaults.
- gotcha Compatibility issues with `pytest-xdist` could lead to `ResourceWarning` messages, especially when using `n > 1` parallel workers.
- gotcha There's another popular plugin, `pytest-rerunfailures`, which provides similar functionality but uses different command-line options (`--reruns`, `--reruns-delay`) and decorator arguments (`reruns`, `reruns_delay`). These two plugins are not compatible and should not be installed together.
- gotcha Older versions of `pytest-retry` (prior to 1.6.2) had an 'Item instantiation error' when used with `pytest 8`.
- gotcha When using `pytest-retry` with other reporting plugins (e.g., `pytest-html`), the default 'retried' outcome name might cause compatibility issues.
- gotcha Global configuration of retries and delays via `pytest.ini` or `pyproject.toml` files was introduced in version 1.5.0. Prior versions only supported command-line arguments for global settings.
Install
-
pip install pytest-retry
Imports
- pytest.mark.flaky
import pytest @pytest.mark.flaky(retries=3, delay=1) def test_something_flaky(): # Test implementation pass
Quickstart
import pytest
import random
@pytest.mark.flaky(retries=2, delay=0.5)
def test_sometimes_fails():
# This test has a 50% chance to fail, simulating flakiness.
# It will retry up to 2 times (3 attempts total) with a 0.5-second delay.
if random.random() < 0.5:
pytest.fail("Simulated intermittent failure")
assert True
# To run this test from your terminal:
# pytest your_test_file.py
# You can also set global retries:
# pytest --retries 2 --retry-delay 0.5 your_test_file.py