0
0
PyTesttesting~10 mins

Flaky test detection and retry in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks a function that sometimes fails randomly. It uses retry to run the test again if it fails, to detect flaky behavior and pass if any retry succeeds.

Test Code - pytest
PyTest
import random
import pytest

@pytest.mark.flaky(reruns=2, reruns_delay=1)
def test_random_flaky_behavior():
    value = random.choice([True, False])
    assert value is True, "Random failure to simulate flakiness"
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsPytest test runner initializes and prepares to run test_random_flaky_behavior-PASS
2Test executes first run: random.choice returns FalseTest function runs, random value is Falseassert value is TrueFAIL
3Pytest detects failure and triggers retry after 1 second delayWaiting 1 second before retrying test-
4Test executes second run: random.choice returns TrueTest function runs, random value is Trueassert value is TruePASS
5Test passes due to successful retryTest marked as PASSED in test report-PASS
Failure Scenario
Failing Condition: All retries fail with random value False
Execution Trace Quiz - 3 Questions
Test your understanding
What causes the test to retry in this example?
AThe test passed on the first run
BThe test was skipped
CThe test failed an assertion on the first run
DThe test timed out
Key Result
Using retries helps detect flaky tests by allowing them to pass if they succeed on a retry, reducing false failures in test reports.