×

python · level 2 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

runs every test in a and reports back.

A checks one small piece of code. The unittest module keeps them organised: write a test case, a child class of unittest.TestCase, with one method per test. Each method name must start with test_.

Your test case inherits checking methods. checks two values match, and with self.assertRaises(ValueError): checks that the lines inside it raise that error.

unittest.main(argv=["x"], exit=False) runs every test_ method. A dot means passed, an F means failed, and the last line says OK when everything passes.

import unittest
def discount(price, percent):
    return price - price * percent / 100
class TestDiscount(unittest.TestCase):
    def test_half_price(self):
        self.assertEqual(discount(40, 50), 20)
    def test_no_discount(self):
        self.assertEqual(discount(40, 0), 40)
unittest.main(argv=["x"], exit=False)

argv=["x"] stops unittest reading settings meant for something else, and exit=False lets your program carry on afterwards.