Show contents
Chapter 5 of 7 · 20 min
Tests serving the architecture
By the end of this chapter, you'll be able to
- Write unit tests with unittest
- Describe the test pyramid and the role of each level
- Replace a dependency with a test double using unittest.mock
- Make a test deterministic
A unit test
A unit test checks a small unit of code (a function, a method) in isolation, by comparing the result obtained with the expected result. Python's unittest module provides what is needed. Here, the tests are launched from the code and a summary is printed:
import unittest
def price_with_tax(price, rate=0.18):
if price < 0:
raise ValueError("negative price")
return round(price * (1 + rate))
class TestPriceWithTax(unittest.TestCase):
def test_default_rate(self):
self.assertEqual(price_with_tax(10000), 11800)
def test_reduced_rate(self):
self.assertEqual(price_with_tax(10000, rate=0.10), 11000)
def test_zero_price(self):
self.assertEqual(price_with_tax(0), 0)
def test_negative_price_refused(self):
with self.assertRaises(ValueError):
price_with_tax(-5)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestPriceWithTax)
result = unittest.TestResult()
suite.run(result)
print(result.testsRun, "tests,", len(result.failures), "failure(s),", len(result.errors), "error(s)")
4 tests, 0 failure(s), 0 error(s)
- each method starting with
test_is a test; assertEqualcompares the result obtained with the expected one,assertRaiseschecks that an error is indeed raised;- we test normal cases, but also boundaries (zero) and errors (negative price).
In a real project, tests are run from the terminal (python -m unittest, or the very popular pytest tool), and continuous integration runs them on every change.
The test pyramid
There are three levels of tests, from the most numerous to the rarest:
End-to-end tests replay a complete user journey. Valuable, but slow and more brittle: keep few of them.
Text description of the animation
- Unit tests check each function in isolation. Fast and precise, they point exactly at what breaks.
- Integration tests check that the pieces work together: the service with a real database, for example.
- End-to-end tests replay a complete user journey. Valuable, but slow and more brittle: keep few of them.
A good architecture makes the base of the pyramid wide and easy: when business rules are isolated in services that receive their dependencies, they are tested without a database or a browser.
Test doubles
To test a service without its real dependencies (sending SMS, payment, database), they are replaced with doubles. The unittest.mock module makes them on the fly: a Mock accepts any call, returns what you ask, and records how it was used.
from unittest.mock import Mock
class ReminderService:
def __init__(self, repository, sms):
self.repository = repository
self.sms = sms
def remind_late(self, today):
sent = 0
for loan in self.repository.late_loans(today):
self.sms.send(loan["phone"], f"Please return “{loan['title']}”")
sent += 1
return sent
repository = Mock()
repository.late_loans.return_value = [
{"phone": "+221700000001", "title": "The Suns of Independence"},
{"phone": "+221700000002", "title": "Allah Is Not Obliged"},
]
sms = Mock()
service = ReminderService(repository, sms)
print(service.remind_late("2026-03-02"))
repository.late_loans.assert_called_once_with("2026-03-02")
print(sms.send.call_count)
print(sms.send.call_args_list[0].args)
2
2
('+221700000001', 'Please return “The Suns of Independence”')
return_valuesets what the double returns: here, two late loans, with no database;assert_called_once_withchecks that the service queried the repository with the right date;- no real SMS was sent, but we know exactly what would have been. The numbers are fictitious.
Mini-lab: break the code, watch the testsPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: test a service with a double
An OrderService checks the stock before validating an order: validate(product, quantity) returns True and calls stock.remove(product, quantity) if stock.available(product) >= quantity, otherwise returns False without removing anything. Write two tests with Mocks, one for each case, and run them.
Hint 1
stock.available.return_value = 10 sets the available quantity.Hint 2
stock.remove.assert_not_called() checks that no removal took place.Show the solution and common mistakes
import unittest
from unittest.mock import Mock
class OrderService:
def __init__(self, stock):
self.stock = stock
def validate(self, product, quantity):
if self.stock.available(product) < quantity:
return False
self.stock.remove(product, quantity)
return True
class TestOrderService(unittest.TestCase):
def test_enough_stock(self):
stock = Mock()
stock.available.return_value = 10
self.assertTrue(OrderService(stock).validate("millet", 4))
stock.remove.assert_called_once_with("millet", 4)
def test_not_enough_stock(self):
stock = Mock()
stock.available.return_value = 2
self.assertFalse(OrderService(stock).validate("millet", 4))
stock.remove.assert_not_called()
r = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(TestOrderService).run(r)
print(r.testsRun, "tests,", len(r.failures), "failure(s),", len(r.errors), "error(s)")
2 tests, 0 failure(s), 0 error(s)
The second test checks an absent behaviour: when refused, no removal. This is often where the most costly bugs hide, such as stock decremented for a refused order.
Common mistakes:
- Only checking the returned value (
False): the test would pass even if the service removed stock before refusing. - Reusing the same
Mockin both tests: the first one's calls would skew the second one's checks. Each test prepares its own doubles.
Summary
- 1A unit test checks a function in isolation; unittest provides assertEqual, assertRaises, etc.
- 2We test normal cases, boundaries and errors.
- 3The test pyramid: many unit tests, some integration tests, a few end-to-end tests.
- 4Doubles (unittest.mock) replace dependencies and record how they are used.
- 5A test must be deterministic: inject randomness and the date instead of being at their mercy.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.