Python theorytheory 0/50 · 0%
Testing · medium

34. Unit testing with unittest/assert

Writing checkable assertions and simple test functions.

Python's built-in `assert` statement raises `AssertionError` if the condition is false, and is the simplest form of testing.

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

assert add(2, 3) == 5, "add(2, 3) should be 5"

The standard library's `unittest` module provides structured test classes:

python
import unittest

class TestAdd(unittest.TestCase):
    def test_basic(self):
        self.assertEqual(add(2, 3), 5)
        self.assertTrue(add(0, 0) == 0)

Good tests cover typical inputs, edge cases (zero, negative, empty), and expected failure modes.

Check your understanding

  1. 1. What does `assert cond, "msg"` do when cond is False?

  2. 2. What must a unittest test class inherit from?

  3. 3. Why test edge cases like zero or empty input?