pytest-rerunfailures
pytest-rerunfailures is a plugin for pytest that re-runs failed or intermittently failing tests to eliminate flaky failures, improving the reliability of CI/CD pipelines. It is actively maintained with frequent releases, typically every few months, adding new features and ensuring compatibility with the latest Python and pytest versions.
Warnings
- breaking Dropped support for older Python and pytest versions in recent releases. Version 16.1 requires Python 3.10+, and version 16.0 requires pytest 8.0+.
- gotcha Incompatible with `pytest-xdist`'s `--looponfail` flag, `pytest`'s core `--pdb` flag, and the `flaky` plugin. Do not use `pytest-rerunfailures` simultaneously with these. Also, explicitly incompatible with `pytest-rerunclassfailures`.
- gotcha The order of precedence for setting rerun counts is: `@pytest.mark.flaky()` decorator > command-line `--reruns` option > `pytest.ini`/`pyproject.toml` configuration. The `--force-reruns` command-line option can override all other settings.
- gotcha Recovery from hard crashes (e.g., segfaults) using `pytest-xdist` (via the `-n` flag) requires `pytest-xdist >= 2.3.0` and assumes workers and controller are on the same local area network (LAN). This functionality may not operate if this assumption is not met.
- gotcha When a teardown function fails, `pytest-rerunfailures` will generate two reports: one for the test case itself and another for the teardown error. This can sometimes be confusing in the test output.
Install
-
pip install pytest-rerunfailures
Imports
- pytest
import pytest
Quickstart
import pytest
import random
def test_flaky_example():
# This test will randomly fail, demonstrating rerunfailures
if random.choice([True, False, False]): # Higher chance to fail initially
pytest.fail("Simulated flaky failure")
# To run with reruns: pytest --reruns 3 your_test_file.py
# To mark a specific test as flaky:
@pytest.mark.flaky(reruns=2, reruns_delay=1)
def test_another_flaky_example():
if random.choice([True, False]):
pytest.fail("Another flaky failure")
# Example of pytest.ini configuration (add to a file named pytest.ini in your project root):
# [pytest]
# reruns = 2
# reruns_delay = 1
# You can then run: pytest