Start learning free

LESSON 136 OF 188 · BACKEND: TESTS AND RUNNING IT

Test a POST in Python

Practice

Your tests so far only read the shop. A test can also add to it: client.post sends a POST request, and its json= argument is the body, a dictionary that the client sends as JSON, the way requests.post did.

def test_add_customer(self):
    client = app.test_client()
    response = client.post("/customers", json={"name": "Ana"})
    self.assertEqual(response.status_code, 201)

A 201 Created only says the app answered well. It doesn't prove that the new thing was saved. To know that, the test asks for it back with a GET, using the id from the answer, and checks that it gets the same thing.

In the shop, the Plant gets the next id, 5, and asking for product 5 must give back the very same product:

POST /products  {"name": "Plant", "price": 15, "category": "home"}
  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}
GET /products/5  →  the same product

The check runs your tests on the shop, then on two broken copies: one answers 201 but never saves the product, the other gives every new product the id 1. Your tests must pass on the shop and catch both copies:

Your tests on the shop:
  test_add_product ... ok
  test_one_product ... ok
  2 tests: OK
Your tests on a copy that answers 201 but never saves the product:
  test_add_product ... FAIL
    AssertionError: {'error': 'Product not found'} != {'category': 'home', 'id': 5, 'name': 'Plant', 'price': 15}
  test_one_product ... ok
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that gives every new product the id 1:
  test_add_product ... FAIL
    AssertionError: {'category': 'kitchen', 'id': 1, 'name': 'Mug', 'price': 12} != {'category': 'home', 'id': 1, 'name': 'Plant', 'price': 15}
  test_one_product ... ok
  2 tests: 1 failed, so they caught this bug

Your task: below test_one_product, write test_add_product. With one client, POST a Plant (price 15, category "home") to /products, check that the status is 201, keep the JSON answer in new_product, then GET /products/ followed by its id and check that this answer equals new_product.


Assignment
Follow the Coding Tutorial to write a test that POSTs a product and then GETs it back.


Hint
The id in new_product["id"] is a number: turn it into text with str(...) before you add it to "/products/". The last check compares the whole JSON of the GET with new_product.


STEP 1 OF 7
    Ctrl + Enter to check

    Test Post 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