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
This commit is contained in:
1 parent
6adb4bce33
commit
5c477151cc
3 files changed
+89
-1
No files matched your search
@@ -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.
|
||||
|
||||
+3
-1
@@ -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.
|
||||
|
||||
@@ -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`.
|
||||
Reference in new issue
Block a user