Testing and Debugging
Algorithms, Programming, and Data Representation · Module 92313 · Chapter 9
Specify what a program promises, design tests that challenge that promise, and investigate failures with evidence. Exceptions make runtime errors explicit; assertions check internal assumptions.
Start from memory
Answer these before reading.
- How do testing and debugging differ?
- Why test boundary values?
- Does branch coverage prove correctness?
- What does int("cat") raise?
- Should assert validate user input?
Check your answers
- Testing compares actual behavior with a specification; debugging investigates a mismatch’s cause. §9.1
- Boundaries expose off-by-one and special-size errors. §9.3
- No; a path may run but compute the wrong result. §9.4
- ValueError: the type is suitable but the value is not an integer literal. §9.6
- No. Assertions may be removed under optimization. §9.8
How to use this guide
For every test, write its input, expected result, and reason. Keep the smallest failing case when debugging.
- Day 0: §9.1–9.3; practice 1, 4, 7, 10, 13.
- Day 1: §9.4–9.5; practice 2, 5, 8, 11, 14.
- Day 3: §9.6–9.8; practice 3, 6, 9, 12, 15, 18.
- About day 7: Rebuild the derivations; solve 16–20.
- About day 14: Work both exam problems in about 20 minutes each.
- Before the exam: Tick only skills you can demonstrate without notes.
When stuck: reproduce the failure, observe values, test one hypothesis at a time.
How the chapter fits together
Specifications define expected behavior. Black-box tests choose representative inputs from the contract; glass-box tests inspect code paths. Debugging explains mismatches. Exceptions signal failures; assertions check internal invariants.
Specify
Contract §9.1
input → promised outputRests on: assumptions and guarantees.
Partitions §9.3
classes + boundariesRests on: expected behavior.
Inspect
Paths §9.4
each decision outcomeRests on: visible control flow.
Debug §9.5
observe → hypothesize → testRests on: repeatable evidence.
Respond
Exceptions §9.6
raise → handlerRests on: a deliberate recovery policy.
Assertions §9.8
assert conditionRests on: an internal assumption.
9.1 Defensive programming
In plain words: make assumptions visible and each program part small enough to test.
A function contract states acceptable inputs and promised output. Modularity makes parts testable in isolation. Remove syntax and static errors first, then compare chosen input/output pairs with the specification.
Worked example · absolute value contract
- Assume x is an integer.
- Return x if x ≥ 0 and −x otherwise.
- Expected cases: 4→4, −4→4, 0→0.
Trap: A function running once does not prove it meets its contract.
Near miss: Testing only x=4 misses a faulty zero boundary; add x=0.
Recall · §9.1
- What does a contract state?
- Why modularize?
Answers
- Input assumptions and the promised result. §9.1
- To test and debug pieces independently. §9.1
9.2 Test levels
In plain words: test one unit, keep tests for old bugs, and check components together.
- Unit: one function.
- Regression: prevent a fixed bug from returning.
- Integration: check the combined program.
For each input, record an expected result before execution. Integration-only testing makes failures harder to localize.
Trap: A passing unit test does not prove the integrated report is correct.
Near miss: Two functions pass alone but use mismatched record shapes; integration exposes it.
Recall · §9.2
- What does a regression test protect?
- What does integration testing check?
Answers
- A previously fixed defect. §9.2
- Whether components work together. §9.2
9.3 Black-box testing
In plain words: choose cases from the specification without looking at implementation.
Partition inputs into natural classes and test boundaries: empty/singleton, small/large, and either side of a decision. A square-root function might promise x≥0, ε>0 and x−ε≤r²≤x+ε.
Worked example · square-root cases
- (0, 0.0001) checks zero.
- (25, 0.0001) checks a perfect square.
- (0.05, 0.0001) checks values below one.
- (2, 0.0001) checks an irrational root against tolerance.
- Very small and large values probe extremes.
Trap: Many typical values can still miss a boundary.
Near miss: Testing −2 and 2 covers branches in the faulty abs example but misses −1.
Recall · §9.3
- Why test boundaries?
- Why can another person design tests?
Answers
- Boundary defects can be missed by ordinary examples. §9.3
- They can follow the specification without implementer bias. §9.3
9.4 Glass-box testing
In plain words: inspect decisions in code and exercise their outcomes.
executed paths ≠ correct behaviorPair path checks with boundary cases from the specification.Path-complete testing attempts every path, but loops have many lengths and coverage does not prove correctness. For faulty code if x < -1: return -x, tests 2 and −2 cover both branches, yet −1 returns −1, contrary to the absolute-value contract.
Worked example · coverage blind spot
- 2 takes the false branch and returns 2.
- −2 takes the true branch and returns 2.
- −1 takes the false branch and wrongly returns −1.
- The boundary test finds what branch coverage missed.
Exercise branches and boundaries
Trap: Path coverage is evidence of execution, not proof of correctness.
Near miss: A branch test with −2 nearly checks abs, but −1 reveals the wrong condition.
Recall · §9.4
- What does path-complete mean?
- What does coverage not guarantee?
Answers
- Every potential path was tested at least once. §9.4
- That every boundary or specification case is correct. §9.4
9.5 Debug systematically
In plain words: find how the unexpected value arose; do not guess at a fix.
observe → hypothesis → repeatable testChange one cause at a time.Observe evidence, form a hypothesis, and repeat a small experiment. Use a simple failing input. Print function entry, parameters and results. With bisection, inspect midway through a long calculation, then focus on the half containing the first divergence.
Worked example · find a wrong total
- Save the smallest failing input.
- Inspect an intermediate value halfway through.
- If wrong, inspect the earlier half; otherwise inspect the later half.
- Repeat to locate the first faulty operation.
- Change one thing and rerun this case and regression tests.
Trap: Changing several lines before rerunning the case destroys useful evidence.
Near miss: A print at the final result shows failure but not where it began; inspect intermediate values.
Recall · §9.5
- Why ask how the result arose?
- What makes a debugging experiment useful?
Answers
- It focuses on the sequence of events and values. §9.5
- It is small, repeatable, and tests one hypothesis. §9.5
9.6 Exceptions and handlers
In plain words: Python raises an exception when an operation cannot proceed.
raised type ∈ handled typesOtherwise the exception propagates.IndexError: index outside a sequence.NameError: a name is not defined.TypeError: an operation received an inappropriate type.ValueError: a suitable type carries an invalid value.AttributeError: an attribute lookup failed.
A try body runs until an exception; a matching specific except handles it. Unmatched exceptions propagate.
Worked example · safe conversion
try: int(text) may raise ValueError; except ValueError can report a correction, and else runs only after success. Keep try narrow so unrelated errors remain visible.
Trap: A bare except can hide a TypeError while handling a conversion error.
Near miss: Catching ValueError around the whole report almost works, but can mislabel a later ValueError; keep try narrow.
Recall · §9.6
- How do TypeError and ValueError differ?
- Why avoid bare except?
Answers
- Wrong operand type versus invalid value. §9.6
- It can hide unrelated programming errors. §9.6
9.7 Raise or recover deliberately
In plain words: catch an error only when there is a sensible next action.
recover only when the next action is definedOtherwise raise or re-raise a descriptive exception.Raise a descriptive exception if a function cannot meet its contract. Avoid magic error values that resemble valid results. A handler may notify, stop, apply a documented default, or re-raise. For empty grades, choose whether to reject or define a default average. Finally runs after success or failure, making it suitable for cleanup.
Worked example · empty grades
- sum(grades)/len(grades) raises ZeroDivisionError for an empty list.
- One policy rejects the list; another defines an average of 0.0.
- Document the choice so callers do not treat a default as measured data.
Trap: Returning a special number for failure can make it look like a valid result.
Near miss: Returning 0.0 for no grades is only valid if that policy is explicit.
Recall · §9.7
- When re-raise?
- What is finally for?
Answers
- When the function cannot safely recover. §9.7
- Cleanup regardless of success or failure. §9.7
9.8 Assertions and invariants
In plain words: assert says an internal condition should always hold here.
assert conditionChecks an internal assumption during development.assert len(grades) > 0 raises AssertionError when false in a normal run. Assertions can check invariants and expected internal results during development. They supplement testing.
Python may omit assertions under optimization (-O). Do not use them for required behavior or user-input validation; validate external data explicitly.
Worked example · internal versus external
- Assert an internal count remains non-negative after an algorithm step.
- Explicitly reject invalid user input and display an error.
- The first checks a programmer assumption; the second is required behavior.
Trap: An assertion is not a substitute for checking user data.
Near miss: assert age >= 18 looks like validation, but -O can remove it; use an explicit check.
Recall · §9.8
- What is an invariant?
- Why not assert external input?
Answers
- A condition expected to remain true. §9.8
- Optimization can remove assertions. §9.8
Decision map
| Need | Tool |
|---|---|
| Define expected behavior | Contract |
| Choose representative inputs | Partitions and boundaries |
| Exercise implementation logic | Branch and loop tests |
| Locate a first wrong value | Trace and bisection |
| Recover from known runtime failure | Specific exception handler |
| Check internal assumption | Assertion during development |
Derive it cold
- Design square-root test partitions. §9.3
- Trace the abs(-1) boundary defect. §9.4
- Write a specific try/except/else. §9.6
- Choose an empty-grade policy. §9.7
- Separate an invariant assertion from input validation. §9.8
Explain it
- Why write expected results before testing?
- Why retain a regression test after fixing a defect?
- Why doesn’t path coverage prove correctness?
- Why use a small failing input?
- Why keep try narrow?
- Why avoid magic error values?
Model answers
- Keeps expectation separate from observed behavior. §9.2
- Prevents a fixed defect returning. §9.2
- Coverage measures execution, not correctness. §9.4
- Removes irrelevant behavior. §9.5
- Prevents swallowing unrelated errors. §9.6
- A caller may confuse one with a valid result. §9.7
Mixed practice
20 problems. Try each before opening the matching worked answer.
- State a contract for is_bigger(x,y).
- Which test level checks one function?
- Name input classes for a first-item function on lists.
- For n < 10, give boundary values on both sides.
- Why can branch coverage miss the abs(-1) defect?
- Describe bisection debugging.
- Why preserve the smallest failing input?
- What does int('3.5') raise?
- What does [1,2][4] raise?
- When raise instead of return -1?
- Why avoid a bare except?
- When does try/else execute else?
- What belongs in finally?
- What does a false assert do in a normal run?
- Why not assert an access rule?
- For eps>0, name an invalid boundary and a nearby valid value.
- Why retain a regression test?
- An empty grade list causes division by zero. Name a policy.
- Should abs test -1 if 2 and -2 already ran?
- What makes debugging systematic?
Show worked answers
- Assume integer inputs. Return True exactly when x>y; otherwise return False. §9.1
- Unit testing checks an isolated function or component. §9.2
- Test a singleton, a longer list, and the empty list if its behavior is specified. §9.3
- Use 9 and 10; they lie immediately on opposite sides of the decision. §9.3
- The tests may take both branches at other values while missing the incorrect boundary. §9.4
- Inspect a midpoint, then focus on the half where the first value diverges. §9.5
- It makes the defect reproducible and removes unrelated behavior. §9.5
- ValueError: the text is not an integer literal. §9.6
- IndexError: index 4 is outside the list. §9.6
- When no valid result can be produced or -1 may be mistaken for a valid result. §9.7
- It can hide unrelated errors; catch the expected exception specifically. §9.6
- Only when the try body completes without raising an exception. §9.6
- Cleanup that must run whether the operation succeeds or fails. §9.7
- It raises AssertionError. §9.8
- Python can omit assertions under optimization, so required checks must be explicit. §9.8
- eps=0 is excluded; a small positive epsilon is valid. §9.3
- It catches the fixed defect if a later change reintroduces it. §9.2
- Reject with ValueError, or document an intentional default such as 0.0. §9.7
- Yes. -1 is the boundary that exposes the faulty condition. §9.4
- Use evidence, form one hypothesis, and repeat a controlled test. §9.5
Exam-style problems
Allow about 20 minutes for each problem.
Problem 1 · Test a square-root function
Given x≥0, eps>0, and the promise x−eps≤r²≤x+eps, design a test set, explain coverage limits, and describe debugging a failure.
- Partition the inputs.
- State a boundary and extreme-value check.
- Explain the path-coverage limitation.
- Describe a debugging strategy.
Show worked answer
- Test zero, perfect squares, sub-unit values, irrational roots, and very small and large values. §9.3
- Check zero and extremes; evaluate the promised inequality instead of requiring one exact approximation. §9.3
- Exercise branches and loop exits, but keep boundary tests because execution coverage does not prove correctness. §9.4
- Keep the failing input and bisect intermediate values to find the first divergence. §9.5
Problem 2 · Grade report and errors
A class report computes each student's average. Choose behavior for empty grade lists, describe tests, and separate exception handling from assertions.
- State a policy for empty grades.
- Name unit and regression tests.
- Name an integration test.
- Explain which checks should be assertions.
Show worked answer
- Choose and document rejection or a defined default. §9.7
- Test ordinary and empty inputs; preserve the divide-by-zero case as a regression test. §9.2, §9.7
- Test a full class report with ordinary and empty records. §9.2
- Validate outside input explicitly; use assertions for internal invariants. §9.8
Slips in the notes
- Slides 21–22 use bare except before recommending specific handlers. This guide uses the specific form to keep unrelated failures visible.
- Slide 33 shows assert as input validation. Python may remove assert with
-O; explicitly validate user input. - Slide 24 lists silent failure but warns against it; an unexplained default can hide an error.
Self-check
Based on the supplied “09_testing_debugging.pdf”, rewritten in my own words. See the Python exception tutorial and assert reference. Not an official FAU publication. Made by Thanate Amornjiraporn (Focus).