With assert and a table of cases you can already test your code. But when a project grows, it is worth using a test framework, which runs all the tests, counts the failures and shows a clear report. Python includes unittest.
Your first test with unittest
import unittest
def is_leap(year):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
class TestLeap(unittest.TestCase):
def test_multiple_of_4(self):
self.assertTrue(is_leap(2024))
def test_normal_century(self):
self.assertFalse(is_leap(1900))
def test_century_multiple_of_400(self):
self.assertTrue(is_leap(2000))
if __name__ == "__main__":
unittest.main()
The rules are simple:
- Each group of tests is a class that inherits from
unittest.TestCase. - Each test is a method whose name starts with
test. - Inside,
assert...methods ofselfare used to check results.
When run, unittest shows a dot for each test that passes:
# ...
# ----------------------------------------------------------------------
# Ran 3 tests in 0.000s
#
# OK
And if one fails, it says which one, with the expected and the obtained value:
# FAIL: test_normal_century (__main__.TestLeap)
# AssertionError: True is not false
#
# FAILED (failures=1)
The most used checking methods
| Method | Checks that… |
|---|---|
assertEqual(a, b) | a == b |
assertNotEqual(a, b) | a != b |
assertTrue(x) / assertFalse(x) | x is true / false |
assertIn(a, b) | a is in b |
assertIsNone(x) | x is None |
assertAlmostEqual(a, b) | a and b are almost equal (for decimals) |
assertRaises(Error) | the indicated exception is raised |
class TestMath(unittest.TestCase):
def test_sum(self):
self.assertEqual(2 + 3, 5)
def test_decimals(self):
self.assertAlmostEqual(0.1 + 0.2, 0.3) # 0.1 + 0.2 == 0.3 is False
def test_division_by_zero(self):
with self.assertRaises(ZeroDivisionError):
1 / 0
assertAlmostEqual avoids the floating-point decimal problem. assertRaises checks that the code fails the way it should.
Testing many values: subTest
With subTest, a loop checks many values and, if one fails, the report says exactly which:
def square(x):
return x * x
class TestSquare(unittest.TestCase):
def test_values(self):
for n in [0, 1, 2, -3, 10]:
with self.subTest(n=n):
self.assertEqual(square(n), n ** 2)
Running the tests from the program
Normally they are launched from the terminal with python -m unittest. You can also launch them from the code and read the result, as in the exercise:
import io
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestSquare)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(result.wasSuccessful()) # True
print(len(result.failures)) # 0
Practice with Run tests with unittest.
setUp: preparing before each test
class TestList(unittest.TestCase):
def setUp(self):
self.items = [3, 1, 2] # created again before EACH test
def test_sort(self):
self.items.sort()
self.assertEqual(self.items, [1, 2, 3])
def test_length(self):
self.assertEqual(len(self.items), 3)
pytest: the most popular alternative
pytest is an external library (pip install pytest) that simplifies testing: tests are normal functions with assert, without classes:
# test_leap.py
def test_multiple_of_4():
assert is_leap(2024)
def test_normal_century():
assert not is_leap(1900)
It is run with the pytest command and it finds the test_*.py files by itself. When one fails, it shows the value of each part of the expression. It is what most real projects use. Here, in the course editor, we use unittest and assert because they come included with Python.