Start learning free

LESSON 134 OF 188 · BACKEND: TESTS AND RUNNING IT

Test the Answer in Python

Practice

Your first test checks only the status. A shop that answers 200 with the wrong list still passes it. To test the list itself, read the body: response.get_json() turns the JSON text into Python values. For GET /products that is a list with one dictionary per product.

Once the body is Python data, you check it with tools you already know: len, list indexes and dictionary keys. Here is a check on another route, product 2, the Notebook:

response = client.get("/products/2")
product = response.get_json()
self.assertEqual(product["price"], 7)

The check runs your tests on the shop and on two broken copies: one leaves out the last product, the other lists the cheapest product first. Both still answer 200, so only a test of the body catches them. The output must be:

Your tests on the shop:
  test_products_answer_200 ... ok
  test_products_list ... ok
  2 tests: OK
Your tests on a copy that leaves out the last product:
  test_products_answer_200 ... ok
  test_products_list ... FAIL
    AssertionError: 3 != 4
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that lists the cheapest product first:
  test_products_answer_200 ... ok
  test_products_list ... FAIL
    AssertionError: 'Pen' != 'Mug'
  2 tests: 1 failed, so they caught this bug

Your task: below the first test, write test_products_list: GET /products, read the body with get_json() into products, and check that there are 4 products and that the first one's "name" is "Mug".


Assignment
Follow the Coding Tutorial to write a second test that checks the list in the answer.


Hint
Lists count from 0, so the first product is products[0], a dictionary. A test stops at its first failed check, so each broken copy shows one message.


STEP 1 OF 6
    Ctrl + Enter to check

    Test Json Body 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