Edexcel International Advanced Level Computer Science, point 19.3.1
In Unit 4 you must be able to identify errors, correct them, produce accurate outcomes, and refine a solution to meet its requirements, usually in a larger program. The ideas are in 9.3.1. The specification points to the Good Programming Practice Guide (GPPG).
a. Testing and debugging
Start from the requirements
List what the program must do, and turn each into a test.
| Requirement | Test |
|---|---|
| A discount of 10% applies to orders over £100 | total(100) is 100, total(100.01) is 90.009 |
| Negative quantities are rejected | add(-1) returns an error |
| Totals are shown to 2 decimal places | Output of 12.5 shows 12.50 |
Unit tests in code
import unittest
def total_after_discount(value):
"""10% off orders over £100."""
return value * 0.9 if value > 100 else value
class TestTotal(unittest.TestCase):
def test_no_discount_at_100(self): # boundary: not over 100
self.assertEqual(total_after_discount(100), 100)
def test_discount_just_over(self): # boundary: just over
self.assertAlmostEqual(total_after_discount(100.01), 90.009)
def test_small_order(self): # normal
self.assertEqual(total_after_discount(40), 40)
def test_zero(self): # boundary
self.assertEqual(total_after_discount(0), 0)
if __name__ == "__main__":
unittest.main()
- Tests are written as code and re-run after every change (regression testing).
assertAlmostEqualcompares floats with a tolerance (18.1.1).- Test normal, boundary and erroneous data (9.3.1).
A test plan
| Test | Data | Expected | Actual | Pass? |
|---|---|---|---|---|
| Normal | 40 | 40 | ||
| Boundary | 100 | 100 | ||
| Boundary | 100.01 | 90.009 | ||
| Erroneous | "abc" | Error handled |
Fill in "Actual" by running the tests. Every failure is investigated.
Debugging method
- Reproduce the fault with the simplest data possible.
- Read the error message and traceback (the last line says what; the lines above say where).
- Form a hypothesis: what could cause this?
- Narrow it down: a breakpoint, stepping, variable watch (6.3.1),
printstatements, or testing the subprogram alone. - Fix one thing, re-run the failing test, then all the tests.
- Add a test that would have caught it.
Types of error (9.3.1): syntax (the program won't run), runtime (crashes: ZeroDivisionError, IndexError), logic (runs but is wrong).
Common logic errors
| Error | Example | Fix |
|---|---|---|
| Off by one | range(1, n) misses n |
range(1, n + 1) |
| Wrong boundary | > instead of >= |
Check the requirement |
| Wrong initial value | largest = 0 with negatives |
Start from the first item |
| Not resetting a variable | A total not set to 0 in a loop | Initialise inside the loop |
| Changing a list while looping | Skipped items | Loop over a copy |
| Integer or float confusion | / instead of // |
Use the right operator |
b. Reviewing and refining
Reviewing is checking the finished solution against the requirements and for quality. Refining is improving it, then testing again.
Review checklist
| Question | Evidence |
|---|---|
| Does every requirement work? | Test results |
| Does it handle invalid and extreme data? | Boundary and erroneous tests |
| Are the outputs accurate and in the right form? | Compare with hand calculations |
| Is the code readable and consistent? | Names, comments, layout (19.2) |
| Is it efficient enough? | Timing (17.2.2), choice of algorithm |
| Is it modular and easy to change? | Structure (19.1.3) |
| Could a user misuse it? | Try bad input |
Refining
- Fix the bugs found.
- Remove repeated code (refactor into a subprogram).
- Improve names and comments.
- Add missing validation and error messages.
- Improve performance where it matters.
- Re-run all the tests after each change.
This is a cycle: test, fix, review, refine, re-test.
Worked example
Task: the requirement says: "The function must return the number of adults (aged 18 or over) in a list of ages, ignoring ages outside 0 to 120." Test and refine this code.
def count_adults(ages):
count = 0
for a in ages:
if a > 18:
count += 1
return count
Test plan and results:
| Data | Expected | Actual | Result |
|---|---|---|---|
[25, 12, 40] |
2 | 2 | Pass |
[18] |
1 | 0 | Fail: boundary |
[] |
0 | 0 | Pass |
[150, 30] |
1 (150 is invalid) | 2 | Fail: validation |
[-3] |
0 | 0 | Pass (by accident) |
Errors found:
- Logic error:
>should be>=(18 counts as an adult). - Missing validation: ages over 120 are counted.
Refined code:
ADULT_AGE = 18
MAX_AGE = 120
def count_adults(ages):
"""Count ages from ADULT_AGE to MAX_AGE; ignore invalid ages."""
return sum(1 for a in ages if ADULT_AGE <= a <= MAX_AGE)
assert count_adults([25, 12, 40]) == 2
assert count_adults([18]) == 1 # boundary now counts
assert count_adults([]) == 0
assert count_adults([150, 30]) == 1 # invalid age ignored
assert count_adults([-3]) == 0
assert count_adults([120, 17]) == 1 # upper and lower boundaries
print("All tests passed")
Review: all the requirements are met, the boundaries (17, 18, 120, 121) have been tested, the code is shorter and uses named constants, and the earlier tests were re-run (regression).
Exam tip: start with the requirements, choose test data (normal, boundary, erroneous) with expected results, run, and record actual results. When correcting code, state the error, its type, and the fix. Re-run all tests after the change. Review against the requirements before finishing.
Check yourself
What is regression testing?
Re-running earlier tests after a change to check that nothing that worked before has been broken.
Which test data would you use for a rule "marks of 50 or more pass"?
Boundary values 49, 50 and 51 (and the limits 0 and 100), plus a normal value and an invalid one.
What are the first steps in debugging?
Reproduce the fault with the simplest data, then read the error message and traceback to see what and where.
What does reviewing a solution involve?
Checking it against the requirements and for quality (accuracy, readability, efficiency, structure), then refining it and re-testing.