Przejdź do treści
Biblioteka skilli
Programowanie · Przegląd i audyt

writing-tests

/writing-tests

Pisze i przegląda testy sprawdzające realne zachowanie kodu, z kontrolą, czy test rzeczywiście może wykryć błąd.

Licencja
Apache-2.0
Ostatnia zmiana repozytorium
27.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
1
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 27.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

Co robi i kiedy

Pisze i przegląda testy sprawdzające realne zachowanie kodu, z kontrolą, czy test rzeczywiście może wykryć błąd.

Oryginalny opis (EN)

How to write, change, or review tests — the load-bearing rule is test real behavior, not source text. Also covers non-vacuity (prove the test can fail), e2e tests that secretly stub the component they name, drift guards as a design smell to name rather than launder, SSOT contract tests that must move with their data, stubs that must drain stdin, checks that must prove the subject ran before judging its output, probes that must not perturb the state they read, failure-signature lists that must carve out your own guards' refusals, and the Python test idioms (repo-root discovery, `exec()`-ing a m

Jak działa

  1. Test behavior, not source text
  2. Prove the test can fail (non-vacuity)
  3. An accusation needs evidence from the subject, never an absence
  4. Never skip or weaken a test unless asked
  5. An e2e test that stubs its own subject is a unit test wearing a badge
  6. Drift guards are a smell to NAME, not launder
  7. Contracts move with their data
  8. Stubs
  9. Python test idioms
Sekcje z nagłówków SKILL.md, w oryginale · 145 linii, 1 756 słów
Podgląd SKILL.md
---
name: writing-tests
description: How to write, change, or review tests — the load-bearing rule is test real behavior, not source text. Also covers non-vacuity (prove the test can fail), e2e tests that secretly stub the component they name, drift guards as a design smell to name rather than launder, SSOT contract tests that must move with their data, stubs that must drain stdin, checks that must prove the subject ran before judging its output, probes that must not perturb the state they read, failure-signature lists that must carve out your own guards' refusals, and the Python test idioms (repo-root discovery, `exec()`-ing a module's `__main__`, `from __future__ import annotations`) that bite under pytest-xdist. Activate whenever the user asks to write, add, fix, refactor, strengthen, or review tests ("write a test", "add tests", "test this", "regression test", "cover this", "why didn't this test catch it"), or when a coding task's last step is testing the change you just made.
---

# Writing tests

## Test behavior, not source text

**Never grep the implementation as a proxy for what it does.** Asserting that a
file contains a string, a flag, or a call name passes just as happily when the
code around it is broken, and it locks the test to a spelling rather than a
behavior. Drive the real code path under stubs and assert the observable
outcome: the installed file and its mode, the exec argv and environment, the
exit code, the bytes emitted.

**Assert the operation, not a keyword.** `assert "chown -R root:root" in content`
is a source-text check wearing a behavior badge; run the thing and assert the
resulting ownership.

## Prove the test can fail (non-vacuity)

A test that passes against the unfixed code tests nothing. For every regression
test, run it against the code as it was before the fix and show it red, then
green after. When that is awkward, invert the branch the fix added and confirm a
test goes red.

**A mutation harness must assert its edit LANDED before it runs the test.** A `sed` or patch whose anchor no longer matches edits nothing, the suite passes on unmodified code, and the harness reports `SURVIVED` — which reads as a test gap and sends you auditing tests that were fine. Any refactor that moves a line (a `dataclass` conversion, a rename) silently no-ops every mutant anchored on it. Diff the file after the edit, or fail the harness when the substitution count is zero.

**A fix's own comment is the spec its test must be driven from.** Treat any
generality claim in a fix's comment ("matched on the phrase, not the exact
wording", "handles any of these retryable phrasings") as the behavior under test,
and drive cases from that claim rather than the single input that first triggered
the bug. "Comment promises more generality than the test exercises" is the
cheapest reviewer tell for a hollow regression test.

## An accusation needs evidence from the subject, never an absence

**A check that concludes from a missing artifact reads a dead environment as a violation.** An absent log, an unreadable output file, a process that exited before it wrote anything — each is evidence-shaped and proves nothing. Assert that the subject ran and produced the artifact, then judge what the artifact says. A check that skips the first step goes red loudest exactly when its own harness broke. It is the twin of the vacuous green: one missing input, reported as a false accusation instead of a false pass.

**Read the subject's state before its output, and read it without touching it.** Ask the runtime's own inventory — `docker ps -a`, a job list, a status endpoint — rather than entering the thing. Entering a stopped container starts it, so the probe destroys the ending it exists to observe.

**Exclude your own guards' words from any failure-signature list.** A defense usually refuses in the operating system's wording, so `Permission denied` from a root-owned file is the guard working. A crash-signature or error-string match that does not carve those out scores a correct refusal as a failure.

## Never skip or weaken a test unless asked

Including silently dropping an assertion while refactoring, and including
loosening one to make a finding "go away". If a test is wrong, fix what it
asserts and say so; don't quietly reduce what it proves.

## An e2e test that stubs its own subject is a unit test wearing a badge

**An e2e test that monkeypatches or re-implements the component it names can pass
while the real boundary is broken.** For each "end-to-end" test, ask: is the named
component actually executed, or stubbed? Drive the real component and assert an
observed side effect; reserve stubs for genuine external dependencies. Where a
real substitution can't run, pin the duplicated contract with a drift guard —
and name it as one (below).

**A test of a collaborator is not a test of the wiring that reaches it.** Calling a
production function directly skips everything between the entry point and that
function, so the suite stays green through two distinct failures. The call site
can vanish: the behaviour moves into the caller, no assertion goes red, and a
dead-code check then reports a function the suite still exercises. Or the
environment can differ: the direct call never sees an env key the suite's
`conftest` strips or a marker the collector applies, so an inert fix reports as
working. Both fixes are one fix — drive the live entry point (a `pytest`
subprocess over a fixture directory, the CLI, the collector) and assert its
observable effect: the skip and its reason, the emitted argv. Never exempt the
orphan instead.

## Drift guards are a smell to NAME, not launder

A test that asserts two duplicated sources agree — a hand-maintained copy (a
literal list, an example map, a mirrored constant) that must match a separate
config/file/other-language copy — means you don't have an SSOT. The honest moves
are exactly two:

1. **Kill the duplication** — make one source authoritative, or generate the
   second copy at build time so it can't drift. When consumers share a language,
   check first whether one already reads the other at runtime; if so, hoist the
   value to a single sourced file and delete the guard.
2. **Keep the guard and mark it in the open** — only when a true single source is
   genuinely infeasible (a hard cross-language/cross-process boundary, an external
   value you don't control): mark it
   `@pytest.mark.drift_guard("<why a true SSOT is infeasible>")`, naming the
   concrete boundary.

**The banned move is relabeling the guard to dodge that** — calling a
copies-agree test an "SSOT contract" / "coverage contract" / "portability check"
so it reads as principled rather than duplicated. The tell you're laundering: the
framing makes _duplication-with-a-guard_ sound like _duplication eliminated_
("pinned to the SSOT" when nothing was unified). This binds regardless of language
and regardless of whether a lint fires — "the check didn't catch it" is not a
defense; widen the check.

## Contracts move with their data

- **SSOT contract tests must change in the same commit as their data.** When a
  deny/allow list, generated file, or doc has a round-trip test ("cases exactly
  cover the live config" / "committed output == regenerated output"), editing the
  source without updating the test is a silent CI break. Search for such a
  contract test before landing any change to the data it guards.
- **Config-derived ordered lists: derive the test's expected order from the same
  config file.** Reordering entries in the config silently breaks any test with a
  hardcoded copy of the order.
- **When a fix repoints a dangling reference, add a repo-wide static scan for the
  whole class.** After fixing a "referenced X was deleted" bug (file path, image
  tag, service name, config key, workflow filename), add a scan driven on
  `git ls-files` output that asserts every referenced X of that kind still
  resolves. These bugs hide on opt-in/cost-gated paths that no functional test
  exercises; a cheap static contract catches the entire class at once.

## Stubs

- **Don't write a stub. Drive the real thing.** A stub encodes your reading of a dependency; the real dependency encodes its own — and the two drift the moment the real tool changes a flag, an exit code, or an error format. The stub then silently greens invocations the real tool would reject. Use the real binary against a fixture directory, a recorded interaction, or a container image pinned in CI. **A stub is licensed only when the real thing genuinely cannot run in the test** (a paid API, hardware, a wall-clock boundary you cannot fake) — and the stub definition site says which of those applies. "Faster to write" is not a reason.
- **A stub that ANSWERS for a dependency sits on both sides of the test, so no assertion over it can refute the reading it encodes.** A response fake supplies the input and defines the expected output, so the test agrees with your belief about the dependency however wrong that belief is. Count the suites resting on one stub: that is how many go green together on one wrong belief.
- **When a stub is licensed, it must reject what the real tool rejects and consume what it consumes.** A stub that accepts every flag pair certifies only your reading of the interface; one that exits without draining stdin under `set -o pipefail` causes the writer's `write()` to get EPIPE (rc 141) intermittently, independent of pipe-buffer size. Reproduce the argv/stdin/env behavior the caller depends on, and add `cat >/dev/null` in the body when it stands in for a pipe consumer.

## Python test idioms

- Resolve the repo root via `git rev-parse --show-toplevel`, not
  `Path(__file__).resolve().parent.parent` — depth-based parent-walking silently
  breaks when test files are moved.
- Don't add `from __future__ import annotations` unless you need runtime
  annotation introspection (`typing.get_type_hints()`, Pydantic) — `dict[str, str]`
  and `X | None` work natively in Python 3.9+.
- **Running a module's `__main__` via `exec()` executes real startup side
  effects**, including direct `os.environ[...]` mutations that `monkeypatch` never
  recorded and therefore never restores. Under `pytest-xdist` those mutations leak
  to later tests on the same worker. Snapshot and restore the environment around
  such `exec()` calls, or pre-register every mutated key with `monkeypatch` first.
- **A test that drops a package from `sys.modules` must put the original back.**
  The re-import re-executes the module and builds a SECOND set of class objects,
  so an instance held from the first generation answers False to `isinstance`
  against the second, and a class held from it answers False to `issubclass`. The failure then surfaces in an unrelated test,
  on whichever `pytest-xdist` worker ran both — restore the entry in a teardown.
- **Keep a platform-only import inside the test body, not at module top.** A
  collector or push gate that imports every module carrying a marker runs on every
  platform, so a guest-only or Linux-only top-level import refuses the whole run
  rather than skipping one test. Import it under the `skipif` it belongs to.
- **Stage a fixture you must `chmod` outside the shared temp root.** Widening
  permissions on a directory the test does not own — pytest's `basetemp`, a
  worker's tmp dir — to let another uid reach a path is a shared-state bug, not a
  filesystem quirk: every other test under that root inherits the change. Make
  your own directory and grant on that.
- Parametrize for compactness; prefer exact-equality assertions over
  `in`/truthiness, which pass for the wrong reason.

Wersje

RepozytoriumWynikLicencja
Ta strona · alexandermattturner/agent-sanitizer100Apache-2.0
andymai/brepjs100Apache-2.0
hotovo/aider-desk100Apache-2.0
jungvonmatt/agent-toolkit100MIT
it-bens/ai-tools100MIT
caarlos0/dotfiles100MIT
tosun-si/bigtesty100MIT
mcp-use/mcp-use100MIT
ahgraber/skills100CC0-1.0

Migawka bazy z 13.11.2026 · wersja paczki 112f069cf383 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 2 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 90write-tests
    Pisze i przegląda trwałe testy, które potwierdzają rzeczywiste zachowanie, przy nowym kodzie, regresji i refaktoryzacji.
  • 100principle-test-behavior
    Pisze lub przegląda testy sprawdzające zachowanie, którego wymaga wymaganie, przez publiczny interfejs kodu, i wykrywające prawdziwy błąd.
  • 100write-tests
    Pisze testy sprawdzające zachowanie produktu, bez zależności od szczegółów implementacji i wartości konfiguracji.
  • 100write-tests
    Pisze testy sprawdzające zachowanie produktu, bez zależności od szczegółów implementacji i wartości konfiguracji.
  • 100write-tests
    Pisze lub przegląda testy jednostkowe dla kodu w repozytorium, gdy trzeba dodać nowe testy, sprawdzić istniejące albo zwiększyć pokrycie.
  • 100best-practices
    Pisze i poprawia testy automatyczne, które wykryją błąd, gdy zachowanie się zmieni, w dowolnym języku i frameworku.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.