Lesson 13: Testing Your Code

⏱ ~35 min Lesson 13 of 14 💚 Free

Professional developers write tests — code that checks that other code works correctly. Tests catch bugs before they reach users, make refactoring safer, and serve as living documentation of what your code is supposed to do.

Key Concepts

Why Test?

Manual testing is slow and forgetful. Automated tests run in seconds and catch regressions — bugs introduced when you change existing code. Tests give you confidence to make changes.

unittest Module

import unittest
class TestMyFunction(unittest.TestCase):
def test_basic(self):
self.assertEqual(add(2, 3), 5)
def test_negative(self):
self.assertEqual(add(-1, 1), 0)
if __name__ == '__main__':
unittest.main()

Common Assertions

assertEqual(a, b) — a == b
assertNotEqual(a, b) — a != b
assertTrue(x) — x is truthy
assertRaises(Error, func, args) — func raises Error
assertIn(item, collection) — item in collection

pytest (Popular Alternative)

pytest is simpler: just write functions starting with test_:
def test_add():
assert add(2, 3) == 5
Run with: pytest tests/
pytest auto-discovers tests and gives clear output.

✅ Check Your Understanding

1. What is the main purpose of automated tests?

2. What does assertEqual(a, b) check?

3. A regression is: