32. Testing
Tests help you check that your code behaves the way you expect. Even small functions benefit from a few automated checks. The standard library includes unittest so you can start testing without extra dependencies.
32.1. Simple assertions
The simplest test checks that a function returns the value you expect.
1def add(a, b):
2 return a + b
3
4
5assert add(2, 3) == 5
6assert add(-1, 1) == 0
32.2. Using unittest
unittest gives you test classes, setup hooks, and richer assertions.
1import unittest
2
3
4def is_even(n):
5 return n % 2 == 0
6
7
8class TestIsEven(unittest.TestCase):
9 def test_even_number(self):
10 self.assertTrue(is_even(2))
11
12 def test_odd_number(self):
13 self.assertFalse(is_even(3))
14
15 def test_zero(self):
16 self.assertTrue(is_even(0))
17
18
19if __name__ == '__main__':
20 unittest.main()
32.3. Why testing matters
Tests make refactoring safer and catch regressions early. They also serve as executable examples of how a function is supposed to behave.
32.4. Exercise
Write tests for a function named is_even. Check at least one even number, one odd number, and zero.
32.4.1. Solution
1def is_even(n):
2 return n % 2 == 0
3
4assert is_even(2) is True
5assert is_even(3) is False
6assert is_even(0) is True