Bird
Raised Fist0
Testing Fundamentalstesting~15 mins

Flaky test management in Testing Fundamentals - Build an Automation Script

Choose your learning style10 modes available
Detect and handle flaky test in a simple test suite
Preconditions (2)
Step 1: Run the test suite 5 times in a row without changing the code
Step 2: Record the pass or fail result of each test in each run
Step 3: Identify any test that fails in some runs but passes in others as flaky
Step 4: Mark the flaky test in the test report
Step 5: Rerun the flaky test separately 3 more times to confirm flakiness
Step 6: Log the flaky test details for further investigation
✅ Expected Result: The flaky test is detected by inconsistent pass/fail results across runs, marked clearly in the report, and rerun to confirm flakiness
Automation Requirements - pytest
Assertions Needed:
Verify test results are recorded for each run
Verify flaky test is identified by inconsistent results
Verify flaky test is marked in the report
Best Practices:
Use pytest fixtures to run tests multiple times
Use logging to record test results
Separate flaky test detection logic from test logic
Avoid hardcoding test names; use test metadata
Use clear assertion messages
Automated Solution
Testing Fundamentals
import pytest
import logging

logging.basicConfig(level=logging.INFO, format='%(message)s')

# Simulated flaky test function
import random

def flaky_test():
    # Randomly pass or fail
    return random.choice([True, False])

@pytest.fixture(scope='module')
def run_flaky_test_multiple_times():
    results = []
    for _ in range(5):
        result = flaky_test()
        results.append(result)
        logging.info(f'Run {_ + 1}: {"PASS" if result else "FAIL"}')
    return results


def test_detect_flaky(run_flaky_test_multiple_times):
    results = run_flaky_test_multiple_times
    assert len(results) == 5, "Should have 5 test run results"
    # Check if results are inconsistent
    if all(results) or not any(results):
        flaky = False
    else:
        flaky = True
    logging.info(f'Flaky detected: {flaky}')
    assert flaky, "Test should be detected as flaky due to inconsistent results"

    # Rerun flaky test 3 more times to confirm
    rerun_results = []
    for i in range(3):
        result = flaky_test()
        rerun_results.append(result)
        logging.info(f'Rerun {i + 1}: {"PASS" if result else "FAIL"}')

    # Confirm flakiness if rerun results also inconsistent
    if all(rerun_results) or not any(rerun_results):
        rerun_flaky = False
    else:
        rerun_flaky = True
    logging.info(f'Flaky confirmed on rerun: {rerun_flaky}')
    assert rerun_flaky, "Flaky test should be confirmed on rerun"

This script uses pytest to automate flaky test detection.

The flaky_test function simulates a test that randomly passes or fails.

The fixture run_flaky_test_multiple_times runs this test 5 times and logs results.

The test test_detect_flaky checks if results are inconsistent, marking the test as flaky if so.

It then reruns the flaky test 3 more times to confirm flakiness.

Assertions verify the number of runs, flaky detection, and confirmation.

Logging helps track each run's outcome for clarity.

Common Mistakes - 5 Pitfalls
Using fixed pass/fail results instead of random to simulate flakiness
Hardcoding test names or results in detection logic
Not rerunning tests to confirm flakiness
Using print statements instead of logging
Mixing flaky detection logic inside test logic
Bonus Challenge

Now add data-driven testing with 3 different flaky test functions having different flaky behaviors

Show Hint

Practice

(1/5)
1. What is a flaky test in software testing?
easy
A. A test that always passes successfully
B. A test that sometimes passes and sometimes fails without code changes
C. A test that is never executed
D. A test that always fails due to a bug

Solution

  1. Step 1: Understand flaky test behavior

    A flaky test is one that shows inconsistent results, passing or failing randomly without changes in the code.
  2. Step 2: Compare options to definition

    Only A test that sometimes passes and sometimes fails without code changes describes this behavior correctly; others describe consistent outcomes or unrelated cases.
  3. Final Answer:

    A test that sometimes passes and sometimes fails without code changes -> Option B
  4. Quick Check:

    Flaky test = random pass/fail [OK]
Hint: Flaky tests fail unpredictably without code changes [OK]
Common Mistakes:
  • Thinking flaky tests always fail
  • Confusing flaky tests with skipped tests
  • Assuming flaky tests are due to code bugs only
2. Which of the following is the correct way to mark a flaky test in Python using pytest?
easy
A. @pytest.mark.flaky
B. @pytest.flaky()
C. @flaky_test
D. @pytest.mark.flaky(reruns=3)

Solution

  1. Step 1: Recall pytest flaky test marking syntax

    Pytest uses decorators with @pytest.mark.flaky and parameters like reruns to mark flaky tests.
  2. Step 2: Identify correct syntax among options

    @pytest.mark.flaky(reruns=3) correctly uses @pytest.mark.flaky(reruns=3) to rerun flaky tests up to 3 times.
  3. Final Answer:

    @pytest.mark.flaky(reruns=3) -> Option D
  4. Quick Check:

    pytest flaky mark = @pytest.mark.flaky(reruns=3) [OK]
Hint: Look for decorator with reruns parameter in pytest [OK]
Common Mistakes:
  • Using incorrect decorator syntax
  • Missing reruns parameter for flaky tests
  • Confusing pytest.mark with other decorators
3. Consider this pseudocode for a flaky test management system:
tests = ['testA', 'testB', 'testC']
flaky_tests = set()

for test in tests:
    result = run_test(test)
    if result == 'fail':
        flaky_tests.add(test)

print(sorted(flaky_tests))
If run_test('testA') returns 'pass', run_test('testB') returns 'fail', and run_test('testC') returns 'fail', what will be printed?
medium
A. ['testB', 'testC']
B. ['testA', 'testB', 'testC']
C. ['testA']
D. []

Solution

  1. Step 1: Analyze test results and flaky test additions

    Only tests with 'fail' results are added to flaky_tests set: testB and testC.
  2. Step 2: Sort and print flaky_tests

    Sorted flaky_tests will be ['testB', 'testC'].
  3. Final Answer:

    ['testB', 'testC'] -> Option A
  4. Quick Check:

    Failed tests = ['testB', 'testC'] [OK]
Hint: Add only failed tests to flaky set, then sort [OK]
Common Mistakes:
  • Including passed tests in flaky list
  • Not sorting the output
  • Confusing set behavior with list
4. You have a flaky test marked with a retry decorator, but it still fails intermittently. What is the most likely cause?
medium
A. The retry count is too low to cover all flaky failures
B. The test code has a syntax error
C. The test is not marked as flaky
D. The test always passes and never fails

Solution

  1. Step 1: Understand retry decorator purpose

    Retry decorators rerun flaky tests a set number of times to reduce false failures.
  2. Step 2: Identify cause of intermittent failure despite retries

    If failures persist, likely the retry count is too low to catch all flaky cases.
  3. Final Answer:

    The retry count is too low to cover all flaky failures -> Option A
  4. Quick Check:

    Low retry count causes flaky failures [OK]
Hint: Check retry count if flaky test still fails [OK]
Common Mistakes:
  • Assuming syntax error causes flaky behavior
  • Forgetting to mark test as flaky
  • Ignoring retry count limits
5. A team wants to manage flaky tests without blocking releases. Which approach best balances fixing flaky tests and maintaining release flow?
hard
A. Run flaky tests only once before release
B. Remove flaky tests permanently to avoid failures
C. Temporarily mark flaky tests to skip during release, then fix them later
D. Ignore flaky tests and release as usual

Solution

  1. Step 1: Understand impact of flaky tests on releases

    Flaky tests can block releases if they fail randomly, so managing them is critical.
  2. Step 2: Evaluate options for balancing fixes and release flow

    Temporarily marking flaky tests to skip during release avoids blocking while allowing later fixes.
  3. Final Answer:

    Temporarily mark flaky tests to skip during release, then fix them later -> Option C
  4. Quick Check:

    Skip flaky tests temporarily to keep releases smooth [OK]
Hint: Skip flaky tests temporarily, fix later to keep releases smooth [OK]
Common Mistakes:
  • Deleting flaky tests instead of fixing
  • Ignoring flaky tests causing release failures
  • Running flaky tests only once risking missed failures
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard