Start learning free

LESSON 138 OF 188 · BACKEND: TESTS AND RUNNING IT

Tests That Catch Bugs in Python

Practice

A test is only worth something if it fails when the code is wrong. A test can pass on the right code and still let a bug through. That happens when the right code and the broken code give the same answer to its question.

Off-by-one bugs work like that. Writing < where you meant <= changes the answer for one value only, the one right on the edge. Say a club lets in people aged 16 or more. A test with age 30 can't tell age >= 16 from age > 16. Tests right on the edge and just past it can:

def test_age_on_the_edge(self):
    self.assertEqual(can_join(16), True)

def test_age_just_below(self):
    self.assertEqual(can_join(15), False)

In this lesson, /products?max_price=N lists the products that cost N or less. The Mug costs 12, the Notebook 7, the Lamp 29 and the Pen 2. test_max_price asks for 10 and expects 2 products. The check runs your tests on the shop and on two broken copies of it. When you're done, Run prints:

Your tests on the shop:
  test_max_price ... ok
  test_price_equal_to_max ... ok
  test_price_just_over_max ... ok
  3 tests: OK
Your tests on a copy that uses < instead of <=:
  test_max_price ... ok
  test_price_equal_to_max ... FAIL
    AssertionError: 2 != 3
  test_price_just_over_max ... ok
  3 tests: 1 failed, so they caught this bug
Your tests on a copy that also lets in products that cost 1 more than max_price:
  test_max_price ... ok
  test_price_equal_to_max ... ok
  test_price_just_over_max ... FAIL
    AssertionError: 3 != 2
  3 tests: 1 failed, so they caught this bug

Your task: below test_max_price, add test_price_equal_to_max, which checks that /products?max_price=12 lists 3 products, and test_price_just_over_max, which checks that /products?max_price=11 lists 2.


Assignment
Follow the Coding Tutorial to write two tests on the edge of the Mug's price, one for each broken copy.


Hint
The Mug costs exactly 12. With max_price=12 it must be in the list, and with max_price=11 it must be out. Copy the shape of test_max_price and change the name, the number in the URL and the expected count.


STEP 1 OF 6
    Ctrl + Enter to check

    Test Catch The Bug 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