Lesson · Testing
unittest
65 min readunittest
`unittest` is Python's batteries-included test framework. Its assertions, fixtures, discovery, and lifecycle hooks are enough to build disciplined unit and integration suites without third-party dependencies.
Learning goals
- Organize tests into a
TestCasesubclass and explain why each test method starts with fresh state. - Choose the assertion method that names the check (
assertEqual,assertTrue,assertRaises) instead of relying on a bareassert. - Place per-test preparation in
setUpand cleanup intearDown, and say whensetUpClassis the right level. - Run a suite with
unittest.main()and with discovery, and explain which filenames and method names get collected. - Explain what a fixture is and keep it small enough that a failure still points at one behavior.
Mental model
The runner owns the lifecycle, so isolation is a choice you make with fixture scope: per-test state in setUp for freshness, per-class state in setUpClass for expensive preparation that can safely be shared.
Mental model
read it top to bottom
runner collects: test*.py files → TestCase classes → methods starting with test_
for every test method:
setUp → test method (assertions) → tearDown repeats per method
setUpClass ........................................... tearDownClass once per classCore idea
unittest gives structure to the plain checks from a script: a TestCase groups related tests, assertion methods report failures with context, and the runner manages setup and cleanup around every method. Values created in setUp are fixtures, and their scope decides the isolation you get: per test for fresh state, per class for shared expensive preparation. The naming rules, test*.py files and test_ methods, are what make discovery and the runner find everything.
Test cases
A test case is a unittest.TestCase subclass whose test_ methods each check one behavior. The runner instantiates the class fresh for every method, so tests do not inherit each other's instance state.
Assertions
Assertion methods such as assertEqual, assertTrue, and assertRaises check a condition and record the outcome instead of printing: a failing call raises AssertionError internally and the runner marks the test failed. They produce better diagnostics than a bare assert, naming the expected and actual values.
Setup/teardown
setUp runs before each test method and tearDown after it, even when the test fails, so per-test state is built and cleaned in the same order every time. Expensive whole-class preparation belongs in setUpClass and tearDownClass, which the runner calls once per class.
Test discovery
Test discovery finds tests without an explicit list: python -m unittest walks the directory tree looking for files matching test*.py and collects TestCase classes and methods whose names start with test. The naming conventions are the contract, which is why a file or method that misses them silently runs nothing.
Fixtures
A fixture establishes reusable test state and cleans it up afterward. Keep fixtures small and intention-revealing so tests do not depend on hidden global setup.
Walkthrough
AddTests(unittest.TestCase)groups the two checks, and the runner creates a fresh instance for each method, so nothing leaks between tests unless a fixture puts it there.test_positive_numberscallsself.assertEqual(add(2, 3), 5); when the check fails,assertEqualreports expected versus actual instead of only stopping the run.test_stringsproves the same function works through+for strings:"a" + "b"is"ab", and a type mismatch inside the test body would surface as an error, which the report counts separately from a failure.- Predict before running: how many test methods the runner finds, what the report calls a
TypeErrorraised inside a test, and what a method namedcheck_positivewould contribute.
Experiments to try
- Add
test_examplewithself.assertEqual(add(2, 2), 5)and compare its report with what a bareassert add(2, 2) == 5prints. - Add a test that calls
add("a", 1)with no expectation and note that the report classifies theTypeErroras an error rather than a failure. - Run the file with
python -m unittest -vand compare the verbose output with the default dots; list what verbose adds per test. - Add a
setUpthat prints and confirm it runs before each of the two methods, then move the print tosetUpClassand confirm it runs once; use the counts to pick the right scope.
Common mistakes
- Writing tests as plain functions or naming methods without the
testprefix: the runner collects neither, and a suite with zero collected tests still reportsOK, so read the counted total. - Expecting
setUpto run once per class: it runs before every method, so anything accumulated there starts fresh each time andsetUpClassis the per-class hook. - Wrapping the check in
try/exceptto keep a test alive: theAssertionErrorgets swallowed and the test passes no matter what; let failures propagate and useassertRaisesfor expected exceptions. - Comparing values with a bare
assert: it works, but the failure shows only the expression, whileassertEqual(expected, actual)prints both values where you need them.
Practice: Easy
- Run the worked example and read the summary counts; then rename
test_positive_numberstocheck_positive, run again, and explain the new count. - Add
test_zerocoveringadd(0, 5) == 5; run the file and confirm the count reaches three. - Change
test_stringsto compareadd("a", "b")with"ba"and read the failure; note that the report shows both'ba'and'ab'.
Practice: Medium
- Add a
setUpthat storesself.pair = (2, 3)and rewrite both tests to read it; then add a test with different inputs and decide whether it should build its own state. - Add a
tearDownthat records a line and confirm the ordersetUp → test → tearDownby printing from each; then move the recording tosetUpClassandtearDownClassand compare how often each hook fires. - Replace a test that lets
add("a", 1)raise with one usingassertRaises(TypeError); compare the two reports.
Practice: Hard
- Build a
TestCasefor the previous lesson'snormalize_namewith four tests: whitespace trimming, capitalization, empty input, and a non-string input throughassertRaises(AttributeError); run with-vand check every method appears in the report. - Failure lab: leave one failing comparison, raise an unexpected exception in another test, and name a third method
check_something; run the suite and explain the failure, error, and silent-skip patterns in the output. - Write one class sharing an expensive object through
setUpClassand one creating it per test insetUp; describe the isolation difference and pick the right level for a database connection versus an in-memory value.
Lesson checklist
- I can group related checks in a
TestCaseand predict how many tests the runner will report. - I can pick the assertion method that produces the most useful failure output.
- I can place preparation and cleanup in
setUp/tearDownand say whensetUpClassis the right scope. - I can run a file through
unittest.main()and through discovery, and explain which names get collected.
Remember
`unittest` turns checks into structured tests: a `TestCase` holds the methods, assertion methods record failures with expected and actual values, and the runner wraps every method with `setUp` and `tearDown`. Fixtures decide the isolation you get, per test or per class, and the naming conventions decide what discovery and the runner can even see. Read the summary counts, because a suite that collected nothing still reports success.
Interview angles
What is the main purpose of **Test cases**?+
A test case is a unittest.TestCase subclass whose test_ methods each check one behavior. The runner creates a fresh instance per method, so tests do not inherit each other's instance state.
What should you pay attention to when using **Assertions**?+
Assertion methods such as assertEqual, assertTrue, and assertRaises check conditions and record failures with context: a failing call raises AssertionError internally and the runner reports expected versus actual values.
How does **Setup/teardown** fit into this lesson?+
setUp runs before each test method and tearDown after it, even when the test fails, so per-test state is built and cleaned in a fixed order. Whole-class preparation belongs in setUpClass and tearDownClass, which run once.
Why can a test file report `OK` while one of your test methods never ran?+
unittest collects methods whose names start with test; a method named check_..., or written as a plain function, is invisible to the runner and the suite still reports OK for the tests it did run. Read the counted total in the summary.