doctest

Examples in the docstring that the computer can run.

A doctest is an example in the docstring that looks like the interactive interpreter. doctest.testmod runs those examples.

Goal

Put an example on city_label and run testmod.

An example in the docstring

import doctest

def city_label(city):
    """Return a tidy city name.

    >>> city_label("  nairobi ")
    'Nairobi'
    >>> city_label("kisumu")
    'Kisumu'
    """
    return str(city or "").strip().title()

result = doctest.testmod(verbose=True)
print("failed", result.failed, "of", result.attempted)

Keep doctests small

import doctest

def line_total(units, price, tax=0.16):
    """Price a line including tax.

    >>> line_total(2, 10)
    23.2
    """
    return round(units * price * (1 + tax), 2)

result = doctest.testmod()
print("ok" if result.failed == 0 else "failed")
print(line_total(2, 10))

Doctest is documentation that cannot drift. It is not a replacement for unittest on edge cases.

Pitfall

Spacing in the expected line must match exactly, including quotes. Copy from a real print of repr(value).