PYTHON EXPERTChapter 11 · Python Expert
Testing your code
Tests are code that checks code. The simplest test is an assert: assert add(2, 2) == 4 does nothing when true and raises AssertionError when false. The built-in unittest module groups tests into classes with helpful checks like assertEqual, and tools such as pytest run them for you. Writing a few tests for a tricky function catches a bug the moment you introduce it.
Worked example
How it reads
- Each
test_method checks one behaviour assertEqual(actual, expected)explains exactly what differed when it fails- Good tests cover the edges: empty input, spaces, zero, negatives

Cloud tip: Found a bug? Write a test that fails because of it first, then fix the code. The bug can never quietly come back.


