A small unittest suite

Lesson 17 of 54 · Python Foundations

Python includes unittest, a library for organizing automated tests. Save this complete example as test_fee.py:

import unittest

def delivery_fee(packages):
    return packages * 4

class FeeTests(unittest.TestCase):
    def test_three_packages(self):
        self.assertEqual(delivery_fee(3), 12)

    def test_no_packages(self):
        self.assertEqual(delivery_fee(0), 0)

if __name__ == "__main__":
    unittest.main()

In the terminal, in the directory containing the file, run py -m unittest -v test_fee on Windows or python3 -m unittest -v test_fee on macOS or Linux, using the same Python command as in the setup lesson. Both named tests should pass; the runner reports the count and OK. Timing and formatting can vary by Python version.

Some notation here comes from later topics. import unittest makes Python’s testing library available. A class groups related code; the functions written inside this class are called methods, and self refers to the test instance supplied by the runner. We do not need to define our own classes elsewhere in this course to understand what these tests check. Methods whose names start with test are discovered by the runner. assertEqual compares actual and expected values and reports a failure if they differ. The final condition runs the test runner when the file is executed directly; python -m unittest can discover tests without executing that block.

Testing a returned value differs from comparing console output. Output tests may care about exact spaces and line breaks; other tests may capture or ignore output. Extra debugging prints are therefore not universally harmless. Choose the observation that matches the intended behavior.

Chapter index