Start learning free

LESSON 135 OF 188 · BACKEND: TESTS AND RUNNING IT

Test the Errors in Python

Practice

Tests of the happy path ask for things that exist. Bugs like to hide on the other path, the error, because nobody tries it twice by hand. The shop has no product 99, so it must answer 404 Not Found with its JSON error. A 200 would tell the app that called the shop that everything is fine.

assertEqual can compare whole dictionaries: it passes only when both have the same keys with the same values. Here is a check of a whole product, on another route:

response = client.get("/products/4")
self.assertEqual(response.get_json(), {"id": 4, "name": "Pen", "price": 2, "category": "office"})

The request your new test sends, and what the shop answers:

GET /products/99  →  404  {"error": "Product not found"}

The check runs your tests on the shop and on two broken copies: one answers 200 for a missing product, the other answers 404 with Flask's HTML page instead of JSON. test_one_product passes on both. The output must be:

Your tests on the shop:
  test_missing_product ... ok
  test_one_product ... ok
  2 tests: OK
Your tests on a copy that answers 200 for a missing product:
  test_missing_product ... FAIL
    AssertionError: 200 != 404
  test_one_product ... ok
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that answers an HTML page for a missing product:
  test_missing_product ... FAIL
    AssertionError: None != {'error': 'Product not found'}
  test_one_product ... ok
  2 tests: 1 failed, so they caught this bug

Your task: below test_one_product, write test_missing_product: GET /products/99, check that the status code is 404, and check that response.get_json() equals {"error": "Product not found"}.


Assignment
Follow the Coding Tutorial to write a test for a product that doesn't exist.


Hint
You need both checks: the status catches one broken copy, the body catches the other. When the body isn't JSON, get_json() gives None.


STEP 1 OF 5
    Ctrl + Enter to check

    Test Not Found in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free