Unit Tests · 18 min

Write regression tests with unittest

Capture a bug with a test and verify the correction.

Jump to the automation lab

A regression test reproduces a particular bug so you can see it fail before fixing it. After the fix, keep the test to catch future changes that bring the bug back.

The standard library’s unittest groups cases in TestCase classes. Its built-in assertions report expected and actual values. The browser example loads tests directly from a class. On your computer, run python -m unittest discover to find files with names such as test_inventory.py.

Follow the example

An order can consume all available stock.

Run the example and practice

Run the suite once and find the failing test. Correct enough_stock without changing the test cases. Aim for three passes.

Target output

Tests: 3, failures: 0
Show a hint

Read the last two lines from the starter run. Which comparison includes equality?

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
import unittest

def enough_stock(available, requested):
    return available >= requested

class StockTests(unittest.TestCase):
    def test_smaller_order(self):
        self.assertTrue(enough_stock(5, 4))

    def test_exact_order(self):
        self.assertTrue(enough_stock(4, 4))

    def test_larger_order(self):
        self.assertFalse(enough_stock(3, 4))

suite = unittest.defaultTestLoader.loadTestsFromTestCase(StockTests)
result = unittest.TestResult()
suite.run(result)
print(f"Tests: {result.testsRun}, failures: {len(result.failures)}")
for name, failure in result.failures + result.errors:
    print(name)
    print(failure.strip().splitlines()[-1])

Automation lab

Catch a missed spreadsheet deadline

A formula should include expenses dated on the last day of the month. A regression test protects that boundary.

Output

Ready

Run the example to see the output here.

Change <= closing_day to < closing_day. Verify that the tests detect the regression.

Further reading in Automate the Boring Stuff with Python by Al Sweigart