diff --git a/skills/engineering/tdd-bdd/SKILL.md b/skills/engineering/tdd-bdd/SKILL.md index f57b6be..d3fb92c 100644 --- a/skills/engineering/tdd-bdd/SKILL.md +++ b/skills/engineering/tdd-bdd/SKILL.md @@ -14,20 +14,21 @@ description: Drive implementation with a strict red-green-refactor loop where ev ## Language references — Python -- [tests-py.md](tests-py.md) — paired good/bad examples + characteristics; - pytest only (`@pytest.fixture`, `parametrize`, scenario as docstring). -- [mocking-py.md](mocking-py.md) — boundaries only, façade + DI over - patching. *Consult before any `patch` / `monkeypatch`.* +Pytest only — `@pytest.fixture`, `parametrize`, scenario as docstring. + +- [tests-py.md](tests-py.md) — paired good/bad examples. +- [interface-design-py.md](interface-design-py.md) — DI, pure functions, typing, deep modules. *Before step 1.* +- [mocking-py.md](mocking-py.md) — boundaries only, façade + DI over patching. *Before `patch` / `monkeypatch`.* +- [docstrings-py.md](docstrings-py.md) — Google style, types in annotations not prose. ## Language references — R Testthat ed. 3+, `box::use`, `describe`/`it`. -- [tests-r.md](tests-r.md) — paired good/bad examples + characteristics. -- [interface-design-r.md](interface-design-r.md) — DI, pure functions, - minimal surface. *Consult before step 1.* +- [tests-r.md](tests-r.md) — paired good/bad examples. +- [interface-design-r.md](interface-design-r.md) — DI, pure functions, minimal surface. *Before step 1.* - [deep-modules-r.md](deep-modules-r.md) — small interface, large impl. -- [mocking-r.md](mocking-r.md) — boundaries only. *Consult before `mockery::stub` / `local_mocked_bindings`.* +- [mocking-r.md](mocking-r.md) — boundaries only. *Before `mockery::stub` / `local_mocked_bindings`.* - [refactoring-r.md](refactoring-r.md) — what to look for in step 3. ## Process @@ -96,5 +97,4 @@ first run, refactoring while red, silently dropping an untestable scenario. ## See also - [../diagnose/SKILL.md](../diagnose/SKILL.md) — chasing an existing bug? Run `/diagnose` first; phase 5 hands back here for the regression test. -- [../grill-with-docs/SKILL.md](../grill-with-docs/SKILL.md) — run before - step 0 so scenarios use the canonical `CONTEXT.md` vocabulary. +- [../grill-with-docs/SKILL.md](../grill-with-docs/SKILL.md) — run before step 0 so scenarios use canonical `CONTEXT.md` vocabulary. diff --git a/skills/engineering/tdd-bdd/docstrings-py.md b/skills/engineering/tdd-bdd/docstrings-py.md new file mode 100644 index 0000000..91d9687 --- /dev/null +++ b/skills/engineering/tdd-bdd/docstrings-py.md @@ -0,0 +1,93 @@ +# Google-style docstrings (Python) + +Project standard: **Google-style docstrings** (pyguide §3.8), with **types +carried by annotations, never repeated in the docstring**. `ty` checks the +annotations; the docstring carries semantics only. + +## When a docstring is required + +A docstring is mandatory for any function that is **public API**, +**nontrivial in size**, or has **non-obvious logic** (pyguide §3.8.3). The +bar: "enough information to write a call to the function without reading +the function's code." Describe semantics, not implementation. + +Skip it for a one-line obvious helper. A docstring that only restates the +name ("Returns the value") is noise — omit it. + +## Format + +```python +def fetch_variants( + sample_id: str, + region: GenomicRange, + min_depth: int = 10, +) -> pl.DataFrame: + """Fetches called variants for a sample within a region. + + Variants below the depth threshold are dropped before return. The + region is half-open, following the BED convention. + + Args: + sample_id: Identifier of the sequenced sample. + region: Half-open interval to query. + min_depth: Minimum read depth a variant must meet to be kept. + + Returns: + One row per surviving variant, sorted by position. Empty if the + region contains no calls meeting the threshold. + + Raises: + SampleNotFoundError: If sample_id is not in the cohort. + """ +``` + +- **Summary line**: ≤80 chars, ends in a period, fits one physical line. + If more follows, a blank line then the body at the same indent. +- Descriptive ("Fetches…") or imperative ("Fetch…") both allowed — + pyguide only demands consistency within a file. Pick one for the repo. +- **`Args:`** — `name: description`. **No type** — the annotation has it. + Hanging-indent continuation lines by 2–4 spaces. +- **`Returns:`** — semantics the annotation can't convey. Omit entirely if + the function returns `None`. Generators use `Yields:`. +- **`Raises:`** — only exceptions relevant to the interface, not every + internal one. +- Never document `self` / `cls`. + +## Classes, modules, properties + +- **Class** docstring sits below `class …:`, opens with one line saying + what an *instance represents*. Public attributes go in an `Attributes:` + section (same format as `Args:`), excluding properties. +- **Exception class**: describe what it represents, not when raised — + `"""No more cheese is available."""`, not `"""Raised when…"""`. +- **`__init__`**: document in the class docstring *or* on `__init__`, + never both. +- **Module**: top-of-file docstring, one-line summary + overview, optional + "Typical usage example:". +- **Property**: document on the getter, attribute-style — + `"""The reference genome build."""`, not `"""Returns the build."""`. + +## Anti-patterns + +```python +# BAD +def fetch_variants(sample_id, region, min_depth=10): + """fetch_variants(sample_id, region, min_depth) + This function is a function that fetches variants. + + Args: + self: The instance. + sample_id (str): the sample id. + region (GenomicRange): the region. + min_depth: the min depth. + Returns: + Returns the value. + """ +``` + +Faults: repeats the signature; "is a function that" noise; documents +`self`; restates types the annotations already carry; descriptions merely +echo the parameter name (fails the "write a call without reading the body" +bar); "Returns the value" says nothing about semantics; no blank line +after the summary; summary spans more than one line; omits the relevant +`Raises:`. diff --git a/skills/engineering/tdd-bdd/interface-design-py.md b/skills/engineering/tdd-bdd/interface-design-py.md new file mode 100644 index 0000000..e61f04e --- /dev/null +++ b/skills/engineering/tdd-bdd/interface-design-py.md @@ -0,0 +1,91 @@ +# Interface design for testability (Python) + +Rules to apply before writing the test, not after. A deep module (small +interface, large implementation — Ousterhout) is the goal; a testable +interface is the side effect. + +## 1. Dependency injection — pass collaborators, don't construct them + +Functions that build their own dependencies force the test to patch the +constructor. Inject instead — constructor injection, no IoC framework. + +```python +# BAD — constructs its client internally; test must patch +def annotate(gene_ids: list[str]) -> list[Annotation]: + entrez = EntrezClient(httpx.Client()) # hidden dependency + ... +``` + +```python +# GOOD — collaborator is a parameter, typed as a Protocol +class GeneLookup(Protocol): + def fetch_summary(self, gene_id: str) -> dict[str, object]: ... + +def annotate(gene_ids: list[str], lookup: GeneLookup) -> list[Annotation]: + ... +``` + +The `Protocol` lives next to the *consumer* (structural typing — the +implementer never imports it). Tests pass a fake or `Mock(spec_set=...)`; +production passes the real client. A default argument is a fine seam: +`def annotate(ids, lookup: GeneLookup = EntrezClient()) -> ...`. + +## 2. Pure functions — return, don't mutate + +A function that returns its result needs one `assert`. One that writes to +disk, mutates a global, or edits its argument in place needs setup, +teardown, and a side-channel check. + +```python +# BAD — mutates the argument in place (pandas defaults to views/copies +# unpredictably; callers get surprised) +def downscale(df: pd.DataFrame) -> None: + df["total"] *= 0.9 +``` + +```python +# GOOD — returns a new frame, original untouched +def downscale(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(total=df["total"] * 0.9) +``` + +Let the caller decide where the result goes. Same rule for the filesystem: +return the bytes/rows, let a thin outer layer write them. + +## 3. Minimal interface complexity + +Each parameter multiplies test cases; each public method is surface a test +must cover. Shrink it: + +- **Wide arguments, narrow returns** (typing.python.org): accept + `Iterable[str]` / `Mapping`, return concrete `list` / `dict`. Don't + return `MutableMapping` where `dict` is meant. +- **No stringly-typed params** — `mode: Literal["r", "w", "a"]` or an + `Enum`, not `mode: str`. The checker rejects bad values before any test + runs. +- **No boolean traps** — `f(True, False)` at the call site is unreadable; + prefer keyword-only flags or `@overload` with `Literal` when the return + type depends on the flag. +- **No `Any`-leak** — a function returning `Any` disables checking for + every caller. Return a `TypedDict`, dataclass, or `dict[str, object]`. +- Fold orthogonal args into one structured input (a small frozen + dataclass) rather than six positional parameters. + +## Choosing the type of "thing" + +| Need | Use | +|---|---| +| Plain record | `@dataclass` (`frozen=True`, `slots=True`) | +| Record + validation/conversion at construction | `attrs` | +| Behavior-rich, real work in `__init__`, invariants | plain class (deep module) | +| A contract for a parameter | `Protocol` (next to the consumer) | +| Shared skeleton implementation you own | `ABC`, sparingly | + +Subclassing is for **specialization** (must satisfy Liskov), not code +sharing — prefer composition. "Duplication is far cheaper than the wrong +abstraction" (Hynek): start with dedicated classes, extract a hierarchy +only once the shared shape is proven. + +The single test: *can a new caller use this correctly without reading the +body?* If no, the interface is too complex, however clever the +implementation.