Unit 1 of 8 · about 4 hours · explain, implement

Test levels, oracles, boundary cases and test doubles

Most ML bugs hide at component boundaries, not inside one function. The test level decides which failures you can see, and the oracle decides whether the test checks anything at all.

You'll be able to

  • Distinguish unit, contract, integration, end-to-end and performance tests by the failure each can detect.
  • Turn a requirement into an invariant, an independent oracle, representative examples and boundary cases.
  • Build a pytest suite with fixtures, parametrization and test doubles that has no order dependence.

Covers

Unit, contract, integration, end-to-end and performance testsRequirements, invariants, independent oracles and boundary casesFixtures, fakes, stubs, mocks and integration risk
1

Read

In this order, only the parts listed

0 of 6 done

  1. Code Quality: Testing and code coverageThe Missing Semester of Your CS Education

    Testing: unit, integration and functional tests, test-driven development, regression tests, property-based tests and mocks; Code coverage

  2. pytest Get Startedpytest documentation

    Install pytest through Request a unique temporary directory for functional tests: first test, exceptions, classes and approx

  3. pytest fixtures: scope and teardownpytest documentation

    Requesting fixtures; Scope: sharing fixtures across classes, modules, packages or session; Teardown/Cleanup (AKA Fixture finalization)

  4. pytest monkeypatch and mockspytest documentation

    Monkeypatching functions; Monkeypatching returned objects: building mock classes; Monkeypatching environment variables; Monkeypatching dictionaries

  5. pytest and unittest recipesStas' Python Cookbook - debugging and testing

    Testing with pytest and unittest: pytest basics, Fixtures with tmp_path, capsys, monkeypatch and caplog, and Capturing output

  6. MockingAlgoMaster Python - mocking

    Mock vs MagicMock; patch: Decorator, Context Manager, and Manual; The "Where to Patch" Gotcha; autospec and create_autospec; Over-Mocking: The Brittleness Trap

2

Focus on

  • Each level detects a different failure: unit tests catch logic errors in one function, contract tests catch seam drift, integration tests catch wiring errors, end-to-end tests catch requirement misses.
  • An oracle must be independent of the code under test: a reimplementation, the standard library, a known value or a metamorphic relation. Asserting code output against itself proves nothing.
  • Boundary cases carry the failures: empty input, single element, duplicates, limits and malformed rows. Parametrize them explicitly.
  • Function scope is the default for a reason: shared mutable fixtures create order dependence. Use yield fixtures for teardown and monkeypatch for automatic undo.
Common mistakes · 3
  • Mocking the unit you should be testing. Mock at the seam you do not own, such as network, clock or filesystem, and keep one contract test that touches the real dependency.
  • Module- or session-scoped mutable fixtures. Tests pass alone and fail together; keep shared fixtures immutable or hand out fresh copies from a factory.
  • Reading 100 percent line coverage as correctness. Coverage shows which lines ran, not which requirements were checked, so the lecture warns against over-indexing on it.
3

Try it yourself

Closed-book, before checking anything

From a blank directory, write a small parsing module and a pytest file with one boundary test parametrized over three cases, one yield fixture using tmp_path, and one monkeypatched environment test. Run pytest and get 5 passed in about 0.3 s on a 12th Gen Intel Core i9-12900K with Python 3.14.4 and pytest 9.1.1.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.A function returns correct values but writes rows the loader cannot read. Which test level catches this?Answer

    An integration or contract test at the writer and loader seam. A unit test of either side alone passes.

  2. 2.Why is asserting your sort equals your second sort implementation weak, and what is stronger?Answer

    Both can share your misunderstanding. A stronger oracle is independent: the standard library sorted, a fixed fixture, or a property such as the output being ordered.

  3. 3.Two tests share a module-scoped dict fixture and pass alone but fail together. What is wrong?Answer

    One test mutates shared state the other reads. Make the fixture function-scoped or return a fresh copy per test.

  4. 4.monkeypatch.setenv in one test seems to change a later test. Where is the leak?Answer

    Not in os.environ: pytest undoes every monkeypatch change at teardown. Either a test wrote to os.environ directly, or code cached the value while the patch was active, such as a module-level setting or an lru_cache.

  5. 5.mod.py does from json import dumps. A test patches json.dumps, yet mod.run still calls the real one. Why?Answer

    patch replaces a name where it is looked up. mod bound its own name dumps at import, so patch mod.dumps instead. Verified with unittest.mock on CPython 3.14.

5

Practice

You're done when

Your five-test suite passes, every test also passes alone by node id, and you can name the oracle and the boundary behind each assertion.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 3 more in the 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.

  • pytest documentationpytest · required

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

  • 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.

Also in this section

  • 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.

  • 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.