python · level 3 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Good tests check one behaviour, including the edge cases.
A good test checks one behaviour and has a name that says which. Test the normal case, then hunt for an or two: empty lists, zero, negative numbers, missing keys. Bugs love the edges.
runs before every test, so each one starts fresh. passes only if the code inside raises that error. checks many inputs in one test and reports each failure separately.
import unittest
def average(scores):
if len(scores) == 0:
raise ValueError("no scores")
return sum(scores) / len(scores)
class AverageTests(unittest.TestCase):
def test_typical_scores(self):
self.assertEqual(average([2, 4, 6]), 4)
def test_empty_list_is_an_error(self):
with self.assertRaises(ValueError):
average([])
unittest.main(argv=["x"], exit=False) The time on the Ran 2 tests line changes from run to run, so never test your tests by it.
guess first
Does each test get a fresh basket? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import unittest
class BasketTests(unittest.TestCase):
def setUp(self):
self.items = ["tea"]
print("setUp")
def test_add(self):
self.items.append("cake")
print("add:", self.items)
def test_fresh(self):
print("fresh:", self.items)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(BasketTests)
suite.run(unittest.TestResult())
your turn
Your turn. Test several totals in one go.
Add a third basket total, in pence, that should ship free. Then fill the second blank with the helper that reports each case on its own.
fix it
The error was expected, yet the test fails. Fix it!
- The report says the
ValueErrorescaped. Wasparse_agecalled inside the check? assertRaiseson a line of its own checks nothing. It needswith, and the risky call indented under it.- Write
with self.assertRaises(ValueError):and indentparse_age("-5")beneath it, then run.
nailed it
your tests catch bugs at the edges. :D
- One behaviour per test, with a name that says which.
setUpgives every test fresh data.assertRaisesandsubTestcover errors and many cases.
new words in your collection
- edge case
- setUp
- assertRaises
- subTest
This lesson isn’t saved. A free account remembers every lesson you finish.