Skip to content

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.

Beginner 12 min read·Lesson 285 of 306 in Python Programming

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

Python
import unittest
class TestAdd(unittest.TestCase):
def test_ints(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
  • Subclass TestCase.
  • Methods named test_*.
  • Run with python -m unittest.

Code examples

A first test case

Python
import io
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_ints(self):
self.assertEqual(add(2, 3), 5)
def test_strings(self):
self.assertEqual(add("a", "b"), "ab")
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestAdd)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(result.testsRun, len(result.failures), result.wasSuccessful())
Output
2 0 True

A failing test points at a bug

Python
import io
import unittest
def discount(price, percent):
return price - percent / 100 # bug
class TestDiscount(unittest.TestCase):
def test_ten_percent(self):
self.assertEqual(discount(100, 10), 90.0)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestDiscount)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(result.testsRun, len(result.failures))
print(result.failures[0][1].strip().splitlines()[-1])
Output
1 1
AssertionError: 99.9 != 90.0

More examples

Fixtures, exceptions and subtests

Python
import io
import unittest
class Cart:
def __init__(self):
self.items = {}
def add(self, name, price, qty=1):
if price < 0 or qty < 1:
raise ValueError("invalid item")
old_qty = self.items.get(name, (price, 0))[1]
self.items[name] = (price, old_qty + qty)
def total(self):
return sum(p * q for p, q in self.items.values())
class TestCart(unittest.TestCase):
def setUp(self):
self.cart = Cart()
def test_empty_total(self):
self.assertEqual(self.cart.total(), 0)
def test_add_accumulates(self):
self.cart.add("pen", 20)
self.cart.add("pen", 20, 2)
self.assertEqual(self.cart.items["pen"], (20, 3))
def test_total_floats(self):
self.cart.add("sweet", 0.1, 3)
self.assertAlmostEqual(self.cart.total(), 0.3)
def test_invalid_items(self):
for price, qty in [(-1, 1), (10, 0)]:
with self.subTest(price=price, qty=qty):
with self.assertRaises(ValueError):
self.cart.add("x", price, qty)
print(unittest.defaultTestLoader.getTestCaseNames(TestCart))
result = unittest.TextTestRunner(stream=io.StringIO()).run(unittest.defaultTestLoader.loadTestsFromTestCase(TestCart))
print(result.testsRun, result.wasSuccessful())
Output
['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:

TextOutput
['test_add_accumulates', 'test_empty_total', 'test_invalid_items', 'test_total_floats']
4 True

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

def test_1_add(self): self.cart.add(...)
def test_2_total(self): ... # relies on test_1

Prefer

Create the state each test needs in setUp or inside the test.

Test order isn't guaranteed and shared state hides bugs.

assertEqual with floats

Avoid

self.assertEqual(0.1 * 3, 0.3)

Prefer

self.assertAlmostEqual(0.1 * 3, 0.3)

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

  1. 1
    Write unittest tests for a function that checks whether a password is strong.
  2. 2
    Add 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?
Practise this topic