Module 19 · Debugging, Testing and Best Practices — topic 7 of 15
Unit testing
Testing small units of code automatically with unittest: TestCase classes, assert methods, running tests and reading results, setUp for shared fixtures, assertRaises, assertAlmostEqual and subTest.
Learning objectives
- Write unittest test cases
- Run tests and interpret results
- Use setUp, assertRaises, assertAlmostEqual and subTest
Definition
A unit test checks that a small piece of code — usually one function or class — behaves correctly for given inputs. Python's built-in unittest module provides TestCase classes, assertion methods and a test runner.
Introduction
Every time you change code, you could re-check everything by hand — or run a test suite that checks it all in a second.
Why it matters
Automated tests catch regressions immediately, make refactoring safe and document how code is supposed to behave.
Detailed explanation
A unit is a small piece of behaviour: a function, a method, a class. Unit tests check units in isolation.
With unittest, create a class that inherits from unittest.TestCase; each method whose name starts with test_ is a test.
Assertion methods report clear failures: assertEqual, assertTrue, assertIn, assertIsNone, assertAlmostEqual (for floats) and assertRaises (for expected exceptions).
setUp runs before each test and creates fresh objects, so tests don't affect each other.
subTest runs one check for several inputs and reports each failing input separately.
Run tests from the command line with python -m unittest (discovers test_*.py files) or from code with a TextTestRunner.
A result has testsRun, failures (assertions that failed) and errors (unexpected exceptions); wasSuccessful() is True when there are neither.
Good unit tests are fast, independent, repeatable and test one behaviour each, with descriptive names.
Syntax
- Subclass TestCase.
- Methods named test_*.
- Run with python -m unittest.
Code examples
A first test case
2 0 True
A failing test points at a bug
1 1 AssertionError: 99.9 != 90.0
More examples
Fixtures, exceptions and subtests
['test_add_accumulates', 'test_empty_total', 'test_invalid_items', 'test_total_floats'] 4 True
Step-by-step explanation
- setUp gives every test a brand-new empty cart.
- assertAlmostEqual avoids the 0.1 * 3 floating-point trap.
- subTest checks two invalid inputs and would report each failure separately.
Expected output
Running “Fixtures, exceptions and subtests” prints exactly:
Practical applications
- Test suites run automatically on every commit in CI.
- Libraries shipping thousands of unit tests.
Best practices
- One behaviour per test, with a descriptive name.
- Keep tests independent and fast.
- Run tests after every change.
Common mistakes
Tests that depend on each other
Avoid
Prefer
Test order isn't guaranteed and shared state hides bugs.
assertEqual with floats
Avoid
Prefer
Floating-point results are rarely exact.
Important notes
- pytest (next lesson) can run unittest tests too.
Key takeaways
- Unit tests check small pieces of code automatically.
- TestCase methods named test_* use assert methods.
- setUp, assertRaises and subTest help organise tests.
Try it yourself
- 1Write unittest tests for a function that checks whether a password is strong.
- 2Add a test that fails, read the report, then fix the code.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhat is printed?