Detect flaky test and retry on failure using pytest
Preconditions (2)
β
Expected Result: The flaky test retries up to 3 times on failure and passes if any retry succeeds; otherwise, it fails after all retries.
Jump into concepts and practice - no test required
import random import pytest @pytest.mark.flaky(reruns=3, reruns_delay=1) def test_flaky_behavior(): # Simulate flaky behavior: 50% chance to fail assert random.choice([True, False]), "Random failure to simulate flakiness"
This test uses the @pytest.mark.flaky decorator from the pytest-rerunfailures plugin to retry the test up to 3 times if it fails.
The test function test_flaky_behavior randomly fails half the time by asserting a random boolean.
If the test fails, pytest automatically retries it up to 3 times with a 1-second delay between retries.
This approach cleanly separates retry logic from test logic and uses a well-supported plugin.
Now add data-driven testing with 3 different flaky scenarios using pytest parametrize
@pytest.mark.flaky(reruns=N)?@pytest.mark.flaky(reruns=N)@pytest.mark.flaky with parameter reruns to specify retry count.@pytest.mark.flaky(reruns=3), which is the correct syntax for retrying 3 times.import pytest
@pytest.mark.flaky(reruns=2)
def test_random():
import random
assert random.choice([True, False])import pytest
@pytest.mark.flaky(rerun=3)
def test_example():
assert Falsereruns, not rerun.rerun is ignored by pytest, so no retries happen despite failures.