Testing basics
Turn requirements into executable examples with independent expectations.
On this page
The concept
A test usually arranges inputs, acts by calling the operation, and asserts an expected result. Choose normal, boundary, empty, and invalid cases from the requirement. A shipping rule with a threshold of 100 needs checks just below and exactly at 100, not only at distant values.
Assertions are appropriate inside tests because a failure should stop the test and reveal the discrepancy. They are not a substitute for runtime input checks. Regression tests preserve behavior that previously broke, making later changes safer.
Worked example
def shipping_fee(total):
if total < 0:
raise ValueError("total cannot be negative")
return 0 if total >= 100 else 5
assert shipping_fee(0) == 5
assert shipping_fee(99.99) == 5
assert shipping_fee(100) == 0
assert shipping_fee(150) == 0
try:
shipping_fee(-1)
except ValueError:
print("Invalid input was rejected.")
else:
raise AssertionError("negative totals must fail")
print("5 cases checked")Trace the result
- The shipping function rejects negative input and otherwise chooses between two fees.
- The assertions cover zero, 99.99, 100, and 150.
- The explicit exception check fails deliberately if a negative total is accidentally accepted.
Invalid input was rejected.
5 cases checkedLine-by-line walkthrough
Lines 1–4: def shipping_fee(total):
Define the function shipping_fee with input names total. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Lines 2–3: if total < 0:
Evaluate total < 0. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.
Line 3: raise ValueError("total cannot be negative")
Raise ValueError('total cannot be negative'). Normal execution stops here unless an enclosing handler catches it. A from cause, when present, preserves the reason for a translated error.
Line 4: return 0 if total >= 100 else 5
Evaluate 0 if total >= 100 else 5 and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Line 7: assert shipping_fee(0) == 5
Check shipping_fee(0) == 5 and raise AssertionError if it is false. This is a test/internal assumption; optimized Python may remove assertions, so it must not enforce untrusted-input rules.
Line 8: assert shipping_fee(99.99) == 5
Check shipping_fee(99.99) == 5 and raise AssertionError if it is false. This is a test/internal assumption; optimized Python may remove assertions, so it must not enforce untrusted-input rules.
Line 9: assert shipping_fee(100) == 0
Check shipping_fee(100) == 0 and raise AssertionError if it is false. This is a test/internal assumption; optimized Python may remove assertions, so it must not enforce untrusted-input rules.
Line 10: assert shipping_fee(150) == 0
Check shipping_fee(150) == 0 and raise AssertionError if it is false. This is a test/internal assumption; optimized Python may remove assertions, so it must not enforce untrusted-input rules.
Lines 11–16: try:
Run the protected body. A matching except handles its specified failure. An else suite runs after a successful try body, and finally runs when leaving the construct. This structure should handle expected failures without concealing unrelated bugs.
Line 12: shipping_fee(-1)
Call shipping_fee with the displayed arguments. This call may have an effect even when its return value is not assigned.
Alternative or completion suite: read the statements below as part of this branch.
Line 16: raise AssertionError("negative totals must fail")
Raise AssertionError('negative totals must fail'). Normal execution stops here unless an enclosing handler catches it. A from cause, when present, preserves the reason for a translated error.
Handler for ValueError: control reaches this suite only for a matching exception from the protected body.
Line 14: print("Invalid input was rejected.")
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 17: print("5 cases checked")
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Common mistake
Do not calculate the expected result by repeating the implementation's expression. Derive it from the requirement instead.