@srobroek/pi-code-quality 0.0.0-stage → 0.15.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +191 -0
- package/LICENSE +202 -0
- package/README.md +150 -2
- package/agents/adversarial-challenger.md +29 -0
- package/extensions/quality.js +4583 -0
- package/package.json +40 -4
- package/skills/prototype-logic/LICENSE +21 -0
- package/skills/prototype-logic/NOTICE +26 -0
- package/skills/prototype-logic/SKILL.md +76 -0
- package/skills/quality-code-design/LICENSE-mattpocock-skills +21 -0
- package/skills/quality-code-design/NOTICE +63 -0
- package/skills/quality-code-design/SKILL.md +63 -0
- package/skills/quality-code-design/references/contracts.md +37 -0
- package/skills/quality-code-design/references/debugging.md +85 -0
- package/skills/quality-code-design/references/deep-modules.md +67 -0
- package/skills/quality-code-design/references/dependencies.md +81 -0
- package/skills/quality-code-design/references/encapsulation.md +148 -0
- package/skills/quality-code-design/references/feature-flags.md +189 -0
- package/skills/quality-code-design/references/go.md +110 -0
- package/skills/quality-code-design/references/lifecycle.md +66 -0
- package/skills/quality-code-design/references/middleware.md +55 -0
- package/skills/quality-code-design/references/other-paradigms.md +44 -0
- package/skills/quality-code-design/references/persistence.md +52 -0
- package/skills/quality-code-design/references/python.md +100 -0
- package/skills/quality-code-design/references/release.md +59 -0
- package/skills/quality-code-design/references/review.md +121 -0
- package/skills/quality-code-design/references/rust.md +140 -0
- package/skills/quality-code-design/references/safe-mutation.md +33 -0
- package/skills/quality-code-design/references/security.md +65 -0
- package/skills/quality-code-design/references/simplicity.md +165 -0
- package/skills/quality-code-design/references/solid.md +165 -0
- package/skills/quality-code-design/references/supporting-principles.md +78 -0
- package/skills/quality-code-design/references/telemetry.md +54 -0
- package/skills/quality-code-design/references/test-first.md +78 -0
- package/skills/quality-code-design/references/typescript.md +93 -0
- package/skills/quality-code-design/references/verification.md +53 -0
- package/skills/quality-code-policy/SKILL.md +34 -0
- package/skills/quality-profiling/SKILL.md +48 -0
- package/skills/quality-profiling/references/hygiene.md +27 -0
- package/skills/quality-profiling/references/reading-profiles.md +21 -0
- package/skills/quality-profiling/references/system.md +51 -0
- package/skills/quality-test-audit/SKILL.md +122 -0
- package/skills/quality-test-audit/references/catalog.md +108 -0
- package/skills/quality-test-audit/references/evidence.md +123 -0
- package/skills/quality-test-audit/references/report.md +75 -0
- package/skills/quality-testing/SKILL.md +62 -0
- package/skills/quality-testing/references/bad-tests.md +258 -0
- package/skills/quality-testing/references/doubles.md +49 -0
- package/skills/quality-testing/references/good-tests.md +90 -0
- package/skills/quality-testing/references/maintenance.md +96 -0
- package/skills/quality-testing/references/review-tests.md +72 -0
- package/skills/quality-testing/references/shared-contracts.md +30 -0
- package/skills/quality-testing/references/signals.md +50 -0
- package/skills/quality-testing/references/test-budget.md +81 -0
- package/skills/quality-testing/references/what-to-test.md +58 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Plan and report templates
|
|
2
|
+
|
|
3
|
+
Read in steps 4, 6 and 8 of the audit.
|
|
4
|
+
|
|
5
|
+
## Plan table
|
|
6
|
+
|
|
7
|
+
One row per candidate. Keep the evidence short and checkable: a count, a mutant id, a
|
|
8
|
+
file and line.
|
|
9
|
+
|
|
10
|
+
| # | Test | Class | Evidence | Protects | Kept by | Action | Risk |
|
|
11
|
+
| --- | --- | --- | --- | --- | --- | --- | --- |
|
|
12
|
+
| 1 | `tests/test_cart.py::test_total_two_items` | Copied cases | Same shape as `test_total_one_item`, `test_total_three_items` | Cart total | The merged parametrized test | Merge into `test_total[...]` | None |
|
|
13
|
+
| 2 | `src/billing.test.ts > legacy export is gone` | Removal check | Asserts `"legacyTotal" in mod` is false | Nothing | Not needed | Delete | None |
|
|
14
|
+
| 3 | `pkg/store/store_test.go:TestSaveCallsDB` | Coupled to the implementation | Asserts mock call count; kills 0 of 4 mutants in `Save` | Save persists the record | `TestSaveThenLoad` kills all 4 | Delete | None |
|
|
15
|
+
| 4 | `tests/flows.rs::sync_completes` | Flaky | 3 failures in 20 runs; `tokio::time::sleep` on real time | Sync completes | Itself, after the fix | Fix with paused time | Low |
|
|
16
|
+
| 5 | `test_discount[...]` (new case) | Surviving mutant | `discount.py:14` `>` to `>=` survives | A total of exactly 100 gets no discount | The new case | Extend `test_discount` with `total=100, expected=0` | None |
|
|
17
|
+
|
|
18
|
+
Group the rows by action. Put every row whose risk is not "None" first.
|
|
19
|
+
|
|
20
|
+
## Recommendations
|
|
21
|
+
|
|
22
|
+
Write the recommendations as a list grouped by action, worst first. Each item names the
|
|
23
|
+
tests or files, the evidence and the expected gain. Include them even when the user
|
|
24
|
+
applies nothing.
|
|
25
|
+
|
|
26
|
+
- **Drop:** tests to delete, with the test that keeps each one's protection.
|
|
27
|
+
- **Merge:** copied tests to fold into parametrized ones.
|
|
28
|
+
- **Rewrite:** tests to move to the public interface, a real object or a fake.
|
|
29
|
+
- **Simplify:** tests to make readable: hidden data to build in the test, large shared
|
|
30
|
+
fixtures to replace with builders, helpers that hide the action or the expected values.
|
|
31
|
+
- **Fix:** flaky tests and their causes (load-related or order-related); weak assertions to make exact.
|
|
32
|
+
- **Add:** the behaviors that no test protects, and the existing test to extend for each.
|
|
33
|
+
- **Speed up:** the slowest tests and the cost behind each.
|
|
34
|
+
- **Clean up:** unused snapshots, fixtures, builders and test data; expired quarantines.
|
|
35
|
+
- **Suite practices:** runner settings, CI lanes, coverage settings, shared setup,
|
|
36
|
+
conventions and missing tools, from the catalog's Suite practices list.
|
|
37
|
+
|
|
38
|
+
## Report
|
|
39
|
+
|
|
40
|
+
```text
|
|
41
|
+
Test audit: <scope> at <commit>
|
|
42
|
+
|
|
43
|
+
before after
|
|
44
|
+
Tests <n> <n>
|
|
45
|
+
Runtime (median) <s> <s> (wall)
|
|
46
|
+
Test time (sum) <s> <s> (summed test durations)
|
|
47
|
+
User CPU <s> <s>
|
|
48
|
+
Machine load <load> <load> (what else was running)
|
|
49
|
+
Flaky <n> <n> (<n> load-related, <n> order-related)
|
|
50
|
+
Order-dependent <n> <n> (<modes that exposed them>)
|
|
51
|
+
Line coverage <%> <%>
|
|
52
|
+
Branch coverage <%> <%>
|
|
53
|
+
Mutation score <%> <%> (<tool>, <files mutated>)
|
|
54
|
+
|
|
55
|
+
Batches
|
|
56
|
+
<commit> <action> in <area>: <n> tests (lost protection: none | <approved entries>)
|
|
57
|
+
|
|
58
|
+
Kept on purpose
|
|
59
|
+
<test>: <reason>
|
|
60
|
+
|
|
61
|
+
Recommendations not applied
|
|
62
|
+
<action>: <tests or files>, <evidence>, <expected gain>
|
|
63
|
+
|
|
64
|
+
Gaps
|
|
65
|
+
<what was not measured, and why>
|
|
66
|
+
|
|
67
|
+
Follow-ups
|
|
68
|
+
<quarantined tests with issue, owner and expiry; slow tests left; tools to add>
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
On a shared or busy machine, wall time is noise: lead with the summed test time and user
|
|
72
|
+
CPU, and name the load. Count a run flagged noisy by the summary as a finding.
|
|
73
|
+
|
|
74
|
+
State each number with the command or tool that produced it. Mark a manual comparison as
|
|
75
|
+
manual.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: quality-testing
|
|
3
|
+
description: "Load before answering how to test code, or planning, writing, reviewing or pruning tests: doubles, flakes, coverage."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Testing strategy
|
|
7
|
+
|
|
8
|
+
Language-neutral rules for what to test, how many tests to keep, and how tests change
|
|
9
|
+
with the code. For a language's runner, idioms and tool choices, also load the
|
|
10
|
+
`lang-<language>-testing` skill and its `references/practice.md` when one is listed;
|
|
11
|
+
if none is, follow the project's existing tests and test configuration. Tool choices for
|
|
12
|
+
coverage, mutation, property tests, fuzzing and flaky-order checks come from the language's
|
|
13
|
+
concerns table, found through the `toolchain-languages` skill's `references/concerns.md`.
|
|
14
|
+
The test-first
|
|
15
|
+
loop and evidence rules are in the `quality-code-design` skill's `test-first.md` and
|
|
16
|
+
`verification.md` references. To audit an existing suite on demand, with recommendations and
|
|
17
|
+
fixes, load the `quality-test-audit` skill.
|
|
18
|
+
|
|
19
|
+
## Workflow
|
|
20
|
+
|
|
21
|
+
1. Read the existing tests next to the code: runner, layout, helpers, fixtures,
|
|
22
|
+
naming. New tests follow them.
|
|
23
|
+
2. List the behaviors the change adds, changes or removes: the contract at the public
|
|
24
|
+
boundary, edge cases, error paths, and the bug being fixed.
|
|
25
|
+
3. Search the existing tests for each behavior. Decide per behavior: add a test, update
|
|
26
|
+
a test, delete a test, or add nothing because a test already protects it.
|
|
27
|
+
4. Pick the lowest level that can catch each failure.
|
|
28
|
+
5. Work test-first where the change allows. Write one failing test, and confirm that
|
|
29
|
+
it fails for the expected reason. Make it pass with the least code. Refactor, then
|
|
30
|
+
repeat.
|
|
31
|
+
6. Run the touched tests and the suite the project gates on. Report a test that did not
|
|
32
|
+
run as not run.
|
|
33
|
+
7. Before hand-off, read the test diff beside the code diff with
|
|
34
|
+
[review-tests.md](references/review-tests.md).
|
|
35
|
+
|
|
36
|
+
## Rules
|
|
37
|
+
|
|
38
|
+
- Test one behavior per test through the public interface. Work the expected value out
|
|
39
|
+
apart from the code.
|
|
40
|
+
- Make every test protect a distinct risk. Parametrize cases that differ only in data,
|
|
41
|
+
and delete a case that another test already covers.
|
|
42
|
+
- A refactor leaves behavior tests unchanged. Removed behavior takes its tests,
|
|
43
|
+
fixtures, helpers and snapshots with it, in the same change.
|
|
44
|
+
- Never write a test that only checks that code, an export or a file is gone, that
|
|
45
|
+
mirrors the implementation, that re-checks what the compiler or type checker proves,
|
|
46
|
+
or that exists only to raise coverage.
|
|
47
|
+
- Never weaken an assertion, edit an expected value to match new output, skip a test or
|
|
48
|
+
update a snapshot to get green without a requirement that says the behavior changed.
|
|
49
|
+
|
|
50
|
+
## References
|
|
51
|
+
|
|
52
|
+
| Read when | Reference |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| Writing a test, or judging whether one is worth keeping: structure, names, expected values, shared setup, test data, snapshots, test smells | [good-tests.md](references/good-tests.md) |
|
|
55
|
+
| A concrete bad test and its fix: removal checks, copied expected values, call checks, sleeps, tampering, snapshots | [bad-tests.md](references/bad-tests.md) |
|
|
56
|
+
| Choosing a test level, or deciding that something needs no test | [what-to-test.md](references/what-to-test.md) |
|
|
57
|
+
| A behavior collects many tests, tests come from an agent or a generator, or the suite grows faster than the code | [test-budget.md](references/test-budget.md) |
|
|
58
|
+
| Changing, removing or refactoring tested code; bug fixes, legacy code, flaky tests | [maintenance.md](references/maintenance.md) |
|
|
59
|
+
| Choosing a fake, stub, spy or mock, or a double for a contract | [doubles.md](references/doubles.md) |
|
|
60
|
+
| Two languages or processes share a message contract: one schema, a shared corpus, cross-language tests | [shared-contracts.md](references/shared-contracts.md) |
|
|
61
|
+
| Coverage, mutation testing, property tests, fuzzing | [signals.md](references/signals.md) |
|
|
62
|
+
| Reviewing the test changes in a diff or pull request | [review-tests.md](references/review-tests.md) |
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
# Bad tests and their fixes
|
|
2
|
+
|
|
3
|
+
Read when you write, review or prune tests and need a concrete example of a test to
|
|
4
|
+
refuse. Each entry shows a bad test, the reason it fails, and the fix. The examples use
|
|
5
|
+
TypeScript with Vitest; the patterns hold in every language. Framework pitfalls are in
|
|
6
|
+
the `lang-<language>-testing` skill's `references/practice.md`.
|
|
7
|
+
|
|
8
|
+
## Checks that code is gone
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
test("legacy export is gone", async () => {
|
|
12
|
+
const mod = await import("./billing")
|
|
13
|
+
expect("legacyTotal" in mod).toBe(false)
|
|
14
|
+
})
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The build and the deleted call sites already prove the removal. The test protects no
|
|
18
|
+
behavior and stays in the suite forever. Delete it together with `legacyTotal` and the
|
|
19
|
+
tests of `legacyTotal`. When the removal is a requirement, test the outcome:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
test("the retired v1 endpoint answers 410 Gone", async () => {
|
|
23
|
+
const res = await app.request("/v1/invoices")
|
|
24
|
+
expect(res.status).toBe(410)
|
|
25
|
+
})
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Expected value copied from the code
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
test("adds VAT", () => {
|
|
32
|
+
const net = 100
|
|
33
|
+
expect(withVat(net)).toBe(net + net * VAT_RATE)
|
|
34
|
+
})
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The test repeats the formula, so a wrong rate or a wrong formula passes. Write the value
|
|
38
|
+
that the requirement gives:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
test("adds 21% VAT to a net amount", () => {
|
|
42
|
+
expect(withVat(100)).toBe(121)
|
|
43
|
+
})
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Mocked collaborators and call checks
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
test("checkout", async () => {
|
|
50
|
+
const repo = { load: vi.fn().mockResolvedValue(cart), save: vi.fn() }
|
|
51
|
+
await checkout(repo, "c1")
|
|
52
|
+
expect(repo.load).toHaveBeenCalledWith("c1")
|
|
53
|
+
expect(repo.save).toHaveBeenCalledTimes(1)
|
|
54
|
+
})
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The test checks the call graph, which callers never see. A cache in front of `load`
|
|
58
|
+
breaks it, and a `save` of the wrong state passes it. Use a fake and check the state that
|
|
59
|
+
callers see:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
test("checkout marks the cart paid", async () => {
|
|
63
|
+
const repo = new InMemoryCarts([cart])
|
|
64
|
+
await checkout(repo, "c1")
|
|
65
|
+
expect((await repo.load("c1")).status).toBe("paid")
|
|
66
|
+
})
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Checks around the interface
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
test("create stores the user", async () => {
|
|
73
|
+
await users.create({ email: "a@example.com" })
|
|
74
|
+
const rows = await db.query("SELECT email FROM users")
|
|
75
|
+
expect(rows).toEqual([{ email: "a@example.com" }])
|
|
76
|
+
})
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The test depends on the table layout although `users.findByEmail` exists. Check through
|
|
80
|
+
the read operation:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
test("a created user can be found by email", async () => {
|
|
84
|
+
await users.create({ email: "a@example.com" })
|
|
85
|
+
expect(await users.findByEmail("a@example.com")).toMatchObject({ email: "a@example.com" })
|
|
86
|
+
})
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Copies instead of parameters
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
test("slug of an empty string", () => expect(slug("")).toBe(""))
|
|
93
|
+
test("slug of one word", () => expect(slug("Hello")).toBe("hello"))
|
|
94
|
+
test("slug of two words", () => expect(slug("Hello World")).toBe("hello-world"))
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The three tests differ only in data. Use one parametrized test with readable case names:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
test.each([
|
|
101
|
+
{ input: "", expected: "" },
|
|
102
|
+
{ input: "Hello", expected: "hello" },
|
|
103
|
+
{ input: "Hello World", expected: "hello-world" },
|
|
104
|
+
])("slug($input) is $expected", ({ input, expected }) => {
|
|
105
|
+
expect(slug(input)).toBe(expected)
|
|
106
|
+
})
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Logic in the test
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
test.each(sampleOrders)("discount for %o", (order) => {
|
|
113
|
+
if (order.total > 100) expect(discount(order)).toBe(10)
|
|
114
|
+
else expect(discount(order)).toBe(0)
|
|
115
|
+
})
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
The test re-implements the rule, and the case list hides which boundary it checks.
|
|
119
|
+
State each case and its expected value:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
test.each([
|
|
123
|
+
{ total: 100, expected: 0 },
|
|
124
|
+
{ total: 101, expected: 10 },
|
|
125
|
+
])("a $total total gets a $expected discount", ({ total, expected }) => {
|
|
126
|
+
expect(discount(anOrder({ total }))).toBe(expected)
|
|
127
|
+
})
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Sleeps
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
test("debounced save runs once", async () => {
|
|
134
|
+
editor.type("a")
|
|
135
|
+
editor.type("b")
|
|
136
|
+
await new Promise((resolve) => setTimeout(resolve, 600))
|
|
137
|
+
expect(store.saves).toBe(1)
|
|
138
|
+
})
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The test is slow, and it fails on a loaded machine. Control the clock:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
test("debounced save runs once", async () => {
|
|
145
|
+
vi.useFakeTimers() // afterEach(() => vi.useRealTimers()) restores the clock
|
|
146
|
+
editor.type("a")
|
|
147
|
+
editor.type("b")
|
|
148
|
+
await vi.advanceTimersByTimeAsync(500)
|
|
149
|
+
expect(store.saves).toBe(1)
|
|
150
|
+
})
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## No assertion
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
test("parses the config", () => {
|
|
157
|
+
parseConfig(readFixture("config.toml"))
|
|
158
|
+
})
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
The test passes for any result that does not throw. Assert the outcome:
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
test("parses the port and the host", () => {
|
|
165
|
+
expect(parseConfig('port = 8080\nhost = "localhost"')).toEqual({ port: 8080, host: "localhost" })
|
|
166
|
+
})
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Several behaviors in one test
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
test("cart", () => {
|
|
173
|
+
const cart = new Cart()
|
|
174
|
+
cart.add(apple)
|
|
175
|
+
expect(cart.total()).toBe(1.5)
|
|
176
|
+
cart.remove(apple)
|
|
177
|
+
expect(cart.isEmpty()).toBe(true)
|
|
178
|
+
expect(() => cart.remove(apple)).toThrow(NotInCart)
|
|
179
|
+
})
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
A failure does not say which behavior broke, and later checks depend on earlier steps.
|
|
183
|
+
Write one test for each behavior:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
test("adding an item adds its price to the total", () => { /* ... */ })
|
|
187
|
+
test("removing the last item empties the cart", () => { /* ... */ })
|
|
188
|
+
test("removing an item that is not in the cart throws NotInCart", () => { /* ... */ })
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Hidden test data
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
test("rejects an overdrawn account", async () => {
|
|
195
|
+
const account = await accounts.load("acct-42") // seeded by a global fixture
|
|
196
|
+
expect(() => account.withdraw(50)).toThrow(Overdrawn)
|
|
197
|
+
})
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
The outcome depends on a balance that the test does not show. Build the data in the
|
|
201
|
+
test:
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
test("rejects a withdrawal larger than the balance", () => {
|
|
205
|
+
const account = anAccount({ balance: 20 })
|
|
206
|
+
expect(() => account.withdraw(50)).toThrow(Overdrawn)
|
|
207
|
+
})
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## Checks that the type checker already makes
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
test("an invoice has a string id", () => {
|
|
214
|
+
const invoice: Invoice = makeInvoice()
|
|
215
|
+
expect(typeof invoice.id).toBe("string")
|
|
216
|
+
})
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
`tsc` already proves the type. Delete the test. Test runtime validation of untrusted
|
|
220
|
+
input instead:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
test("rejects a payload without an id", () => {
|
|
224
|
+
expect(InvoiceSchema.safeParse({ total: 10 }).success).toBe(false)
|
|
225
|
+
})
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Tampering
|
|
229
|
+
|
|
230
|
+
```diff
|
|
231
|
+
- expect(roundTotal(10.005)).toBe(10.01)
|
|
232
|
+
+ expect(roundTotal(10.005)).toBe(10)
|
|
233
|
+
- expect(parse(input).count).toBe(3)
|
|
234
|
+
+ expect(parse(input).count).toBeDefined()
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
The first change edits the expected value to match new output. The second one loosens
|
|
238
|
+
the assertion so that any count passes. Without a requirement that changed the
|
|
239
|
+
behavior, keep the assertions and fix the code. When the requirement did change, name
|
|
240
|
+
it in the pull request and keep an exact expected value.
|
|
241
|
+
|
|
242
|
+
## Snapshot of a whole object
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
test("renders the invoice", () => {
|
|
246
|
+
expect(buildInvoice(order)).toMatchSnapshot()
|
|
247
|
+
})
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
The snapshot holds hundreds of lines, timestamps and ids. Reviewers accept each update
|
|
251
|
+
without reading it. Assert the part that the behavior is about:
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
test("the invoice lists each line with its total", () => {
|
|
255
|
+
const invoice = buildInvoice(anOrder({ lines: [{ sku: "A", qty: 2, price: 3 }] }))
|
|
256
|
+
expect(invoice.lines).toEqual([{ sku: "A", total: 6 }])
|
|
257
|
+
})
|
|
258
|
+
```
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Test doubles
|
|
2
|
+
|
|
3
|
+
Read when a test needs a stand-in for a collaborator.
|
|
4
|
+
|
|
5
|
+
| Double | What it is | Use it for |
|
|
6
|
+
| --- | --- | --- |
|
|
7
|
+
| Real | The production implementation | The default, when it is fast and deterministic |
|
|
8
|
+
| Fake | A working, simplified implementation, such as an in-memory repository | A slow or external dependency behind an interface you own |
|
|
9
|
+
| Stub | Returns canned answers | Forcing a hard-to-reach condition: a timeout, a 500, a full disk |
|
|
10
|
+
| Spy | Records calls for later checks | A side effect that is the behavior, checked after the act |
|
|
11
|
+
| Mock | Set up with expected calls; fails on a mismatch | Only a call that is the behavior itself: "sends exactly one email", "a cache hit skips the fetch" |
|
|
12
|
+
|
|
13
|
+
## Rules
|
|
14
|
+
|
|
15
|
+
- Prefer the real implementation, then a fake, then a stub. Check interactions last.
|
|
16
|
+
- Never double the code under test, or the module's own internal collaborators.
|
|
17
|
+
- Double at boundaries you own. Wrap a third-party client in a thin adapter, test the
|
|
18
|
+
adapter against the real service or a protocol-level stand-in such as a local HTTP
|
|
19
|
+
mock server, and double the adapter everywhere else.
|
|
20
|
+
- Run one contract test suite against the fake and against the real implementation, so
|
|
21
|
+
the fake cannot drift. Do not build a fake that you will not keep honest.
|
|
22
|
+
- Verified fakes / contract suite: a stub, fake or double that stands in for a contract must
|
|
23
|
+
pass the same conformance suite as the real implementation. Wire it into the contract's
|
|
24
|
+
conformance runner in the consumer's tests; a double that never passed the runner does not
|
|
25
|
+
count as conforming. This is the mechanism behind the previous rule when a contract exists.
|
|
26
|
+
- The contract owns the suite: valid and invalid fixtures, expected outputs, and for
|
|
27
|
+
protocols recorded interaction transcripts, each replayed against the provider (recorded
|
|
28
|
+
responses) and the consumer (recorded requests). Implementations run it; they do not fork it.
|
|
29
|
+
- When only one implementation passes a fixture, check the fixture against the specification.
|
|
30
|
+
If the fixture is right, fix the implementation; change the contract and its fixtures only
|
|
31
|
+
when they are wrong. Never special-case an implementation.
|
|
32
|
+
- On a contract change, regenerate generated outputs in the same change. CI fails when
|
|
33
|
+
generated types, docs or fixtures are stale (drift check in the `quality-code-design`
|
|
34
|
+
skill's `contracts.md`).
|
|
35
|
+
- When two languages share the contract, see `shared-contracts.md`.
|
|
36
|
+
- Keep consumer behavior tests separate from the contract suite: the suite proves the stub
|
|
37
|
+
faithful, the consumer tests prove the consumer correct.
|
|
38
|
+
- Give each external operation its own function, so that a stub returns one shape with
|
|
39
|
+
no branching (the `quality-code-design` skill's `test-first.md`).
|
|
40
|
+
- Do not add an interface, trait or protocol only so that a test can mock it. Inject the
|
|
41
|
+
dependency at a real boundary.
|
|
42
|
+
- Assert the state or output that callers see. Interaction checks couple the test to the
|
|
43
|
+
call graph; keep them for calls that are the behavior, and check only the arguments
|
|
44
|
+
that callers rely on.
|
|
45
|
+
- Restore every patched module, spy and fake timer after the test.
|
|
46
|
+
|
|
47
|
+
Sources: [Mocks Aren't Stubs](https://martinfowler.com/articles/mocksArentStubs.html),
|
|
48
|
+
[Software Engineering at Google, ch. 13](https://abseil.io/resources/swe-book/html/ch13.html),
|
|
49
|
+
[Increase test fidelity by avoiding mocks](https://testing.googleblog.com/2024/02/increase-test-fidelity-by-avoiding-mocks.html).
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Good tests
|
|
2
|
+
|
|
3
|
+
Read when you write a test or judge whether a test is worth keeping. Language idioms are
|
|
4
|
+
in the `lang-<language>-testing` skill's `references/practice.md`.
|
|
5
|
+
|
|
6
|
+
## One behavior through the public interface
|
|
7
|
+
|
|
8
|
+
- Name the test after the behavior: the condition, the action and the outcome, such as
|
|
9
|
+
`rejects an expired token` or `test_total_is_zero_for_empty_cart`. Follow the naming
|
|
10
|
+
style of the suite.
|
|
11
|
+
- Arrange, act, assert (or given, when, then), in that order. Each test has one act.
|
|
12
|
+
- Call the interface that callers use. The unit under test includes the classes and
|
|
13
|
+
functions behind that interface. "Public" means the contract its callers rely on, not
|
|
14
|
+
every exported symbol.
|
|
15
|
+
- Check the result through that interface. When the code under test has a read
|
|
16
|
+
operation, use it instead of reading the database row, file or private field that the
|
|
17
|
+
write touched. An integration test whose subject is the store itself reads the store.
|
|
18
|
+
- One logical assertion: several checks are correct when together they state one
|
|
19
|
+
outcome, such as both balances after a transfer. Two unrelated outcomes are two tests.
|
|
20
|
+
- A test that still passes when the code under test returns a wrong value protects
|
|
21
|
+
nothing. Delete it or make it assert the outcome.
|
|
22
|
+
|
|
23
|
+
## Expected values
|
|
24
|
+
|
|
25
|
+
- Work the expected value out from the requirement, a worked example or a simpler
|
|
26
|
+
oracle.
|
|
27
|
+
- Never copy the implementation's computation into the test, and never paste the
|
|
28
|
+
current output in as the expected value. Both repeat the bug that the test must catch.
|
|
29
|
+
- Write expected values as literals in the test body, so the reader sees the claim.
|
|
30
|
+
|
|
31
|
+
## Deterministic and isolated
|
|
32
|
+
|
|
33
|
+
- A test gives the same result on every run, in any order and in parallel. Do not use
|
|
34
|
+
the real clock, unseeded randomness, the network or state that another test changes.
|
|
35
|
+
- Each test creates what it needs and leaves nothing behind: its own temp directory,
|
|
36
|
+
port and records.
|
|
37
|
+
- Isolation does not mean a mock for every collaborator. Use the real collaborator when
|
|
38
|
+
it is fast and deterministic ([doubles.md](doubles.md)).
|
|
39
|
+
|
|
40
|
+
## Readable over deduplicated
|
|
41
|
+
|
|
42
|
+
Keep tests descriptive and meaningful (DAMP) rather than as short as possible (DRY). A
|
|
43
|
+
reader sees the relevant inputs, the action and the expected outcome in the test body
|
|
44
|
+
without opening a helper. Share what does not change the outcome; keep in view what
|
|
45
|
+
does.
|
|
46
|
+
|
|
47
|
+
| Share | Keep in the test body |
|
|
48
|
+
| --- | --- |
|
|
49
|
+
| Builders and factories with valid defaults, so a call names only the fields the test is about: `anOrder({ total: 0 })` | The action under test |
|
|
50
|
+
| Resource lifecycle: temp directories, servers, database setup with cleanup | The inputs that the outcome depends on |
|
|
51
|
+
| Small fakes that pass a contract test | The expected values |
|
|
52
|
+
| Domain assertions that give a clearer failure message | The case list of a parametrized test, with readable case ids |
|
|
53
|
+
|
|
54
|
+
A test has no branches or loops that decide what to assert. Parametrize instead.
|
|
55
|
+
|
|
56
|
+
## Test data and snapshots
|
|
57
|
+
|
|
58
|
+
- Keep fixtures small and next to the tests that use them. Move a fixture to shared
|
|
59
|
+
setup only when a second test file needs it. A large shared fixture couples every test
|
|
60
|
+
to every field.
|
|
61
|
+
- Use fixed, readable values. Random values belong in property-based tests, with the
|
|
62
|
+
seed printed.
|
|
63
|
+
- Snapshot or golden files suit small, stable, public output such as rendered text or
|
|
64
|
+
generated code. Normalize timestamps, ids and ordering first. Review every snapshot
|
|
65
|
+
diff as an assertion change, and never update snapshots in CI.
|
|
66
|
+
- Do not snapshot a whole object graph or a value that a plain equality check states
|
|
67
|
+
more clearly.
|
|
68
|
+
|
|
69
|
+
## Test smells
|
|
70
|
+
|
|
71
|
+
Treat a smell as a reason to look again, not as an automatic rejection. Each smell has
|
|
72
|
+
a code example and a fix in [bad-tests.md](bad-tests.md).
|
|
73
|
+
|
|
74
|
+
| Smell | Sign | Fix |
|
|
75
|
+
| --- | --- | --- |
|
|
76
|
+
| Mystery guest | The outcome depends on a file, row or environment variable that the test does not show | Create it in the test, or name it in the builder call |
|
|
77
|
+
| General fixture | Every test builds one large shared setup and uses a small part of it | Per-test builders with defaults |
|
|
78
|
+
| Obscure test | The reader cannot tell what is checked without opening helpers | Put the action and the expected values in the test body |
|
|
79
|
+
| Assertion roulette | Many unrelated assertions; a failure does not say which behavior broke | One test per behavior, or a message on each assertion |
|
|
80
|
+
| Conditional logic | `if`, loops or exception handlers decide what the test asserts | Parametrize, with one path per case |
|
|
81
|
+
| Sleepy test | The test waits a fixed time for something to happen | Await the condition, or inject or fake the clock |
|
|
82
|
+
| Empty test | The test runs code and asserts nothing, or only that nothing was thrown when throwing is not the risk | Assert the outcome, or delete the test |
|
|
83
|
+
| Eager test | One test exercises several behaviors | One test per behavior |
|
|
84
|
+
| Duplicate | The same check twice in one test, or the same scenario in two tests | Keep one |
|
|
85
|
+
|
|
86
|
+
Sources: [Software Engineering at Google, ch. 12](https://abseil.io/resources/swe-book/html/ch12.html),
|
|
87
|
+
[The Practical Test Pyramid](https://martinfowler.com/articles/practical-test-pyramid.html),
|
|
88
|
+
[xUnit Test Patterns: test smells](http://xunitpatterns.com/Test%20Smells.html),
|
|
89
|
+
[tsDetect smell catalog](https://testsmells.org/pages/testsmellexamples.html),
|
|
90
|
+
[Canon TDD](https://newsletter.kentbeck.com/p/canon-tdd).
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# Maintaining tests with the code
|
|
2
|
+
|
|
3
|
+
Read when you change, remove or refactor tested code, fix a bug, change legacy code
|
|
4
|
+
without tests, or meet a flaky test.
|
|
5
|
+
|
|
6
|
+
## Tests change in the same change as the code
|
|
7
|
+
|
|
8
|
+
| Change | Tests |
|
|
9
|
+
| --- | --- |
|
|
10
|
+
| Refactor that keeps behavior | No assertion changes. Mechanical edits, such as a renamed import or a moved file, are correct. A changed assertion means the behavior changed, or the test was coupled to structure |
|
|
11
|
+
| New behavior | New tests for each behavior on the list |
|
|
12
|
+
| Bug fix | One regression test that fails without the fix |
|
|
13
|
+
| Changed requirement | Update the affected expected values. The commit or pull request names the requirement |
|
|
14
|
+
| Removed behavior | Delete its tests, fixtures, builders, fakes, snapshots and test data |
|
|
15
|
+
|
|
16
|
+
Put test changes in the same commit or pull request as the behavior change. A later
|
|
17
|
+
"add tests" change leaves a window in which nothing protects the behavior.
|
|
18
|
+
|
|
19
|
+
## Removing code
|
|
20
|
+
|
|
21
|
+
- Delete the tests of removed behavior. Do not comment them out, skip them or mark them
|
|
22
|
+
as expected failures.
|
|
23
|
+
- Delete the fixtures, helpers, fakes, snapshots and golden files that only the deleted
|
|
24
|
+
tests used.
|
|
25
|
+
- Do not add a test that checks that a function, module, export, flag or file is gone:
|
|
26
|
+
an import that fails, a missing attribute, an empty reflection lookup, a compile-fail
|
|
27
|
+
test. The build and the deleted call sites prove the removal.
|
|
28
|
+
- When the removal is itself a requirement, such as an endpoint that must stay off or a
|
|
29
|
+
permission that must stay denied, test the observable outcome at the boundary.
|
|
30
|
+
- When behavior moves behind a deeper interface, port the edge cases to tests of the new
|
|
31
|
+
interface, then delete the old tests. Do not keep both layers (the `quality-code-design`
|
|
32
|
+
skill's `deep-modules.md` reference).
|
|
33
|
+
|
|
34
|
+
## Bug fixes
|
|
35
|
+
|
|
36
|
+
- Reproduce the bug first: one test at the lowest level that reaches the real trigger.
|
|
37
|
+
It fails before the fix for the reported reason, and passes after it.
|
|
38
|
+
- Add a test at a second level only for a separate risk, such as the wiring between
|
|
39
|
+
callers.
|
|
40
|
+
- For hard bugs, follow the `quality-code-design` skill's `debugging.md` reference.
|
|
41
|
+
|
|
42
|
+
## Legacy code without tests
|
|
43
|
+
|
|
44
|
+
Before you change untested code, write characterization tests at the seam you are about
|
|
45
|
+
to change. They record what the code does now, not what it should do: name them so,
|
|
46
|
+
such as `characterizes rounding of negative totals`. Cover only the area of the change.
|
|
47
|
+
When the contract is known, replace them with behavior tests.
|
|
48
|
+
|
|
49
|
+
## Flaky tests
|
|
50
|
+
|
|
51
|
+
A test that sometimes fails is a bug in the test or in the code.
|
|
52
|
+
|
|
53
|
+
1. Reproduce it: run it in a loop, in random order and in parallel until it fails.
|
|
54
|
+
Shuffle file order and test order within a file separately: they catch different
|
|
55
|
+
dependences. Reproduce a timing flake under deliberate CPU load too (busy loops or
|
|
56
|
+
parallel workers): one flake passed 0 of 80 idle runs failing and failed 19 of 60 with
|
|
57
|
+
the CPU saturated. Label each flake load-related or order-related.
|
|
58
|
+
2. Find the source: state shared between tests, the real clock or sleeps, unseeded
|
|
59
|
+
randomness, unordered collections, the network, port or file collisions, races.
|
|
60
|
+
3. Fix the cause: inject a clock, seed randomness and print the seed, await the
|
|
61
|
+
condition instead of sleeping, give each test its own temp directory and port.
|
|
62
|
+
4. When it cannot be fixed now, quarantine it: a tracked issue with an owner and an
|
|
63
|
+
expiry date, and a separate lane that keeps running it without blocking merges. At
|
|
64
|
+
expiry, fix it or delete it.
|
|
65
|
+
|
|
66
|
+
### Leaked-state checklist
|
|
67
|
+
|
|
68
|
+
When a test fails only after another test or in shuffled order, look for state that
|
|
69
|
+
outlives the test:
|
|
70
|
+
|
|
71
|
+
- module-level fixture maps or caches;
|
|
72
|
+
- singletons that survive a module reset, such as a global feature-flag provider;
|
|
73
|
+
- framework global state left paused or changed, such as a query library's online manager;
|
|
74
|
+
- mock return-value overrides that persist across tests;
|
|
75
|
+
- spies that restore-all leaves in place;
|
|
76
|
+
- UI overlays left open that lock the next test's page (body classes, `aria-hidden` on the
|
|
77
|
+
next page);
|
|
78
|
+
- timers that outlive the test file after the DOM environment deletes globals;
|
|
79
|
+
- async loads still pending at teardown.
|
|
80
|
+
|
|
81
|
+
Fix the leak by resetting the state in setup or teardown. Never hide it with a longer
|
|
82
|
+
timeout.
|
|
83
|
+
|
|
84
|
+
Keep retries off by default. A retry that turns a failure green hides the flake unless
|
|
85
|
+
the runner still records it as flaky.
|
|
86
|
+
|
|
87
|
+
## Where tests live and run
|
|
88
|
+
|
|
89
|
+
- Keep tests next to the code they test, or in the layout that the language and the
|
|
90
|
+
project use.
|
|
91
|
+
- Select affected tests for quick local runs, and run the full suite in CI. Selection by
|
|
92
|
+
file name alone misses tests that depend on the changed code.
|
|
93
|
+
|
|
94
|
+
Sources: [Software Engineering at Google, ch. 11 and 12](https://abseil.io/resources/swe-book/html/ch12.html),
|
|
95
|
+
[Characterization testing](https://michaelfeathers.silvrback.com/characterization-testing),
|
|
96
|
+
[Khorikov: structural inspection](https://enterprisecraftsmanship.com/posts/structural-inspection/).
|