Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 7 · Lesson 3 · Core

Testing with assert and edge cases

Work out expected answers by hand, test normal values and edges, and use assert to check them.

  • 50 minutes
  • Serves O5
  • Assumes M7.L2

Phase 1: Prepare

Step 1 Warm-up recall

From M7.L2: why should an except name its error?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • write a test with assert (Foundation);
  • choose normal and edge cases (Core);
  • read a failed test (Core).

Phase 2: Teach

Step 3 A familiar example

A teacher checks a marking scheme by marking a paper whose total she already knows. A test does this for a function: the answer is known before the code is run.

Step 4 Clear explanation

A test runs your code on an input whose correct answer you worked out by hand. assert stops with an AssertionError if the answer is wrong.

def grade(mark):
    if mark >= 70:
        return "A"
    elif mark >= 50:
        return "B"
    return "C"

assert grade(85) == "A"
assert grade(70) == "A"
assert grade(69) == "B"
assert grade(50) == "B"
assert grade(49) == "C"
print("All tests passed")
All tests passed
Expected: by hand0Actual: from code1Same? pass or fail2A test is a question with a known answer
A test compares what the code gives with what you worked out by hand, for normal values and for edges.

Choose cases on purpose. Include a normal value, the boundaries (70 and 69, 50 and 49) as in Module 2, and any odd input such as an empty list or zero. A failed assert shows AssertionError and the line of the test that failed, which tells you the input that broke it.

Passing tests do not prove a program is perfect; they show it is right for the cases you thought of. So the best tests include the cases that have already caused trouble.

Step 5 Worked example (4 marks)

A function double(n) returns n + 2 by mistake. Which of these asserts fail: double(2) == 4, double(3) == 6, double(0) == 0?

  1. double(2) gives 4, so the first test passes by chance. (1 mark)
  2. double(3) gives 5, not 6, so it fails. (1 mark)
  3. double(0) gives 2, not 0, so it fails. (1 mark)
  4. Answer: the second and third fail; the first hides the fault. (1 mark)

Go deeper: the professor's notes

Test with answers you worked out by hand, including edges.
Normal

Typical.

Edge

Boundary.

Odd

Empty or zero.

Expectedby handRunthe codeCompareassertKeepthe tests
Test

Cases

InputExpected
grade(70)A
grade(69)B

At work: A function

You need to trust a new function.

  1. List three cases.
  2. Write the asserts.

What a careful practitioner decides. Choose edge cases on purpose.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. The expected answer of a test should be:

2. A failed assert raises:

3. Good test cases include:

4. A passing test suite shows the code is:

Phase 4: Close

Step 7 Recap

  • A test compares the code with an answer worked out by hand.
  • assert stops when the answer is wrong.
  • Test normal values, boundaries and odd inputs.

Step 8 Exit ticket (ungraded)

Write three assert lines for a function is_even, including zero.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write five tests, including two boundaries, for a function that gives a delivery fee by weight.

In industry: Apollo 11: an alarm that did not stop the landing

During the lunar descent of 20 July 1969 the guidance computer showed 1201 and 1202 alarms because it had too many jobs for its time. The software was written to restart and keep the most important jobs, and ground control judged it safe to continue.

Link to this lesson. Plan for overload and failure ahead of time: a program that degrades safely is better than one that stops.

Source: Apollo 11 Lunar Surface Journal; MIT Instrumentation Laboratory memorandum of 4 August 1969 as summarised by ScienceBlog

Common mistakes

MistakeWhy it fails
Copying the output as the expected answerWork it out by hand first.
Testing only easy casesAdd boundaries and odd inputs.
Stopping at the first passThink of how it could still be wrong.

Limits. Larger projects use test tools that run many tests and report them; the idea is the same.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · What do try and except do?
tryrisky stepexceptnamed errorThencarry on
try / except

try runs a risky step; except handles a named error if it happens, so the program can continue safely. Use it for a text entry where a number is needed.

Card 2 of 3 · Why should you never use a bare except?
CatcheseverythingHidesmistakesUsenamed errors
Bare except

It catches every error, including your own mistakes, and hides them. A loud failure becomes a quiet wrong answer.

Card 3 of 3 · What is a test?
Expectedby handActualfrom codeCompareassert
Test

Run the code on an input whose answer you worked out by hand, then compare. grade(70) should be A; if it is not, the test fails.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards