APDR

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.

  1. How do testing and debugging differ?
  2. Why test boundary values?
  3. Does branch coverage prove correctness?
  4. What does int("cat") raise?
  5. Should assert validate user input?
Check your answers
  1. Testing compares actual behavior with a specification; debugging investigates a mismatch’s cause. §9.1
  2. Boundaries expose off-by-one and special-size errors. §9.3
  3. No; a path may run but compute the wrong result. §9.4
  4. ValueError: the type is suitable but the value is not an integer literal. §9.6
  5. 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.

  1. Day 0: §9.1–9.3; practice 1, 4, 7, 10, 13.
  2. Day 1: §9.4–9.5; practice 2, 5, 8, 11, 14.
  3. Day 3: §9.6–9.8; practice 3, 6, 9, 12, 15, 18.
  4. About day 7: Rebuild the derivations; solve 16–20.
  5. About day 14: Work both exam problems in about 20 minutes each.
  6. 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 output

    Rests on: assumptions and guarantees.

  • Partitions §9.3

    classes + boundaries

    Rests on: expected behavior.

Inspect

  • Paths §9.4

    each decision outcome

    Rests on: visible control flow.

  • Debug §9.5

    observe → hypothesize → test

    Rests on: repeatable evidence.

Respond

  • Exceptions §9.6

    raise → handler

    Rests on: a deliberate recovery policy.

  • Assertions §9.8

    assert condition

    Rests 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

  1. Assume x is an integer.
  2. Return x if x ≥ 0 and −x otherwise.
  3. 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

  1. What does a contract state?
  2. Why modularize?
Answers
  1. Input assumptions and the promised result. §9.1
  2. 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

  1. What does a regression test protect?
  2. What does integration testing check?
Answers
  1. A previously fixed defect. §9.2
  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

  1. (0, 0.0001) checks zero.
  2. (25, 0.0001) checks a perfect square.
  3. (0.05, 0.0001) checks values below one.
  4. (2, 0.0001) checks an irrational root against tolerance.
  5. 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

  1. Why test boundaries?
  2. Why can another person design tests?
Answers
  1. Boundary defects can be missed by ordinary examples. §9.3
  2. 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.

Coverage and correctnessexecuted 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

  1. 2 takes the false branch and returns 2.
  2. −2 takes the true branch and returns 2.
  3. −1 takes the false branch and wrongly returns −1.
  4. The boundary test finds what branch coverage missed.

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

  1. What does path-complete mean?
  2. What does coverage not guarantee?
Answers
  1. Every potential path was tested at least once. §9.4
  2. 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.

Debugging loopobserve → 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

  1. Save the smallest failing input.
  2. Inspect an intermediate value halfway through.
  3. If wrong, inspect the earlier half; otherwise inspect the later half.
  4. Repeat to locate the first faulty operation.
  5. 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

  1. Why ask how the result arose?
  2. What makes a debugging experiment useful?
Answers
  1. It focuses on the sequence of events and values. §9.5
  2. 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.

Handler matchraised 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

  1. How do TypeError and ValueError differ?
  2. Why avoid bare except?
Answers
  1. Wrong operand type versus invalid value. §9.6
  2. 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.

Error policyrecover 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

  1. sum(grades)/len(grades) raises ZeroDivisionError for an empty list.
  2. One policy rejects the list; another defines an average of 0.0.
  3. 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

  1. When re-raise?
  2. What is finally for?
Answers
  1. When the function cannot safely recover. §9.7
  2. 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.

Assertionassert 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

  1. Assert an internal count remains non-negative after an algorithm step.
  2. Explicitly reject invalid user input and display an error.
  3. 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

  1. What is an invariant?
  2. Why not assert external input?
Answers
  1. A condition expected to remain true. §9.8
  2. Optimization can remove assertions. §9.8

Decision map

NeedTool
Define expected behaviorContract
Choose representative inputsPartitions and boundaries
Exercise implementation logicBranch and loop tests
Locate a first wrong valueTrace and bisection
Recover from known runtime failureSpecific exception handler
Check internal assumptionAssertion during development

Derive it cold

  1. Design square-root test partitions. §9.3
  2. Trace the abs(-1) boundary defect. §9.4
  3. Write a specific try/except/else. §9.6
  4. Choose an empty-grade policy. §9.7
  5. Separate an invariant assertion from input validation. §9.8

Explain it

  1. Why write expected results before testing?
  2. Why retain a regression test after fixing a defect?
  3. Why doesn’t path coverage prove correctness?
  4. Why use a small failing input?
  5. Why keep try narrow?
  6. Why avoid magic error values?
Model answers
  1. Keeps expectation separate from observed behavior. §9.2
  2. Prevents a fixed defect returning. §9.2
  3. Coverage measures execution, not correctness. §9.4
  4. Removes irrelevant behavior. §9.5
  5. Prevents swallowing unrelated errors. §9.6
  6. A caller may confuse one with a valid result. §9.7

Mixed practice

20 problems. Try each before opening the matching worked answer.

  1. State a contract for is_bigger(x,y).
  2. Which test level checks one function?
  3. Name input classes for a first-item function on lists.
  4. For n < 10, give boundary values on both sides.
  5. Why can branch coverage miss the abs(-1) defect?
  6. Describe bisection debugging.
  7. Why preserve the smallest failing input?
  8. What does int('3.5') raise?
  9. What does [1,2][4] raise?
  10. When raise instead of return -1?
  11. Why avoid a bare except?
  12. When does try/else execute else?
  13. What belongs in finally?
  14. What does a false assert do in a normal run?
  15. Why not assert an access rule?
  16. For eps>0, name an invalid boundary and a nearby valid value.
  17. Why retain a regression test?
  18. An empty grade list causes division by zero. Name a policy.
  19. Should abs test -1 if 2 and -2 already ran?
  20. What makes debugging systematic?
Show worked answers
  1. Assume integer inputs. Return True exactly when x>y; otherwise return False. §9.1
  2. Unit testing checks an isolated function or component. §9.2
  3. Test a singleton, a longer list, and the empty list if its behavior is specified. §9.3
  4. Use 9 and 10; they lie immediately on opposite sides of the decision. §9.3
  5. The tests may take both branches at other values while missing the incorrect boundary. §9.4
  6. Inspect a midpoint, then focus on the half where the first value diverges. §9.5
  7. It makes the defect reproducible and removes unrelated behavior. §9.5
  8. ValueError: the text is not an integer literal. §9.6
  9. IndexError: index 4 is outside the list. §9.6
  10. When no valid result can be produced or -1 may be mistaken for a valid result. §9.7
  11. It can hide unrelated errors; catch the expected exception specifically. §9.6
  12. Only when the try body completes without raising an exception. §9.6
  13. Cleanup that must run whether the operation succeeds or fails. §9.7
  14. It raises AssertionError. §9.8
  15. Python can omit assertions under optimization, so required checks must be explicit. §9.8
  16. eps=0 is excluded; a small positive epsilon is valid. §9.3
  17. It catches the fixed defect if a later change reintroduces it. §9.2
  18. Reject with ValueError, or document an intentional default such as 0.0. §9.7
  19. Yes. -1 is the boundary that exposes the faulty condition. §9.4
  20. 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.

  1. Partition the inputs.
  2. State a boundary and extreme-value check.
  3. Explain the path-coverage limitation.
  4. Describe a debugging strategy.
Show worked answer
  1. Test zero, perfect squares, sub-unit values, irrational roots, and very small and large values. §9.3
  2. Check zero and extremes; evaluate the promised inequality instead of requiring one exact approximation. §9.3
  3. Exercise branches and loop exits, but keep boundary tests because execution coverage does not prove correctness. §9.4
  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.

  1. State a policy for empty grades.
  2. Name unit and regression tests.
  3. Name an integration test.
  4. Explain which checks should be assertions.
Show worked answer
  1. Choose and document rejection or a defined default. §9.7
  2. Test ordinary and empty inputs; preserve the divide-by-zero case as a regression test. §9.2, §9.7
  3. Test a full class report with ordinary and empty records. §9.2
  4. 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).