The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← CS 101 — Programming Foundations with Python

Weeks 12–14

Tests, debugging and evidence of correctness

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.

Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.

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

Extended teaching and laboratory

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.

Step-by-step reasoning 1. The original test contains no duplicates, so set conversion preserves its sum. It cannot discriminate the erroneous behavior.

  1. Use [100, 100]. Two separate transactions sum to 200 cents; the set-based implementation returns 100.
  1. Add [100, −100] to test cancellation, [] to test the identity, and [0] to test whether zero is accepted without being confused with absence.
  1. 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.

Test the parser boundary before trusting a reconciliation

An integration test can pass while the parser admits invalid documents. The earlier implementation_laboratories.py companion checked its column names inside the row loop. With input consisting only of wrong,header followed by a newline, the loop body never executes. It reports an empty valid ledger instead of rejecting the wrong header. This is a counterexample to the stated header contract, not a debate about the correct total of an empty transaction list. A genuine empty ledger has the required header and no data rows; an empty file has no header and is invalid under the corrected contract.

A second counterexample has header event_id,customer,cents,cents and data row 1,Ada,500,700. Converting a row to a dictionary collapses repeated column names, retaining the last amount. A set of dictionary keys cannot reveal that duplicate header. The earlier function reports 700 cents. Check reader.fieldnames before iteration: require exactly three entries and the set {event_id,customer,cents}. Together, length and set equality prove every required name occurs exactly once. Merely testing the set of raw header names also fails to reject the duplicate.

The corrected companion on Names, Exact Money and Conservation supplies the complete ledger and atomic_report functions and executable regressions. Column order may vary, but names may not repeat. It validates missing and extra cells separately, uses strict CSV parsing, and accepts integer cents only in the declared optional-minus, one-to-twelve ASCII-digit syntax. It does not use the dollar parser from unit 1: the column already denotes cents. Customer and event fields each contain 1–80 characters with no implicit stripping. Numeric normalization means 0500 and 500 denote the same amount under an identical event ID, while a changed customer or amount is a conflict. Quoted commas and newlines are parsed as field content rather than split manually.

The accumulator invariant begins only after the document's header is validated. After each accepted record, seen maps every unique event ID in the processed prefix to its normalized payload, and customer totals sum those unique payloads. An exact retry contributes nothing. A conflicting retry raises, so an incomplete prefix is not published as a complete reconciliation. Physical line numbers can differ from record numbers when quoted fields contain newlines. Diagnostics must not assume that one CSV record occupies one physical line.

Output has a separate failure boundary. Validate the entire input before creating a candidate file, write it in the destination's directory, close it, and replace the old name only after writing succeeds. Clean up an unused candidate in a finally block. Injecting a replacement failure tests a path that a late-input-failure test never reaches. Successful local replacement does not choose a winner between independent writers or establish recovery after power loss. Those require additional coordination and durability requirements.

Independent counterexample and changed condition

Required columns may appear in any order, exactly once. Predict the result for header cents,event_id,customer with rows 500,1,Ada; 500,2,Ada; 500,1,Ada; -200,3,Ada. Next append 501,1,Ada and predict whether a previously valid destination may change. Separately test a header-only input with duplicate cents columns. Finally inject an OSError immediately at replacement after a valid candidate is written. State which artifact should remain and which temporary artifact should disappear. Use the complete corrected companion for this exercise; retain the earlier implementation as the defect-comparison case.

From a passing test to a bounded evidence claim

The original test-evidence laboratory now makes four layers explicit. First, the requirement defines the observable claim: distinct event IDs preserve multiplicity, zero is present, refunds keep their sign, and the result includes both count and integer-cent total. Second, an oracle must be derived independently of the candidate. Calling the candidate to calculate its own expected value only repeats its rule, no matter how many generated cases run. Third, a useful suite contains observations that distinguish plausible defects. Equal-value distinct events expose amount deduplication; a zero event plus a count assertion exposes truthiness filtering; more than one event exposes first-only logic; and a signed refund exposes absolute-value conversion. Fourth, an observed failure should be reduced while its disagreement with the oracle remains.

The complete companion implements four deliberate mutants and a deletion shrinker. For A100, B100 and C50, the correct summary is count3,total250 while amount deduplication returns count2,total150. Deleting C preserves the disagreement and produces two distinct 100-cent events. Neither remaining event can be deleted without losing the mechanism. This is a small causal counterexample, not proof that greedy deletion finds a globally smallest input for every failure predicate.

Property tests are conditional mathematical claims. For validated sequences with disjoint event IDs, raw summary count and total are additive under concatenation. The deterministic generator records a seed and forces useful boundaries into some cases, making a failure replayable. It still samples a finite set. The analogous claim fails when each side applies its own invoice-level rounding: at50% one combined two-cent invoice pays1, while two separately rounded one-cent invoices pay2. The right response is to repair the property's domain or rounding boundary, not to rewrite the observed result.

Integration evidence crosses a real persistence boundary. The laboratory begins an SQLite transaction, writes a batch summary, then writes a non-null audit message and commits. An injected exception between those writes must leave both tables unchanged. Asserting the exception alone is insufficient because a partial summary could still remain. These tests establish the stated local mechanism under their fixtures; they do not establish distributed coordination, production authentication, every crash-durability mode or unbounded performance.

Apply the idea

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.

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.

Required columns may appear in any order, exactly once. Predict the result for header cents,event_id,customer with rows 500,1,Ada; 500,2,Ada; 500,1,Ada; -200,3,Ada. Next append 501,1,Ada and predict whether a previously valid destination may change. Separately test a header-only input with duplicate cents columns. Finally inject an OSError immediately at replacement after a valid candidate is written. State which artifact should remain and which temporary artifact should disappear. Use the complete corrected companion for this exercise; retain the earlier implementation as the defect-comparison case.

Evidence transfer — A generated case A40,B40,C−5 exposes amount deduplication. Derive the specification and mutant summaries, shrink the case by deletion in at least two valid attempt orders, and state exactly what irreducibility the result establishes. Next explain why 500 generated comparisons remain circular if each expected value is produced by the candidate. Replace that oracle. Then state the preconditions for raw-summary concatenation additivity and show why separately rounded 50% discounts on two one-cent invoices violate the analogous claim. Finally inject a failure after both SQLite inserts but before commit; list the exact rows that must remain before and after the failed operation, and explain what separate evidence would be needed for two concurrent writers.

Read the worked reasoning

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.

The reordered document has three unique events and Ada totals 800 cents. The unchanged retry adds nothing. Appending event 1 with amount 501 conflicts with its accepted payload, so validation raises before the old report is touched. A duplicate-column header is invalid even with no data rows, because header validation precedes iteration. With a valid candidate but an injected replacement failure, the old destination remains and the candidate is removed by finally. A test that checks only parsing cannot establish candidate cleanup after a write or replace failure.

Evidence-transfer reasoning — The specification returns count3,total75; amount deduplication returns count2,total35 because the two 40-cent values collapse. Trying to delete C first succeeds and leaves A40,B40; deleting either of those then removes the disagreement. Trying to delete A first fails to preserve the disagreement, so the shrinker keeps it and may next delete C. The final two-equal-value case is one-record irreducible under this observed predicate, not a proof of global minimality for arbitrary failures. Candidate-derived expected values remain circular at any sample size; use hand-derived fixtures or a structurally independent oracle based on the stated count-and-sum contract. Raw additivity requires valid records and disjoint identifiers. Rounding changes the operation: combined2 at50% yields1, while separate1 and1 yield2. After an injected pre-commit failure, exact queries must show neither summary nor audit row for the batch. A concurrent-writer claim needs independent connections, synchronized interleaving and declared lock/version outcomes; the serial rollback test cannot establish them.

Check understanding

What does high line coverage establish?

  1. Every possible input has been tested
    Feedback

    Finite example tests generally cannot enumerate all inputs.

  2. Those lines executed during tests, not that every requirement was checked
    Feedback

    Execution evidence is useful but weaker than complete behavioral evidence.

  3. The business rules are correct
    Feedback

    A specification can be wrong even with full coverage.

Further reading

Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.

Use the original worked investigations and optional changed-record models in this unit. Historical directions below are retained as source history and do not require publisher chapters.

My learning →