brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's doctest turns the examples in your docstrings into tests

Python
~/tips/tip-python-doctest-examples

def to_gb(size_bytes):

Runs the >>> examples in a module's docstrings and reports any whose output no longer matches.

Examples in a docstring go stale quietly. Python can run them for you, so a broken example shows up as a failing test.

def to_gb(size_bytes):
    """Convert bytes to whole gigabytes.

    >>> to_gb(5_000_000_000)
    5
    """
    return size_bytes // 1_000_000_000
python -m doctest -v example.py

doctest imports the module and searches the module docstring and all function, class and method docstrings for lines starting with >>>. It runs them and compares the result with the line below. Without -v, it prints nothing unless something fails.

You can also make the file test itself when run directly:

if __name__ == "__main__":
    import doctest
    doctest.testmod()

For small scripts and helper modules I find this enough testing, and the examples double as documentation that is guaranteed to be right.

Caveats from the docs. The comparison is exact text, so anything whose output varies is fragile: the order of a set, memory addresses in an object’s repr, long floats. Expected output stops at a blank line, so write <BLANKLINE> where you mean an empty line. Output to stderr is not captured. And python -m doctest may not work properly for a file inside a package that imports its own submodules.

Further reading: Python docs: doctest

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link