Unit 3 of 8 · about 3 hours · implement, measure

Regression tests, failure injection and flaky tests

A fixed bug returns unless a test pins it. A flaky test teaches the team to ignore red builds, which hides the next real failure.

You'll be able to

  • Write a regression test that fails on the old code and passes on the fix, and mark known-bad behavior with strict xfail.
  • Inject a targeted fault, such as a full disk or a failing dependency, and show the suite catching it.
  • Measure a flake rate, isolate its randomness, time, concurrency or state source, and quarantine deliberately instead of rerunning blindly.

Covers

Regression tests and targeted failure injectionRandomness, time, concurrency, external state and flaky tests
1

Read

In this order, only the parts listed

0 of 4 done

  1. pytest skip and xfailpytest documentation

    Skipping test functions and skipif; XFail with condition, reason, raises, run and strict parameters; Skip/xfail with parametrize

  2. pytest flaky tests explanationpytest documentation

    Why flaky tests are a problem; Potential root causes: system state, overly strict assertion and thread safety; Other general strategies: split up test suites and quarantine

  3. Hypothesis flaky failuresHypothesis documentation

    Common sources of flakiness; Types of flakiness: Flaky failure and Flaky strategy definition

  4. Reproducing resource issuesThe Art of Debugging

    Watching and reproducing resource issues: Running out of resources, Emulating an almost full disk partition and Emulating running out of CPU memory

2

Focus on

  • A regression test names the defect: it fails before the fix and passes after. Write it before the fix when you can.
  • xfail with strict=True turns an unexpected pass into a failure, so fixed bugs announce themselves. Unstrict xfail as permanent quarantine is dangerous; the pytest guide says so.
  • Flakiness means uncontrolled state: randomness, clocks, threads, leftover files or test order. Parallel runs and randomized ordering expose order dependence.
  • Rerun plugins and quarantines mitigate; they do not fix. Isolate the source first, then control it, quarantine it with an owner, or delete the test.
Common mistakes · 3
  • Rerunning the suite until green and merging. The team learns to distrust failures, so quarantine with a ticket instead.
  • xfail without strict on a fixed bug. The suite stays green while the mark silently goes stale.
  • Wall-clock sleeps as synchronization. Load makes them flaky, so wait on events or poll with deadlines instead.
3

Try it yourself

Closed-book, before checking anything

Write assert random.random() < 0.5 and run it 10 times: expect about half to fail (5 failed and 5 passed in the reference run, about 0.07 s per run on a 12th Gen Intel Core i9-12900K with Python 3.14.4 and pytest 9.1.1). Seed it with random.seed(1) (first draw 0.134) for 5 passes in 5 runs, then random.seed(0) (first draw 0.844) for 5 failures: seeding makes the outcome deterministic, not correct. Then mark a known failure xfail(strict=True), fix the code, and watch the suite fail on XPASS until you remove the mark.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A test fails one run in twenty. What is the first measurement, and what comes after?Answer

    The flake rate over repeated runs, then isolation: seed randomness, fix clocks, serialize threads, clean state, and run the test alone versus in the suite.

  2. 2.When is strict xfail the right tool?Answer

    A known bug with a test: the suite stays green while it fails and goes red with XPASS when fixed, which forces removal of the mark.

  3. 3.A test passes alone but fails under parallel workers. What does that suggest?Answer

    Order dependence or shared state: a previous test leaves data behind, or the test needs data another test creates.

  4. 4.Why does pytest.approx belong in a flake fix for float asserts?Answer

    Exact float equality is an overly strict assertion: tiny representation differences fail otherwise identical runs. approx compares within tolerance.

5

Practice

You're done when

You can quote the flake rate before and after your fix, the regression test fails on the old code, and no test needs a rerun to pass.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 4 more in the section
  • pytest documentationpytest · required

    Use Get Started, fixtures, parametrization, monkeypatch, caplog and temporary paths to build behavior and failure-path tests without order dependence.

  • Hypothesis documentationHypothesis · required

    Follow the Quick start and property-based testing guides, then generate operation histories and retain the minimized example for one real defect.

  • The Art of DebuggingStas Bekman · support

    Use the Unix, Python and compiled-code sections during a real seeded defect. Follow the evidence and tiny-reproducer workflow rather than reading the unfinished book front to back.

Also in this section

  • The Missing Semester of Your CS EducationMIT · primary

    Complete the 2026 lectures on the shell, command-line environment, development tools, debugging and profiling, Git, packaging and shipping code, and code quality. Apply every exercise to the same stage project.

  • Pro GitGit project · support

    Use Chapters 2-3 and the sections on debugging, internals and recovery while constructing a history for bisect and recovering a deliberately displaced commit.

  • Stas' Python Cookbook - debugging and testingStas Bekman · support

    Use Part III and the packaging sections for debugger, traceback, pytest, logging, profiling and clean-environment recipes.

  • AlgoMaster Python - mockingAlgoMaster · support

    Use the Mocking lesson for unittest.mock: Mock versus MagicMock, patch targets, autospec and the over-mocking trap. The pytest docs remain the reference for fixtures and monkeypatch.