
The Tank Inspector
unittest is Python's built-in test framework. Tests are methods
whose names start with test_, inside a class that inherits from
unittest.TestCase:
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(2 + 3, 5)
def test_bad_int(self):
with self.assertRaises(ValueError):
int("seven")
Handy assertions: assertEqual(a, b), assertTrue(x),
assertIn(item, box), assertIsNone(x), and
with self.assertRaises(Error):. Their failure messages show
both values, which beats a bare assert.
Running tests
On a real machine you'd put unittest.main() at the bottom of the
file, or run python -m unittest in a terminal. Here we load the
tests and run them, writing the report into a StringIO:
import io
suite = unittest.TestLoader().loadTestsFromTestCase(TestMath)
stream = io.StringIO()
result = unittest.TextTestRunner(stream=stream, verbosity=2).run(suite)
print(stream.getvalue())
Assignment
Add at least two more test methods to TestFuelTank:
- One showing that filling past capacity stops at
capacityand returns the overflow (e.g. capacity 10, fill 12 gives level 10, returns 2). - One showing that
fill(-1)raisesValueError.
Your tests must pass on this FuelTank and catch those bugs if they appear.
Add at least two more test methods to TestFuelTank:
- One showing that filling past capacity stops at
capacityand returns the overflow (e.g. capacity 10, fill 12 gives level 10, returns 2). - One showing that
fill(-1)raisesValueError.
Your tests must pass on this FuelTank and catch those bugs if they appear.
Press Run to try your code, then Check to test it.