🎓 A1Learner
🔍
0 of 52 lessons completed

Python Testing a Small Module

A test row is a set of assert checks for one module. The row ends with a pass line.

One function, two checks

double must turn 3 into 6 and 0 into 0. Both checks pass.

def double(n):
    return n * 2

assert double(3) == 6
assert double(0) == 0
print("double: pass")

An edge case at zero

Zero divided by 5 is 0. The edge case passes with the normal one.

def divide(a, b):
    return a / b

assert divide(10, 2) == 5
assert divide(0, 5) == 0
print("divide: pass")

An empty list edge case

first must hand back 7 for a full list. An empty list must hand back None.

def first(nums):
    if nums:
        return nums[0]
    return None

assert first([7, 8]) == 7
assert first([]) is None
print("first: pass")

A failing check names the function

double(3) is 6, not 7. The check fails and the print names double.

def double(n):
    return n * 2

try:
    assert double(3) == 7
except AssertionError:
    print("double failed its check")

Example

def with_tax(price):
    return price * 1.2

def cheapest(prices):
    return min(prices)

assert with_tax(10) == 12.0
assert with_tax(0) == 0
assert cheapest([5, 2, 8]) == 2
assert cheapest([9]) == 9
print("prices: all checks passed")

Key points

  • Test row: a set of assert checks for one module
  • Test each function with a normal case and an edge case
  • Edge case: an input at the edge, like zero or an empty list
  • Use one assert per fact, so a failure points at one fact
  • Print a pass line when all checks pass
  • Run the checks after every change to the module

In this example, with_tax and cheapest share one module. Four checks test both functions. Zero and a one-item list are the edge cases. The line prints only after the fourth check passes.

Note

This course tests with assert, not with a test framework.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Why test the empty list as well as a full list?