Until now you checked your shop by hand: send a request, read the answer, decide if it's right. A test is code that does this for you, every time you run it, so you notice at once when a change breaks something. Python comes with the unittest module for writing tests.
Tests live in a class built on unittest.TestCase. Each method whose name starts with test_ is one test, and self.assertEqual(a, b) checks that two values are equal: if they differ, the test fails and shows both. Here is a test for a small function, not for the shop:
import unittest
def add_shipping(price):
return price + 5
class ShippingTests(unittest.TestCase):
def test_add_shipping(self):
self.assertEqual(add_shipping(10), 15)
A test doesn't start a server. app.test_client() makes a test client: its get method sends a request straight to the app and gives back the response, with the status in response.status_code. The shop is loaded for you as app, and it answers GET /products with 200 and its four products. The check runs your test on the shop, then on a broken copy that lost its GET /products route, and must print:
Your tests on the shop:
test_products_answer_200 ... ok
1 test: OK
Your tests on a copy that lost its GET /products route:
test_products_answer_200 ... FAIL
AssertionError: 405 != 200
1 test: 1 failed, so they caught this bug
Your task: write the class ProductTests with one test, test_products_answer_200, that sends GET /products with a test client and checks that the status code is 200.
Assignment
Follow the Coding Tutorial to write your first test: a class, a test method, a test client and one check.
Hint
In assertEqual, put what you got first and what you expect second. A test with no check passes on any shop, even a broken one, so don't forget the last line.
Free plan: 30 tutor messages. PRO is unlimited.
