Start learning free

LESSON 143 OF 188 · BACKEND: TESTS AND RUNNING IT

A Health Check

Practice

A shop on a server can stop working while you sleep. A monitoring service notices it for you: every minute it asks the shop a simple question over HTTP, and alerts you when the answer is wrong or doesn't come. The question is a health check, a route made only for this. A good one really asks the parts the shop needs, like its database, and says which one is down.

Asking can fail: when the database can't answer, db.execute raises an error, and all of sqlite3's errors are kinds of sqlite3.Error. Put the risky line in a try: block, and when it raises, Python jumps to the except part that names the error instead of crashing. For example, in a route that reads a quantity:

try:
    quantity = int(data["quantity"])
except ValueError:
    return jsonify({"error": "quantity must be a number"}), 400

The cheapest question for a database is SELECT 1: it reads no table and just answers 1. While the database is down, the health check still answers 200 with status ok, because the shop itself answers; its database part tells you where to look.

The check plays the monitor, stops the database for a minute, then lets it answer again:

GET /health  →  200  {"database": "ok", "status": "ok"}
(the database stops answering)
GET /health  →  200  {"database": "down", "status": "ok"}
GET /products/count  →  500  (an HTML error page)
(the database answers again)
GET /health  →  200  {"database": "ok", "status": "ok"}

Your task: add GET /health, which asks the database SELECT 1 and answers {"status": "ok", "database": "ok"}, or "down" for the database when a sqlite3.Error is raised. Then write test_health, which checks the status code and the whole JSON body. The check runs it on the shop, where it must pass, and on a copy whose health query has a typo, so it always says down, where it must fail.


Assignment
Follow the Coding Tutorial to build the /health route and a test that checks its whole answer.


Hint
The query goes inside try:, and except sqlite3.Error: sits at the depth of try. A test that checks only the 200 lets the typo copy through: compare response.get_json() too.


STEP 1 OF 11
    Ctrl + Enter to check