Testing a Back End: Unit Tests, Server Tests and Failure Reports
Test back-end code with Python's unittest: pure functions, a real server on a free port, and the error paths, read a real failing test report, and cross-check the results by running the same suite as a separate process.
In this lesson you will
- Write unit tests for pure functions
- Test routes against a live server
- Test the error paths
- Read a failure report
About 28 minutes
Changing code without fear
Every change to Kofi’s API might break something that worked yesterday. Automated tests make changes safe: a few seconds after each edit, a program tells you whether the behaviour you promised still holds. Python ships with unittest. A test case is a class whose methods start with test, with assertions such as assertEqual, assertIn and assertRaises, and optional setUp and tearDown methods that run before and after each test. A good suite has three kinds of tests: unit tests for pure functions, which are fast and many, tests of whole routes against a real server, which check that the pieces work together, and tests of the failure paths, which are the ones people forget.
Tests should be independent and repeatable: each one creates the state it needs, so that the order of tests does not matter, and none depends on the clock, the network or luck. The server is started on a free port in setUp, and shut down in tearDown, so no test depends on a fixed address. When a test fails, the report must tell you what was expected and what happened, which is the reason to prefer assertEqual to a bare assert. A failing test is the system working: it found a bug before a user did.
import unittest, threading, json, urllib.request, urllib.error
from http.server import BaseHTTPRequestHandler, HTTPServer
def days_between(out_day, back_day):
if back_day < out_day: raise ValueError("back_day before out_day")
return back_day - out_day
def late_fee(days, free_days=7, per_day=50):
return max(0, days - free_days) * per_day
class H(BaseHTTPRequestHandler):
def do_GET(self):
parts = self.path.strip("/").split("/")
if parts[0] == "fee" and len(parts) == 2 and parts[1].isdigit():
body, code = {"days": int(parts[1]), "fee_cents": late_fee(int(parts[1]))}, 200
else:
body, code = {"error": "not found"}, 404
b = json.dumps(body).encode()
self.send_response(code); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
def log_message(self, *a): pass
class UnitTests(unittest.TestCase):
def test_days_between(self): self.assertEqual(days_between(3, 10), 7)
def test_same_day(self): self.assertEqual(days_between(5, 5), 0)
def test_backwards_is_an_error(self):
with self.assertRaises(ValueError): days_between(10, 3)
def test_no_fee_inside_free_period(self): self.assertEqual(late_fee(7), 0)
def test_fee_after_free_period(self): self.assertEqual(late_fee(10), 150)
class ServerTests(unittest.TestCase):
def setUp(self):
self.srv = HTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=self.srv.serve_forever, daemon=True).start()
self.base = "http://127.0.0.1:%d" % self.srv.server_address[1]
def tearDown(self): self.srv.shutdown(); self.srv.server_close()
def get(self, path):
try: r = urllib.request.urlopen(self.base + path)
except urllib.error.HTTPError as e: r = e
return r.code, json.loads(r.read())
def test_fee_route(self): self.assertEqual(self.get("/fee/10"), (200, {"days": 10, "fee_cents": 150}))
def test_unknown_route(self): self.assertEqual(self.get("/nothing")[0], 404)
def test_non_numeric_days(self): self.assertEqual(self.get("/fee/abc")[0], 404)
class WrongExpectation(unittest.TestCase):
def test_fee_for_nine_days(self): self.assertEqual(late_fee(9), 150)
def run(*cases):
suite = unittest.TestSuite()
for c in cases: suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(c))
res = unittest.TestResult(); suite.run(res); return res
good = run(UnitTests, ServerTests)
bad = run(WrongExpectation)
print("passing suite: ran", good.testsRun, "tests, failures", len(good.failures), "errors", len(good.errors))
print("failing suite: ran", bad.testsRun, "test, failures", len(bad.failures))
print("failure message:", bad.failures[0][1].strip().splitlines()[-1])
print("DATA " + json.dumps({"ran": good.testsRun, "fail": len(good.failures) + len(good.errors), "badran": bad.testsRun, "badfail": len(bad.failures), "msg": bad.failures[0][1].strip().splitlines()[-1]}))
passing suite: ran 8 tests, failures 0 errors 0
failing suite: ran 1 test, failures 1
failure message: AssertionError: 100 != 150
The passing suite ran 8 tests with 0 failures: five unit tests of two pure functions and three tests of the live server. Each server test starts its own server on a free port in setUp and shuts it down in tearDown, so the tests do not depend on each other or on a fixed address. The unit tests check the boundaries, which is where bugs live: exactly 7 days is still free, and 10 days is 3 days late, 3 x 50 = 150 cents. They also check an error path, that a return date before the loan date raises ValueError, and the server tests check an unknown route and a non-numeric id, both 404, not only the happy path.
The failing suite was deliberately wrong: it expected a fee of 150 cents for a 9-day loan, but the real fee is 2 x 50 = 100. The report ends with “AssertionError: 100 != 150”, which says what was found on the left and what the test expected on the right. When a test like this fails, you have to decide which is wrong, the code or the test, and here it is the test. In a real project the failure would block a release until someone decided.
Independent check: the passing tests were saved to a file and run again by a separate process with python -m unittest, as a continuous integration service would do. It reported “Ran 8 tests” and finished with OK and exit status 0, which agrees with the in-process run. The listing of test names confirms that the five unit tests and the three server tests were all found by discovery.
Check by hand: a fee of 150 cents is for 10 days, because 10 minus the 7 free days is 3, and 3 x 50 is 150. For 9 days it is 2 x 50 = 100, so the wrong expectation of 150 fails with 100 on the left. The numbers of tests are 5 unit tests plus 3 server tests, 8 in all, plus 1 in the failing suite.
If test B needs the leftovers of test A, running one alone or in another order fails mysteriously. Create what you need in setUp and clean up in tearDown.
The middle of a range rarely breaks. Test the edges, such as 0, 1, the maximum and one above it, and test what happens on bad input and on errors, not only the happy path.
Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac, unittest), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour. Many teams use pytest, which has a lighter syntax. The ideas are the same, so check its documentation if you prefer it.
Practice
Add a test for a loan of exactly 8 days. Write a test for the validation function from lesson 5, one for each rule. Break the code on purpose and read the failure report.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does setUp do in unittest?
- Runs once at the end
- Deletes the tests
- Starts the database server
- Runs before each test
tearDown runs after each test.
Why start the server on a free port in each test?
- It is faster
- It is required by HTTP
- Tests stay independent of a fixed address
- To reduce output
Port 0 lets the system choose.
Why test error paths?
- They are shorter
- Users never see them
- Bugs and attacks live there
- Testers prefer them
Happy paths are rarely the problem.
What does assertEqual show on failure?
- Nothing
- Both values
- The file size
- The Python version
Better than a bare assert.
Why run the suite in a separate process too?
- To slow it down
- It is what a CI service does and confirms the result
- To change the code
- It is required
An independent run.
Summary
- Unit tests check functions, server tests check routes, failure tests check the error paths.
- Each test sets up its own state and cleans up.
- Readable failure reports save time.
- Run the suite in a separate process as CI does.
Questions
How many tests are enough?
Enough to give you confidence to change the code. Focus on the rules of the business, the boundaries and the failure paths. Coverage tools can show what is untested, but a high number does not prove the tests are good.
Should tests use the real database?
Unit tests can use fakes or an in-memory database, and some tests should use the same kind of database as production. Keep them fast and isolated.
What is continuous integration?
A service that runs your tests automatically on every change, so a broken change is noticed at once. Check the documentation of your code host.
