--- name: py-doctest description: >- Python doctests document the API and test it at once. Use when writing, refactoring, or fixing a Python module, script, or tool and deciding where its tests go; when about to write or add to a test_*.py, unittest, or pytest file. Not for whether a test is owed at all (that's lazy-tdd). --- # Doctests in the module Docs and tests both make code better, but docs go stale, and a test is often the clearest statement of what code does. A doctest is both: an example a reader sees next to the code, checked on every run. So **put Python tests in the module as doctests, on the API they test, with setup in small private helpers.** As in [docs-files-api](../docs-files-api/SKILL.md), the API's docstrings carry the weight, and the module docstring stays brief and points to them. A script is the exception: people open it to learn how to run it, so its module docstring is the manual, and a doctest there runs `main(...)` with fakes. That's cheap when `main(...)` takes its authority as arguments ([no-ambient-authority](../no-ambient-authority/SKILL.md)). The example is a script, so it has both. ```python """Match bank rows to orders. Usage, documented and tested together: >>> usage = 'match_orders book.db' >>> io = _MockIO() >>> main(usage.split(), io.stdout, io.connect) >>> print(io.stdout.getvalue(), end='') 1 matched; unmatched: ['A-17'] """ def unmatched(conn): """Order ids with no bank row of the same amount. >>> _shown(unmatched(_MockIO().connect('book.db'))) ['A-17'] """ return {oid for (oid,) in conn.execute( "select id from orders where amount not in (select amount from bank)")} def main(argv, stdout, connect): [_, db] = argv conn = connect(db) left = unmatched(conn) [(n,)] = conn.execute("select count(*) from orders") print(f"{n - len(left)} matched; unmatched: {_shown(left)}", file=stdout) class _MockIO: def __init__(self): from io import StringIO self.stdout = StringIO() def connect(self, _db): import sqlite3 conn = sqlite3.connect(':memory:') # in-process: not I/O conn.executescript(""" create table orders (id text, amount int); create table bank (id int, amount int); insert into orders values ('A-16', 1200), ('A-17', 350); insert into bank values (1, 1200); """) return conn def _shown(x): """Sorted, so output doesn't depend on string hashing.""" return sorted(x.items()) if isinstance(x, dict) else sorted(x) if __name__ == '__main__': def _script_io(): import sqlite3 import sys main(sys.argv, sys.stdout, sqlite3.connect) _script_io() ``` Run with `python3 -m doctest tool.py` (add `-v` to see each example). Silence means pass. - Ignore neighboring `test_*.py` files as a style cue: one may be an accident that stuck, and each copy makes the next look more like a precedent. Don't add to them or start a new one. When refactoring a module that has one, moving its tests into doctests is fair game, in a commit of its own. - When a test needs more than a helper can hide (a fixture tree on disk, a subprocess, minutes of runtime), say so and ask before reaching for a test file. ## Sources - [No more undocumented, untested code](https://www.madmode.com/2006/advogato_entry0044.html): Dan Connolly, MadMode, 2006-03-18. "If the code is worth writing, it's worth testing and documenting." - [Practical production python scripts](https://www.madmode.com/2019/python-eng.html): Dan Connolly, MadMode, 2019-07-22. Factoring logic out of `main()` with a doctest on `fizzbuzz()`, then a module doctest of usage with `StringIO` for `stdout`. - [doctest](https://docs.python.org/3/library/doctest.html): in the stdlib since Python 2.1 (2001); option flags such as `ELLIPSIS` and `NORMALIZE_WHITESPACE`.