Start learning free

LESSON 137 OF 188 · BACKEND: TESTS AND RUNNING IT

Fresh Data for Every Test

Practice

Tests must not depend on each other. If all your tests use the same app, they share one shop: a Plant added by one test is still there when the next test runs. Then a test can pass or fail just because of which test ran before it.

unittest has a fix: a method named setUp. unittest calls it before each test, every time, so it's the place to build fresh data. What setUp stores on self, the test that runs next can use.

class CartTests(unittest.TestCase):
    def setUp(self):
        self.cart = []

    def test_add(self):
        self.cart.append("Mug")
        self.assertEqual(len(self.cart), 1)

    def test_empty(self):
        self.assertEqual(len(self.cart), 0)

test_add runs first and puts a Mug in the cart, yet test_empty still finds an empty cart: setUp made a new one before it. In the shop, create_app() does that job: each call builds a new app with its own four products. With a new shop in every test, your two tests get these answers in any order:

test_add_product:     POST /products  (a Plant)  →  {"id": 5, …}
test_count_products:  GET /products  →  a list of 4 products

The check runs your tests, then again in the opposite order, then once more with every test on the same shop, to show what fresh data saves you from. It must print:

Your tests on the shop:
  test_add_product ... ok
  test_count_products ... ok
  2 tests: OK
Your tests again, in the opposite order:
  test_count_products ... ok
  test_add_product ... ok
  2 tests: OK
Your tests if every test got the same shop:
  test_add_product ... ok
  test_count_products ... FAIL
    AssertionError: 5 != 4
  2 tests: 1 failed

Your task: at the top of ProductTests, write setUp: build a new app with create_app(), keep it in self.app, and keep its test client in self.client. Then, below test_add_product, write test_count_products: GET /products with self.client and check that the list has 4 products.


Assignment
Follow the Coding Tutorial to give every test a fresh shop in setUp, then test that the shop still has 4 products.


Hint
The name is setUp, with a capital U, and like the tests it takes self. Store the app and the client on self so the tests can reach them. len(...) counts the items of a list.


STEP 1 OF 6
    Ctrl + Enter to check