Testing and logging Python programs

3.15.2

Write tests for return values and edge cases, and record events that explain a run.

On this page

Test a normal input and a boundary

Put calculation code in functions so tests can call it directly. Test a representative case, boundary values, and invalid input where relevant. unittest assertions report what differs. The example runs a tiny test suite and prints the result.

from io import StringIO
import unittest

def line_total(qty, price):
    if qty < 0:
        raise ValueError("Negative quantity")
    return qty * price

class OrderTests(unittest.TestCase):
    def test_total(self):
        self.assertEqual(line_total(2, 3), 6)
        self.assertEqual(line_total(0, 3), 0)

    def test_invalid_quantity(self):
        with self.assertRaises(ValueError):
            line_total(-1, 3)

suite = unittest.defaultTestLoader.loadTestsFromTestCase(OrderTests)
result = unittest.TextTestRunner(stream=StringIO()).run(suite)
print(result.testsRun, result.wasSuccessful())
Example output
2 True

Record meaningful events

Use a module-level logger and configure handlers at the program entry point. Use INFO for milestones, WARNING for recoverable problems, and exception() inside an exception handler if the traceback helps. Keep secrets and private records out of logs.

import logging

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger = logging.getLogger(__name__)
logger.info("Loaded %d rows", 120)

Official references