Python · Chapter 44 of 45

Testing with unittest

The built-in `unittest` module lets you write automated tests. Alternative: `pytest` (more concise) — very popular.

Good tests give you confidence to refactor without breaking things.

Structure

Create a subclass of `unittest.TestCase`. Methods starting with `test_` are auto-run. Use `assertEqual`, `assertTrue`, `assertRaises`.

Running

`python -m unittest` discovers and runs tests in files named `test_*.py`.

Example 1 (python)
import unittest

def add(a, b): return a + b

class TestAdd(unittest.TestCase):
    def test_positive(self):
        self.assertEqual(add(2, 3), 5)
    def test_negative(self):
        self.assertEqual(add(-1, -1), -2)

unittest.main(argv=[""], exit=False)
Output
..
OK

Two tests both pass.

Example 2 (python)
# pytest style — same idea, less boilerplate
def add(a, b): return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, -1) == -2
Output
PASSED

pytest just uses plain `assert`.

Key points

  • Standard library: `unittest`.
  • Popular alternative: `pytest`.
  • Tests give confidence during refactors.
  • Aim for many small, focused tests.
💡 Note: Run tests automatically on every commit with a CI service (GitHub Actions, GitLab CI, etc.).

📝 Quick Quiz

1. Test methods must start with:

2. A popular alternative to unittest is:

3. In unittest you extend: