Testing with unittest
Published by Brayan K
unittest is Python's built-in testing framework for writing small checks that confirm your code produces the right results and keeps producing them as it changes.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A passing test must be able to fail
Suppose delivery is free from 30 pounds, including exactly 30. A test of an order worth 40 cannot tell you whether the code uses > or >=. Choose inputs at the boundary as well as on either side. The expected value comes from the delivery rule, not from copying the implementation into the test.
import unittest
def delivery(total):
return 0 if total > 30 else 4
class DeliveryTests(unittest.TestCase):
def test_at_free_delivery_boundary(self):
self.assertEqual(delivery(30), 0)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(DeliveryTests)
result = unittest.TestResult()
suite.run(result)
print("tests:", result.testsRun)
print("failures:", len(result.failures))
print(result.failures[0][1].splitlines()[-1])
# ✅ Expected output:
# tests: 1
# failures: 1
# AssertionError: 4 != 0The test deliberately exposes a bug. assertEqual(actual, expected) records a failure when the values differ. The result object collects it so the demonstration can show the assertion message without a clock or a machine path. A normal terminal runner also reports a traceback, which points back to the failed assertion.
import unittest
def delivery(total):
return 0 if total >= 30 else 4
class DeliveryTests(unittest.TestCase):
def test_below_boundary(self):
self.assertEqual(delivery(29), 4)
def test_at_boundary(self):
self.assertEqual(delivery(30), 0)
def test_above_boundary(self):
self.assertEqual(delivery(31), 0)
result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(DeliveryTests).run(result)
print(result.testsRun, result.wasSuccessful())
# ✅ Expected output:
# 3 TrueA green result means these cases passed; it does not prove every possible input is correct. A test that merely calls delivery(30) without checking its return value would miss this bug. Choose an equality assertion for a specific price, assertIsNone for absence, and assertRaises for a deliberately rejected input.
A method name can leave a test undiscovered
The default loader selects methods whose names begin with test. Use the familiar test_ prefix to make that intention obvious. A method called check_delivery is an ordinary helper; defining it does not make the loader run it.
import unittest
class DeliveryTests(unittest.TestCase):
def check_delivery(self):
self.fail("This method was not discovered")
def test_delivery(self):
self.assertEqual(4, 4)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(DeliveryTests)
print("discovered:", suite.countTestCases())
result = unittest.TestResult()
suite.run(result)
print("ran:", result.testsRun)
# ✅ Expected output:
# discovered: 1
# ran: 1When working locally, save tests in a file such as test_delivery.py and run python -m unittest discover -v from the project directory. Discovery normally looks for test*.py files that Python can import. Check the number of tests as well as the success status: zero successful tests is no evidence about your program. The examples here load a named class explicitly so they work inside the browser editor.
Failures, errors, and expected exceptions mean different things
import unittest
class Examples(unittest.TestCase):
def test_wrong_result(self):
self.assertEqual(2 + 2, 5)
def test_missing_key(self):
{}["total"]
result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(Examples).run(result)
print("failures:", len(result.failures))
print("errors:", len(result.errors))
print("successful:", result.wasSuccessful())
# ✅ Expected output:
# failures: 1
# errors: 1
# successful: FalseA failed assertion means an expectation was not met. An unexpected exception, such as the missing-key access above, is recorded as an error. Either requires investigation. An exception you intend the function to raise is different: wrap the call in with self.assertRaises(...). Passing a call as an already-evaluated argument would run it before the assertion can catch anything.
import unittest
def quantity(text):
value = int(text)
if value < 1:
raise ValueError("quantity must be positive")
return value
class QuantityTests(unittest.TestCase):
def test_rejects_zero(self):
with self.assertRaises(ValueError) as caught:
quantity("0")
self.assertEqual(str(caught.exception), "quantity must be positive")
def test_accepts_positive(self):
self.assertEqual(quantity("3"), 3)
result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(QuantityTests).run(result)
print(result.testsRun, result.wasSuccessful())
# ✅ Expected output:
# 2 TrueKeep only the operation expected to fail inside the context. Otherwise an unrelated line raising the same exception can make a broken test pass. Catch/control-flow mechanics belong to Exception Handling; here the question is which failure your test promises to recognize.
Give each test its own mutable state
A list stored on the test class is shared. One test can append to it and leave another test dependent on execution order. setUp runs before each test method; create a fresh list on self there. Do not repair order dependence by naming methods so one happens to run first.
import unittest
class BasketTests(unittest.TestCase):
def setUp(self):
self.basket = []
def test_add(self):
self.basket.append("tea")
self.assertEqual(self.basket, ["tea"])
def test_starts_empty(self):
self.assertEqual(self.basket, [])
result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(BasketTests).run(result)
print(result.testsRun, result.wasSuccessful())
# ✅ Expected output:
# 2 TrueUse tearDown for cleanup after a successfully completed setUp. If setup itself can fail after acquiring a resource, register addCleanup as soon as acquisition succeeds: those registered callbacks still run when setup fails. Cleanup callbacks run in reverse registration order.
import unittest
events = []
class SetupTests(unittest.TestCase):
def setUp(self):
events.append("opened")
self.addCleanup(events.append, "closed")
raise RuntimeError("setup stopped")
def tearDown(self):
events.append("tearDown")
def test_unused(self):
events.append("test")
result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(SetupTests).run(result)
print(events)
print("errors:", len(result.errors))
# ✅ Expected output:
# ['opened', 'closed']
# errors: 1Complete the test without copying the function
The shipping rule is free at 50 and above, otherwise 5. Fill the first blank with the expected price at the boundary; fill the second with the assertion method that compares two values. The literal hints are in the editor if you get stuck.
import unittest
def shipping(total):
return 0 if total >= 50 else 5
class ShippingTests(unittest.TestCase):
def test_boundary(self):
self.assertEqual(shipping(50), ___)
def test_below(self):
self.___(shipping(49), 5)
result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(ShippingTests).run(result)
print(result.testsRun, result.wasSuccessful())
# 👉 replace ___ with 0
# 👉 replace ___ with assertEqual
# ✅ Expected output:
# 2 TrueCheck several inputs without stopping at the first mismatch
A plain loop ends at its first failed assertion. A subTest context records a failure for that case and lets the loop continue. The surrounding method is still one test, so the test count does not become the number of rows.
import unittest
seen = []
class DoubleTests(unittest.TestCase):
def test_cases(self):
for value, expected in [(1, 2), (2, 5), (3, 6)]:
with self.subTest(value=value):
seen.append(value)
self.assertEqual(value * 2, expected)
result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(DoubleTests).run(result)
print("visited:", seen)
print("test methods:", result.testsRun)
print("failed cases:", len(result.failures))
# ✅ Expected output:
# visited: [1, 2, 3]
# test methods: 1
# failed cases: 1Mocking external dependencies and pytest fixture scopes are covered in Testing with pytest: Fixtures, Parametrisation & Mocks. Use that material when a test depends on something outside the function; these examples deliberately use pure functions and local state.
Write tests for a ticket limit
Write reserve(available, requested): return the remaining count for a positive request no larger than availability; otherwise raise ValueError. Test a partial reservation, an exact sell-out, zero, and a request larger than availability. Print the number of tests and whether they all passed. Try breaking the comparison after the tests pass and confirm the exact sell-out test catches it.
import unittest
def reserve(available, requested):
if requested <= 0 or requested > available:
raise ValueError("request outside availability")
return available - requested
class ReservationTests(unittest.TestCase):
def test_partial(self):
self.assertEqual(reserve(5, 2), 3)
def test_sell_out(self):
self.assertEqual(reserve(5, 5), 0)
def test_zero(self):
with self.assertRaises(ValueError):
reserve(5, 0)
def test_too_many(self):
with self.assertRaises(ValueError):
reserve(5, 6)
result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(ReservationTests).run(result)
print(result.testsRun, result.wasSuccessful())
# ✅ Expected output:
# 4 TrueThe function assumes integer inputs and nonnegative availability. Tests for those assumptions would be separate requirements, not something these four cases already prove. For runner options and lifecycle details, consult the unittest reference.
Practice quiz
Delivery is free at 30 and above. Which input distinguishes total > 30 from total >= 30?
- 29
- 31
- 30
- 40
Answer: 30. Only the boundary itself takes different branches under > and >=.
What does this program print? import unittest class Checks(unittest.TestCase): def check_total(self): self.fail("wrong") def test_total(self): self.assertEqual(4, 4) print(unittest.defaultTestLoader.loadTestsFromTestCase(Checks).countTestCases())
- 1
- 0
- 2
- AssertionError
Answer: 1. The default loader finds test_total; check_total is a helper.
A test raises an unexpected KeyError before reaching an assertion. How does unittest record it?
- A failure
- A skipped test
- A passing test
- An error
Answer: An error. Unexpected exceptions are errors; failed assertions normally appear in failures.
Which form checks that parse("bad") raises ValueError?
- self.assertEqual(parse("bad"), ValueError)
- with self.assertRaises(ValueError): parse("bad")
- self.assertRaises(ValueError, parse("bad"))
- try: parse("bad") except Exception: pass
Answer: with self.assertRaises(ValueError): parse("bad"). The context is active before the call. An already-evaluated call runs too early; a catch-all can hide the wrong exception.
Two tests both need an empty mutable cart. Where should self.cart = [] normally go?
- In setUp, before each test
- On the class, shared by tests
- Only in the first test
- In tearDown, after each test
Answer: In setUp, before each test. setUp gives each test its own starting state without relying on ordering.
setUp acquires a resource, registers addCleanup, then raises. Which registered action still runs?
- The test method
- tearDown
- The addCleanup callback
- The next assertion
Answer: The addCleanup callback. Registered cleanups run even if setUp fails; tearDown requires successful setup.
One test method uses subTest over three rows; the middle row fails. What happens with the default result collector?
- The third row is skipped; testsRun is one
- The third row runs; testsRun counts one method
- The third row runs; testsRun is three
- The whole suite stops; testsRun is zero
Answer: The third row runs; testsRun counts one method. subTest records the individual failure while continuing the method; it does not create three test methods.
All four reservation tests pass. Which conclusion is justified?
- Every possible input is safe
- The tests prove there are no bugs
- Input validation is complete
- The four specified cases behaved as asserted
Answer: The four specified cases behaved as asserted. Tests give evidence for their cases. Unchecked types, ranges and interactions still need requirements and tests.
Continue this course
- Previous: Hashing with hashlib
- Next: Advanced Type Hints (Generics, Protocol, TypedDict) — Generics with TypeVar, structural typing with Protocol, and TypedDict
- Quick reference: Python cheat sheet