From 5c477151ccf9c946e37979a265fe50731a8041b4 Mon Sep 17 00:00:00 2001 From: Dan Connolly Date: Sat, 14 Nov 2026 15:50:50 -0600 Subject: [PATCH] feat(py-doctest): Python tests are doctests on the API they test Docs go stale, and a test is often the clearest statement of what code does; a doctest is both. Setup goes in private helpers in the module (a `_MockIO` named after `main`'s parameters, `_shown()` to sort), so each example is a call and its output. A script's module docstring is its manual and runs `main(...)` with fakes; otherwise the module docstring stays brief, per docs-files-api. The rule had lived only in one workspace's project memory. It came from qtrx, where agents kept copying test_bld_balance.py: "test_bld_balance is a bad precedent. I keep running into that." Hence the trigger on being about to write a test_*.py, and lazy-tdd's step 1 now points here, since "the project's existing framework and style" is what sent agents to the neighboring file. The example script's doctests pass under several PYTHONHASHSEEDs. Generated-by: Claude Opus 5.5 --- README.md | 2 ++ lazy-tdd/SKILL.md | 4 ++- py-doctest/SKILL.md | 84 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 py-doctest/SKILL.md diff --git a/README.md b/README.md index f82ca9b..3838492 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ Code](https://code.claude.com/docs/en/skills) and failure path leaves a trace in the logs. - [lazy-tdd](lazy-tdd/SKILL.md) — works the first time? fine. Goofed? You owe a test. +- [py-doctest](py-doctest/SKILL.md) — Python tests are doctests on the + API they test, setup in private helpers, no `test_*.py`. - [refactor-mercilessly](refactor-mercilessly/SKILL.md) — at each green, move logic out of the modules that hold authority into small, fast-tested ones; keep refactors in commits of their own. diff --git a/lazy-tdd/SKILL.md b/lazy-tdd/SKILL.md index 952914e..4301cb8 100644 --- a/lazy-tdd/SKILL.md +++ b/lazy-tdd/SKILL.md @@ -31,7 +31,9 @@ From Dan Connolly's ## paying the debt (test-driven debugging) 1. Write a test that reproduces the goof, in the project's existing test - framework and style, next to related tests. + framework and style, next to related tests. For a Python script or + tool, that's a doctest in the module, whatever files sit next to it + ([py-doctest](../py-doctest/SKILL.md)). 2. Run it; **watch it fail** for the reason you expect. A test that passes before the fix proves nothing about the fix. 3. Fix the code. diff --git a/py-doctest/SKILL.md b/py-doctest/SKILL.md new file mode 100644 index 0000000..70f5e8c --- /dev/null +++ b/py-doctest/SKILL.md @@ -0,0 +1,84 @@ +--- +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`. \ No newline at end of file