python · level 2 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Run one test by hand. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import unittest
class TestMaths(unittest.TestCase):
def test_divide(self):
self.assertEqual(10 / 2, 5)
print("First check passed")
self.assertEqual(10 / 4, 2)
print("Second check passed")
TestMaths().test_divide()
your turn
Your turn. Test a halving function.
Fill in the method that checks two values are equal, and give it a number and its half. Then fill in the error that halving text should raise. Look for OK on the last line.
fix it
A test has found a bug. Fix the code, not the test!
- One test passes and one fails. Read the failure: which two numbers did
assertEqualcompare? - The function always divides by 2, which only works for two numbers. An average divides by how many numbers there are.
- Change / 2 to / len(numbers) on line 3, then run.
nailed it
you test like a professional. :D
- A test case is a child class of
unittest.TestCase. unittest.mainruns every method whose name starts withtest_.assertEqualandassertRaisesreport failures instead of crashing.
new words in your collection
- unit test
- unittest
- test case
- assertEqual
This lesson isn’t saved. A free account remembers every lesson you finish.