Skip to content
dreamcode
dreamcode
Map
Testing
Lesson 67 of 77
+15 XP on finish
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.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Add assert not is_leap(1900) and assert is_leap(2000), then fix is_leap so every assert passes (years divisible by 100 are not leap years unless they are also divisible by 400). The program should still print tests done.

Press Run to check your work.