Lesson · Testing
Testing Strategy & Parameterized Cases
80 min readTesting Strategy & Parameterized Cases
A testing strategy decides what to test, at which layer, and with how much isolation. Parameterized cases, deterministic inputs, temporary resources, and a sensible mix of unit and integration tests improve confidence.
Learning goals
- Place a test at the unit or integration level and justify the choice with what each level proves.
- Describe the pyramid as a ratio of feedback speed and confidence rather than a fixed rule.
- Derive the boundary cases of a range check and turn them into a table of inputs and expected results.
- Parameterize cases with
subTestso one failing row is reported without losing the others. - Explain what a fake, a stub, and a mock each add, and keep doubles at the boundaries.
Mental model
Strategy is a sequence of choices about scope, coverage, and doubles, and each one trades feedback speed against confidence. Parameterized tables and boundary values multiply the cases without multiplying the code.
Mental model
read it top to bottom
decision question it answers unit or integration? does this test cross a real boundary? pyramid ratio how many tests of each size can we afford, how often? boundary values where do conditions flip? test just below and exactly at the edge table + subTest one body, many rows, every row reported on its own double choice fake (behavior) < stub (one response) < mock (interactions)
Core idea
A testing strategy is a set of placements and ratios: unit tests carry the bulk because they are fast and precise, integration tests cover the boundaries where real dependencies meet your code, and a few end-to-end checks prove the full path. Inside a level, the shape of the cases matters as much as their number, so boundary values pick the inputs most likely to break and a parameterized table keeps those cases separate in the report. The whole strategy bends toward one quality: a failure that tells you what broke.
Unit vs integration boundaries
The boundary decides whether a test runs one unit against controlled collaborator replacements or crosses a real edge such as a database, a network, or a file. Unit tests stay fast and local, while integration tests exercise where your code meets the outside world, which is where queries, serialization, and configuration actually break.
Test pyramid intuition
The pyramid is a ratio, not a rule: many fast unit tests at the base, fewer integration tests across boundaries, and a thin layer of end-to-end checks that prove the whole path. The point is feedback, since cheap tests catch most defects before the expensive layers run.
Boundary-value tests
Boundary-value tests check the edges of each input range, where conditions flip: the minimum and maximum allowed, one below and one above, the empty case, and a single item. Bugs cluster at comparisons, so a check such as value < limit needs cases at limit - 1 and at limit.
Table-driven tests
A table-driven test keeps its cases in a data structure, such as a list of (input, expected) tuples, and one loop drives the same check for every row. The table separates the specification from the mechanics, so adding a case means adding a row.
Parameterized-test concept
Parameterizing a test reuses one test body across many inputs while still reporting each case separately, which subTest provides inside unittest. A failure names the offending parameters instead of stopping at the first bad row.
Testing exceptions
Test exceptions with the tool that asserts them, assertRaises, and check the exception type and, when it matters, the message. Catching by hand around the call tends to hide the failure, and the check belongs on the operation that raises rather than on surrounding setup.
Testing filesystem behavior safely
Filesystem tests must not touch real user paths or leave files behind: create a temporary directory per test, confirm it is removed afterward, and pass the path into the code instead of hardcoding one. Temporary resources keep runs repeatable even when a test fails midway.
Dependency seams
A dependency seam is a place where a test can substitute a collaborator without editing the code under test, usually because the dependency arrives as a parameter or an overridable attribute. Code without seams is hard to isolate, so designing for testability mostly means creating seams at real boundaries.
Fake vs stub vs mock
Fakes implement working simplified behavior, stubs return canned responses, and mocks record interactions for assertions. Choose the weakest one that answers the test's question: a fake proves the code works against real behavior, a stub controls one response, and a mock is needed only when the interaction itself is the contract.
Avoiding over-mocking
Every mock removes real behavior from the test, so an over-mocked suite proves that your code calls the right names with the right arguments and little else. Keep doubles at the boundaries and let internal collaborators run for real whenever they are cheap and deterministic.
Deterministic tests
Seed or inject a pseudo-random generator when a test needs repeatable random-looking data. Security tokens should not be made deterministic this way.
Test readability and maintenance
A test is read far more often than it is written, so name it for the behavior it proves, keep the three stages obvious, and prefer one concrete case per check over clever helpers. The test to rewrite first is the one whose failure message does not say what broke.
Walkthrough
is_even(value)returnsvalue % 2 == 0, so the interesting inputs are parity edges:0and2for even,1and-3for odd, with the negative case proving the modulo rule still holds below zero.casesis the table: a list of(value, expected)tuples that keeps the specification separate from the checking mechanics.self.subTest(value=value)parameterizes the loop: with a correctis_evenall four rows pass, and when one row fails the report names that value while the remaining rows still run.- Predict before running: how many tests the runner reports (one method, four cases), what happens to the other rows when
(1, True)gets a wrong expectation, and what-3 % 2equals in Python.
Experiments to try
- Flip
(2, True)to(2, False)and read the failure; note that the subtest label identifies the value2while the other rows still execute. - Add rows for
(10**18, True)and(-2, True); confirm both pass and explain what large positive and even negative values exercise. - Replace
subTestwith a plainself.assertEqualinside the loop and compare what a failing row reports; then restoresubTest. - Add a separate test method using
assertRaises(TypeError)foris_even("2"); explain why that case cannot join the plain value table without branching.
Common mistakes
- Treating every test as an integration test: running the whole stack for pure logic slows feedback and blurs where the defect sits; keep the pyramid's base local and cheap.
- Testing only the middle of an input range:
is_even(2)passes while0, negatives, and the flip points of comparisons stay unexamined; derive cases from where conditions change. - Chasing coverage with mocks: a suite where every collaborator is doubled verifies the call graph, not the behavior, and still passes when the real collaborator would reject the call.
- Writing files to a fixed path: a filesystem test that reuses one name leaks state between runs and fails on machines where that path is missing or protected; use a fresh temporary directory per test.
Practice: Easy
- Run the worked example, then add
(10**18, True)and(-2, True)rows; confirm all pass and that the runner still reports one test. - Change one expectation to be wrong and read the report; then make two rows wrong at once and count how many failures appear.
- Convert the table into a plain loop without
subTestand compare the failure output for the same wrong row.
Practice: Medium
- Write
def in_range(value, low, high)and build boundary rows atlow,low - 1,high, andhigh + 1; justify each row from the comparison in the body. - Extend the
is_eventable with an exception case in a second test method usingassertRaises; explain why it cannot share the plain value table without branching. - Split the table into two tests, one for zero and positive values and one for negatives, and compare the report against the single
subTestversion; state which you would keep as the table grows and why.
Practice: Hard
- Design a test plan for a small config reader that loads a JSON file: classify each planned test as unit or integration, choose its doubles, and write the boundary table for path and content rules before writing code.
- Failure lab: make two table rows wrong under one
subTestloop, add a row whose call raises unexpectedly, and rerun the same suite withsubTestremoved; explain how the reports differ in each case. - Take four tests for a service that validates input, reads a config file, calls a payment API, and renders a page; place each on the pyramid, name the boundary it crosses if any, and choose the double or none.
Lesson checklist
- I can place a test at the unit or integration level and say what that level proves.
- I can justify a test mix with the pyramid as a ratio of speed to confidence.
- I can derive boundary rows for a comparison and keep them in a table driven by
subTest. - I can say what a suite gains from parameterized rows and loses when doubles replace every collaborator.
Remember
Strategy is about placement and ratio: units carry the bulk, integration tests cover the boundaries where real dependencies appear, and the pyramid is a budget of feedback speed against confidence. Inside a level, boundary rows focus the cases where conditions flip, and a table driven by `subTest` keeps every row visible in the report. The test to keep is the one whose failure names the broken behavior, which is also the test that over-mocking tends to destroy.
Interview angles
What is the main purpose of **Unit vs integration boundaries**?+
The boundary decides whether a test runs one unit against controlled replacements or crosses a real edge such as a database, network, or file. Unit tests stay fast and local, while integration tests exercise where your code meets the outside world, which is where queries, serialization, and configuration break.
What should you pay attention to when using **Test pyramid intuition**?+
The pyramid describes a ratio: many fast unit tests, fewer integration tests across boundaries, and a thin layer of end-to-end checks. The ratio is about feedback, since cheap tests catch most defects before the expensive layers run.
How does **Boundary-value tests** fit into this lesson?+
Boundary-value tests check the edges of an input range, where conditions flip: the minimum and maximum allowed, one below and one above, the empty case. Bugs cluster at comparisons, so value < limit needs cases at limit - 1 and at limit.
What does a test suite that mocks every collaborator actually verify?+
It verifies that the code calls the right names with the right arguments, not that anything works, because every mock accepts calls the real collaborator might reject. Keep doubles at the boundaries and let cheap, deterministic internals run for real.