CS 101 — Programming Foundations with Python · Weeks 12–14
Tests, debugging and evidence of correctness
Full teaching sequence and cumulative subject work
Work the debugging appendix and the list-algorithm exercises. Classify failures as syntax, runtime or logical errors; construct minimal counterexamples. Use independent expected outputs, boundary tests and properties with explicit assumptions. Then study the original assigned documentation as a language reference and complete the worked and transfer problems.
Tests as discriminating evidence
A useful test distinguishes a correct implementation from a plausible wrong one. Repeating the implementation’s own formula in the expected-value expression can reproduce its mistake. Hand-compute a small example and choose cases at policy boundaries. Properties connect many inputs but still require assumptions: additivity applies to unrounded integer-cent sums, whereas independently rounded discounts need not be additive.
A test suite is evidence about specified behavior, not proof that no defect exists. Include invalid types, empty data, repeated events, conflicting IDs and failures during output. Separate pure-function tests from integration tests that establish whether the actual parser, coordinator and writer are connected correctly.
Worked problem
A programmer tests a total function only with [100, 200]. It passes, but the implementation first converts the list to a set. Design the smallest useful counterexample and an independent expected value.
Trace the complete reasoning
The original test contains no duplicates, so set conversion preserves its sum. It cannot discriminate the erroneous behavior.
Use [100, 100]. Two separate transactions sum to 200 cents; the set-based implementation returns 100.
Add [100, −100] to test cancellation, [] to test the identity, and [0] to test whether zero is accepted without being confused with absence.
For validated lists a and b, total(a + b) = total(a) + total(b). Test this property only for the unrounded total, not for a process with invoice-level rounding at each call.
Independent transfer problem
A test for a 50% invoice discount claims discounted(a+b) always equals discounted(a)+discounted(b). Use a=[1] cent and b=[1] cent with half-up rounding to evaluate that claim.
Compare the transfer solution
One combined 2-cent invoice discounts to 1 cent. Each separate 1-cent invoice discounts to 0.5 cent and rounds to 1 cent, so their sum is 2 cents. The failed property exposes an invalid test assumption, not necessarily a defective discount function. Replace it with properties matching the chosen rounding boundary, and keep examples that verify both combined and separate invoices.
Learning objectives
- Explain and trace the mechanisms in tests, debugging and evidence of correctness.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
Study the mechanism
A test states an observable expectation and checks it against an implementation. Begin with requirements rather than copying the function's internal steps into the test. If the requirement says duplicate transactions both count, a test must contain duplicates. If negative hours are invalid, test a negative input. Normal cases, boundaries, invalid inputs and interactions reveal different classes of failure.
Distinguish a defect in implementation from a defect in the specification. A program can implement a poorly chosen rule exactly. For example, requiring all transactions to be positive may make tests pass while excluding legitimate refunds. Ask stakeholders what the output means before optimizing test coverage. Code coverage measures executed code, not whether assertions are meaningful or whether missing behaviors were specified.
Debugging is a controlled experiment. Reproduce the failure with the smallest input, predict the intermediate state, observe where the actual state first differs and alter one cause at a time. A changed expected result is justified only when the requirement was wrong, not merely because the implementation returned something different. Property checks broaden your evidence: concatenating two transaction lists should make their summed total equal the sum of each list's total, provided arithmetic and policies are unchanged. Such properties do not replace example tests; they complement them. Keep randomness reproducible and distinguish stable unit tests from integration checks that depend on files, networks or external services.
Worked example
def total(rows):
return sum(cents for _, cents in rows)
def test_refunds_and_duplicates():
rows = [("Ada", 500), ("Ada", 500), ("Ben", -200)]
assert total(rows) == 800
assert total([]) == 0
left, right = rows[:1], rows[1:]
assert total(left + right) == total(left) + total(right)
test_refunds_and_duplicates()The example checks the business meaning of duplicates and refunds together. An implementation that converts rows to a set returns 300, exposing an information-loss bug. The empty test establishes the additive identity. The concatenation property connects several cases through a mathematical relationship, but does not check amount parsing or customer validation because those belong to another boundary.
Check your understanding
What does high line coverage establish?
- Those lines executed during tests, not that every requirement was checked
- The business rules are correct
- Every possible input has been tested
Answer and reasoning for every option
Correct: Those lines executed during tests, not that every requirement was checked Execution evidence is useful but weaker than complete behavioral evidence.
Reconsider: The business rules are correct A specification can be wrong even with full coverage.
Reconsider: Every possible input has been tested Finite example tests generally cannot enumerate all inputs.
Transfer laboratory: A test that passes for the wrong reason
An implementation returns zero for every input. Its only test uses [100,-100]. Design the smallest meaningful suite that exposes it and distinguishes totals from transaction counts.
Work through the full solution
The balanced example passes because its correct total is zero. Add a positive-only case, a refund-only case, a duplicate transaction case, an empty list and a list containing zero whose record count is checked. For example [100] must total 100 and [-20] must total -20. Assertions should reflect independent requirements rather than duplicating implementation steps. Coverage cannot compensate for missing expected behavior.
Evidence of understanding
At least one failing nonzero case and separate multiplicity/count assertions are required.
Complete on-site teaching readings
These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.
- unittest — Unit testing framework · Python Software Foundation and Python documentation contributors
- doctest — Test interactive Python examples · Python Software Foundation and Python documentation contributors
- re — Regular expression operations · Python Software Foundation and Python documentation contributors
Open the complete practice sequence and cumulative assessment →