Compare commits

..
2 Commits
Author SHA1 Message Date
dckc ff600b84f6 no-ambient-authority: tests don't check logs; note DPY010 :memory: bug
Logging is an operational side effect, not output, so tests check
stdout and return values, never log records. This follows from the
style guide's choice to call logging directly rather than inject it.
Moved here from py-doctest, where it was orthogonal.

The checker flags sqlite3.connect(':memory:'), which isn't I/O. Note
it beside "treat each finding as a bug" until the checker learns the
exemption.

Generated-by: Claude Opus 5.5
2026-11-14 15:50:50 -06:00
dckc 5c477151cc 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
2026-11-14 15:50:50 -06:00
4 changed files with 96 additions and 3 deletions

No files matched your search

+2
View File
@@ -28,6 +28,8 @@ Code](https://code.claude.com/docs/en/skills) and
failure path leaves a trace in the logs. failure path leaves a trace in the logs.
- [lazy-tdd](lazy-tdd/SKILL.md) — works the first time? fine. Goofed? - [lazy-tdd](lazy-tdd/SKILL.md) — works the first time? fine. Goofed?
You owe a test. 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 - [refactor-mercilessly](refactor-mercilessly/SKILL.md) — at each
green, move logic out of the modules that hold authority into small, green, move logic out of the modules that hold authority into small,
fast-tested ones; keep refactors in commits of their own. fast-tested ones; keep refactors in commits of their own.
+3 -1
View File
@@ -31,7 +31,9 @@ From Dan Connolly's
## paying the debt (test-driven debugging) ## paying the debt (test-driven debugging)
1. Write a test that reproduces the goof, in the project's existing test 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 2. Run it; **watch it fail** for the reason you expect. A test that
passes before the fix proves nothing about the fix. passes before the fix proves nothing about the fix.
3. Fix the code. 3. Fix the code.
+7 -2
View File
@@ -1,7 +1,7 @@
--- ---
name: no-ambient-authority name: no-ambient-authority
description: >- description: >-
Use when writing or reviewing code whose functions touch I/O, clocks, random number generators, process.env, fetch, or filesystem; before writing or refactoring any Python script (DisciplinedPython style guide and checker); when someone says "ambient authority", "wash your mouth out", or "that function shouldn't reach for that"; when debating dependency injection or default-arg seams; when asked what OCap discipline is. Source: the Agoric wiki's OCap Discipline page. Use when writing or reviewing code whose functions touch I/O, clocks, random number generators, process.env, fetch, or filesystem; before writing or refactoring any Python script (DisciplinedPython style guide and checker); when someone says "ambient authority", "wash your mouth out", or "that function shouldn't reach for that"; when debating dependency injection or default-arg seams; when tempted to inject a logger or assert on log output; when asked what OCap discipline is. Source: the Agoric wiki's OCap Discipline page.
--- ---
# OCap Discipline # OCap Discipline
@@ -53,12 +53,17 @@ before writing or refactoring a Python script; don't invent conventions.
guard, authorities passed by name), standard authority names (`argv`, guard, authorities passed by name), standard authority names (`argv`,
`cwd`, `stdout`, `connect`, `run`, `urlopen`, `now`), prompt attenuation `cwd`, `stdout`, `connect`, `run`, `urlopen`, `now`), prompt attenuation
in `main`, and **status goes through `logging.info(...)` directly**: not in `main`, and **status goes through `logging.info(...)` directly**: not
`print`, not `stderr` writes, not an injected logger. `print`, not `stderr` writes, not an injected logger. Logging is an
operational side effect, not output: tests check `stdout` and return
values, never log records, since correctness doesn't depend on logging.
- [disciplined-python-attenuation.md](https://codeberg.org/dckc/awesome-ocap/src/branch/master/style-guide/disciplined-python-attenuation.md): - [disciplined-python-attenuation.md](https://codeberg.org/dckc/awesome-ocap/src/branch/master/style-guide/disciplined-python-attenuation.md):
narrowing authority function by function. narrowing authority function by function.
- Checker: run `~/projects/awesome-ocap/tools/disciplined_python_check.py path/to/script.py` - Checker: run `~/projects/awesome-ocap/tools/disciplined_python_check.py path/to/script.py`
and treat each finding as a bug. It points at matching before/after and treat each finding as a bug. It points at matching before/after
examples in `tests/fixtures/disciplined_python/{errors,fixed}/`. examples in `tests/fixtures/disciplined_python/{errors,fixed}/`.
Known checker bug: it flags `sqlite3.connect(':memory:')` as DPY010,
but an in-memory database is private to the process, not I/O; leave
that call in place.
- Calibration: Python can't enforce a capability boundary (name mangling - Calibration: Python can't enforce a capability boundary (name mangling
and introspection get around any wrapper), so for a small script, and introspection get around any wrapper), so for a small script,
attenuation that lives mostly in names is fine. An example: a read-only attenuation that lives mostly in names is fine. An example: a read-only
+84
View File
@@ -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`.