Testing Python code
Write tests with unittest
Group related tests and run them repeatedly.
Lesson 45 of 63
Reading: about 2 min
Lesson + practice: about 16 min
Difficulty: Intermediate
On this page5 sections
unittest is part of Python. Test methods start with test_, and assertEqual reports a useful failure when actual and expected values differ.
Worked example
import unittest
def total(values):
return sum(values)
class TotalTests(unittest.TestCase):
def test_regular_values(self):
self.assertEqual(total([20, 25]), 45)
def test_empty_values(self):
self.assertEqual(total([]), 0)
if __name__ == "__main__":
unittest.main().. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK
Why this works
The test loader finds both test_ methods. Save the file as test_total.py and run python test_total.py, or run python -m unittest to discover every test_*.py file in the folder. Each dot is one passing test. A failing assertEqual reports the expected and actual values.
Another case
import unittest
case = unittest.TestCase()
case.assertEqual(sum([1, 2, 3]), 7)Traceback (most recent call last):
File "assert_demo.py", line 3, in <module>
case.assertEqual(sum([1, 2, 3]), 7)
File ".../unittest/case.py", line ..., in assertEqual
assertion_func(first, second, msg=msg)
File ".../unittest/case.py", line ..., in _baseAssertEqual
raise self.failureException(msg)
AssertionError: 6 != 7The two case.py entries come from inside unittest itself; their path and line numbers depend on your Python installation. Read the first entry for your own file and the last line for the result.
Your terminal may show the full path to the file instead of just its name. Python 3.11 and newer also add ^ or ~ marker lines under the part of the line that failed, and recent versions colour the output. The last line, with the error type and message, is the same.
Practice
Add a test for total([-5, 10]). What should it expect?
Check the practice result
Reveal answer
It should expect 5.
Try another case
You rename test_empty_values to empty_values. How many tests run now?
Check your answer
Reveal answer
One. The default loader only collects methods whose names start with test.
Your progress
Reveal the check answer or reach the end to complete this lesson.