sisi 0.1.0: a shared rulebook and verification tool for AI coding agents
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.9) (push) Canceled after 0s
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.9) (push) Canceled after 0s
Contracts with a ladder of checks, an end-of-turn gate, retrospectives and shared lessons, time-to-delivery measurement, a library of 140 verification techniques and 20 recipes, personal data kept outside the clone, and releases with rollback. Standard library only. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
2fc1fe9c2d
223 files changed
+22163
No files matched your search
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: afl-plus-plus
|
||||
title: Fuzzing C, C++ and Rust with AFL++
|
||||
answers: Can any input make this native program or library crash, hang or trip a sanitizer?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: c, cpp, rust
|
||||
kinds: parsing, general
|
||||
cost: medium
|
||||
detect: afl-fuzz -h
|
||||
ran_here: no
|
||||
verified: docs
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- The target is C or C++ (or Rust via `cargo-afl`) that reads a file or stdin, and you want a mature fuzzer with many mutation strategies.
|
||||
- A program has a command-line entry point and cannot easily be turned into a libFuzzer function.
|
||||
- You want to run several fuzzer processes for long periods on a server.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- A libFuzzer-style function is easy to write: `cargo-fuzz`, `go-fuzz` or `jazzer` are less work.
|
||||
- You only need a few minutes of sanity fuzzing of a Rust crate: `cargo-fuzz` is simpler.
|
||||
|
||||
## Set up
|
||||
|
||||
C and C++: build the target with an AFL compiler (`afl-clang-fast` or `afl-cc`):
|
||||
|
||||
CC=afl-clang-fast CXX=afl-clang-fast++ ./configure --disable-shared && make
|
||||
|
||||
Rust: `cargo install cargo-afl`, add `afl = "*"` to `Cargo.toml`, then `cargo afl build`.
|
||||
Put a few small valid inputs in `in/`.
|
||||
|
||||
## Minimal example (Rust, `src/main.rs`)
|
||||
|
||||
#[macro_use]
|
||||
extern crate afl;
|
||||
|
||||
fn main() {
|
||||
fuzz!(|data: &[u8]| {
|
||||
if let Ok(s) = std::str::from_utf8(data) {
|
||||
let _ = mycrate::parse_pair(s);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
C and C++: `afl-fuzz -i in -o out -- ./target @@` (`@@` is replaced by the input
|
||||
file name; leave it out to feed stdin).
|
||||
|
||||
## Run
|
||||
|
||||
cargo afl build
|
||||
cargo afl fuzz -i in -o out target/debug/<binary>
|
||||
|
||||
AFL runs until stopped; for a time budget use the time-limit option that
|
||||
`afl-fuzz -h` lists (I believe `-V <seconds>`; not confirmed against the docs here).
|
||||
Passing looks like: the run ends with "saved crashes: 0" in the status screen. Failure
|
||||
leaves crashing inputs in `out/default/crashes/`. Reproduce one with
|
||||
`cargo afl run <binary> < out/default/crashes/<file>`.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "afl-parse-pair", "claim": "AFL++ finds no crash in parse_pair in 60 seconds", "kind": "parsing", "rung": 2, "cmd": "sh scripts/afl-budget.sh 60 && test -z \"$(ls out/default/crashes 2>/dev/null | grep -v README)\"", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
|
||||
|
||||
`scripts/afl-budget.sh` is yours: it must run `cargo afl fuzz` with the time limit
|
||||
and exit. AFL itself exits non-zero or hangs in ways that need that wrapper.
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- A run with no crashes means none found in the time given; a short run in a CI machine without core-pattern or CPU-governor tuning may fail to start (AFL prints the fix).
|
||||
- It finds crashes, not wrong outputs. Add assertions in the harness.
|
||||
- Not run here (AFL++ and `cargo-afl` are not installed). Compile and run commands for C and Rust are from the AFL++ and Rust fuzz book pages; the time-limit flag is unconfirmed. Check the check: plant a crash behind a recognisable input.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
id: algebraic-laws
|
||||
title: Domain laws as properties (conservation, idempotence, commutativity, monotonicity)
|
||||
answers: Do the rules my domain guarantees, such as debits equal credits, hold after any generated sequence of operations?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: money, state-machine, general
|
||||
cost: low
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- The domain has laws that must always hold: debits equal credits, totals are conserved by transfers, applying an operation twice equals once, order of independent operations does not matter, a counter never goes down.
|
||||
- Money, inventory, permissions, scheduling, any ledger-like state.
|
||||
- You can name each law in one sentence. Each becomes one test, named for the law.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The law is only true for a subset of states you cannot generate; generate valid states first.
|
||||
- You want to compare with another implementation: `differential-reference`.
|
||||
|
||||
## Set up
|
||||
|
||||
Write a generator for operations (or for valid starting states), apply them with
|
||||
the real code, then check the law on the result. Keep money in integer cents.
|
||||
|
||||
## Minimal example (Python; a transfer ledger)
|
||||
|
||||
from hypothesis import given, strategies as st
|
||||
|
||||
def apply(balances, a, b, cents): # under test
|
||||
out = dict(balances)
|
||||
if cents <= 0 or out.get(a, 0) < cents:
|
||||
return out # refused: nothing changes
|
||||
out[a] -= cents
|
||||
out[b] = out.get(b, 0) + cents
|
||||
return out
|
||||
|
||||
names = st.sampled_from("abc")
|
||||
state = st.dictionaries(names, st.integers(0, 10**6))
|
||||
transfers = st.lists(st.tuples(names, names, st.integers(-5, 10**6)), max_size=30)
|
||||
|
||||
@given(state, transfers)
|
||||
def test_conservation(s, ts):
|
||||
total = sum(s.values())
|
||||
for a, b, c in ts:
|
||||
s = apply(s, a, b, c)
|
||||
assert sum(s.values()) == total # nothing created or destroyed
|
||||
assert all(v >= 0 for v in s.values()) # nobody goes negative
|
||||
|
||||
@given(state, names, names, st.integers(1, 10**6))
|
||||
def test_refused_transfer_is_idempotent_noop(s, a, b, c):
|
||||
once = apply(s, a, b, c)
|
||||
assert apply(once, a, b, 10**9) == once # an impossible transfer changes nothing
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_laws.py
|
||||
|
||||
Passing looks like: `2 passed`, exit 0. Failure shows the shortest violating sequence.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "law-conservation", "claim": "transfers conserve the total and never overdraw", "kind": "money", "rung": 2, "cmd": "python3 -m pytest -q test_laws.py", "expect": {"exit": 0, "stdout_contains": "2 passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Laws that hold are necessary, not sufficient: an implementation that does nothing conserves the total. Pair with `stateful-model-test` for what should have happened.
|
||||
- The check holds only for generated states. If the generator never makes an overdrawn account or `a == b`, those cases are untested.
|
||||
- Check the check: break the code (skip the debit, or credit twice) and see the right law fail.
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: atheris
|
||||
title: Coverage-guided fuzzing of Python with Atheris
|
||||
answers: Can any input make this Python code raise an exception it should not, hang, or crash the interpreter?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: python
|
||||
kinds: parsing, general
|
||||
cost: medium
|
||||
detect: python3 -c "import atheris"
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- Python code parses or transforms untrusted input and should raise only its documented exceptions.
|
||||
- You want libFuzzer's coverage guidance, corpus handling and time budget for Python code, including C extensions.
|
||||
- Property tests with `hypothesis` have not found anything and you want a search guided by coverage.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- You need shrinking to a readable counterexample and structured values: `hypothesis`.
|
||||
- The code is pure and fast to reason about; a property test is less work.
|
||||
|
||||
## Set up
|
||||
|
||||
python3 -m venv .venv && .venv/bin/pip install atheris
|
||||
|
||||
Atheris builds against clang; wheels exist for common platforms. Use
|
||||
`@atheris.instrument_func` on your functions or `atheris.instrument_imports()`
|
||||
around the import of the code under test. Without instrumentation there is no
|
||||
coverage feedback and the fuzzer finds almost nothing.
|
||||
|
||||
## Minimal example (`fuzz_parse.py`)
|
||||
|
||||
import sys
|
||||
import atheris
|
||||
|
||||
@atheris.instrument_func
|
||||
def parse_pair(s: str):
|
||||
a, _, b = s.partition(",")
|
||||
x, y = int(a), int(b) # ValueError is the documented error
|
||||
if s.startswith("42,") and y == 7:
|
||||
raise RuntimeError("seeded bug") # anything else is a finding
|
||||
return x, y
|
||||
|
||||
def test_one_input(data: bytes):
|
||||
fdp = atheris.FuzzedDataProvider(data)
|
||||
s = fdp.ConsumeUnicodeNoSurrogates(16)
|
||||
try:
|
||||
parse_pair(s)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
atheris.Setup(sys.argv, test_one_input)
|
||||
atheris.Fuzz()
|
||||
|
||||
## Run
|
||||
|
||||
mkdir -p corpus && .venv/bin/python fuzz_parse.py corpus -max_total_time=60 -timeout=10
|
||||
|
||||
Passing looks like: `Done N runs in 60 second(s)`, exit 0.
|
||||
Failure prints the traceback, writes `crash-<hash>` in the current directory
|
||||
(`artifact_prefix='./'`) and exits 77. Replay with `.venv/bin/python fuzz_parse.py crash-<hash>`;
|
||||
commit the file as a regression case.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "fuzz-parse-pair-py", "claim": "parse_pair raises only ValueError on 60 seconds of fuzzed input", "kind": "parsing", "rung": 2, "cmd": ".venv/bin/python fuzz_parse.py corpus -max_total_time=60 -timeout=10", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Only what was found in the time given; the bug in the example took under 60 seconds with instrumentation and was never found in 30 seconds without it.
|
||||
- Uninstrumented code and code in another process are invisible to the fuzzer.
|
||||
- Check the check: confirm a planted bug is found, and that the `except` clause only catches the documented error.
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: cargo-fuzz
|
||||
title: Coverage-guided fuzzing of Rust with cargo-fuzz (libFuzzer)
|
||||
answers: Can any input I did not think of make this Rust code panic, overflow, hang or break an assertion?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: rust
|
||||
kinds: parsing, general, state-machine
|
||||
cost: medium
|
||||
detect: cargo fuzz --version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- Rust code takes untrusted or complex input: parsers, decoders, importers, journal and file readers, request handlers.
|
||||
- You want a run with a time budget and a saved reproducer for any crash.
|
||||
- You have a few valid example inputs to seed the search.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The input must satisfy a grammar that raw bytes rarely meet; use `structure-aware-fuzzing`.
|
||||
- You need a law checked on structured values with shrinking: `proptest`.
|
||||
- You cannot run nightly Rust. cargo-fuzz needs a nightly toolchain.
|
||||
|
||||
## Set up
|
||||
|
||||
cargo install cargo-fuzz # once; needs rustup nightly
|
||||
cargo fuzz init # creates fuzz/ with fuzz_target_1
|
||||
mkdir -p fuzz/corpus/fuzz_target_1 fuzz/seeds/fuzz_target_1
|
||||
|
||||
Put small valid inputs in `fuzz/seeds/<target>/` and commit them. The `corpus/`
|
||||
directory grows during runs and is normally git-ignored. Crash files appear in
|
||||
`fuzz/artifacts/<target>/`.
|
||||
|
||||
## Minimal example (`fuzz/fuzz_targets/fuzz_target_1.rs`)
|
||||
|
||||
#![no_main]
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
if let Ok(s) = std::str::from_utf8(data) {
|
||||
let _ = mycrate::parse_pair(s); // must never panic, only return None/Err
|
||||
}
|
||||
});
|
||||
|
||||
## Run
|
||||
|
||||
cd <crate> && RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 \
|
||||
fuzz/corpus/fuzz_target_1 fuzz/seeds/fuzz_target_1 -- -max_total_time=60 -timeout=10
|
||||
|
||||
The first directory after the target is where new inputs are written; later ones
|
||||
are read-only seeds. The directory must already exist (the run refuses with
|
||||
"The required directory ... does not exist" otherwise).
|
||||
Passing looks like: `Done N runs in 60 second(s)`, exit 0.
|
||||
Failure shows the panic message, `Test unit written to fuzz/artifacts/fuzz_target_1/crash-<hash>`,
|
||||
and exit 1. Replay one crash with `cargo fuzz run fuzz_target_1 fuzz/artifacts/fuzz_target_1/crash-<hash>`;
|
||||
after the fix, copy it into `fuzz/seeds/fuzz_target_1/` as a regression case.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "fuzz-parse-pair", "claim": "parse_pair neither panics nor hangs on 60 seconds of fuzzed input", "kind": "parsing", "rung": 2, "cmd": "cd fuzz-host && RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 fuzz/seeds/fuzz_target_1 -- -max_total_time=60 -timeout=10", "expect": {"exit": 0, "stdout_contains": "Done"}, "tier": "deep", "timeout_s": 600}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- A clean run only means nothing was found in that time. The bug seeded in the example needs a specific prefix; a 30-second run on a numeric comparison deeper in the code did not find an equivalent one. Longer runs and good seeds matter.
|
||||
- It finds crashes, not wrong answers. Add assertions inside the target (round trip, agreement with a reference) to catch those.
|
||||
- Check the check: plant a panic behind a recognisable input and see the fuzzer find it, then remove it. Also check the target actually reaches the code (`cargo fuzz coverage`).
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: derived-view-agreement
|
||||
title: Every displayed figure recomputed from the core and compared
|
||||
answers: Does every number a screen, report or export shows equal what the core computes from the same data?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: ui, money
|
||||
cost: medium
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- A UI, report, CSV export or API response shows figures that a core library also computes (balances, totals, percentages).
|
||||
- Formatting, rounding or caching in the display layer could change a value the core got right.
|
||||
- Two surfaces show the same fact (a dashboard and an exported statement).
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The view has no figures, only layout: use `ui-screenshot-compare`.
|
||||
- The view is the only place the figure is computed; compare against an independent reference (`differential-reference`).
|
||||
|
||||
## Set up
|
||||
|
||||
Give the display layer a seam that returns what it will show as data (not pixels):
|
||||
a view model, a rendered text, a parsed export. Generate random data, load it
|
||||
through the core, and for each displayed figure recompute from the core
|
||||
and compare after normalising only the formatting.
|
||||
|
||||
## Minimal example (Python)
|
||||
|
||||
from decimal import Decimal
|
||||
from hypothesis import given, strategies as st
|
||||
|
||||
def core_total(entries): # the core: integer cents
|
||||
return sum(entries)
|
||||
|
||||
def render_report(entries): # the display layer under test
|
||||
lines = [f"{c / 100:.2f}" for c in entries] # a float in a money path
|
||||
return {"lines": lines, "total": f"{core_total(entries) / 100:.2f}"}
|
||||
|
||||
def parse(text): return int(Decimal(text) * 100)
|
||||
|
||||
@given(st.lists(st.integers(-10**9, 10**9), max_size=30))
|
||||
def test_every_figure_matches_core(entries):
|
||||
view = render_report(entries)
|
||||
assert [parse(x) for x in view["lines"]] == entries # each line
|
||||
assert parse(view["total"]) == core_total(entries) # the total
|
||||
assert sum(parse(x) for x in view["lines"]) == parse(view["total"]) # the page adds up
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_view.py
|
||||
|
||||
Passing looks like: `1 passed`, exit 0 (the float formatting is right for these sizes).
|
||||
With amounts above about 2**53 cents the float version fails and Hypothesis shrinks
|
||||
to the smallest such figure. Widen the range to see it; a display path that must
|
||||
handle big amounts should use `Decimal`, not `float`.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "view-matches-core", "claim": "every figure the report displays equals the core's value, and the report adds up", "kind": "money", "rung": 2, "cmd": "python3 -m pytest -q test_view.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- It checks the figures you list. Enumerate every displayed number (tests that walk the whole view model help) and add new ones as screens are added.
|
||||
- Equal to the core only shows the view is faithful; the core can still be wrong (see `algebraic-laws`, `differential-reference`).
|
||||
- A reference project also scans display source for rounding calls outside the one shared function; a source scan is a cheap extra guard.
|
||||
- Check the check: change the rounding in the view by one cent and see it fail.
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
id: differential-executable-spec
|
||||
title: Differential testing against an executable formal model
|
||||
answers: Does the implementation agree, on random cases, with the formal model that was proved, run as a program?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: state-machine, money, parsing
|
||||
cost: high
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- The design has a formal model that can be run: a Lean checker binary, a TLA+ trace checker, an Alloy or Dafny program.
|
||||
- You want the implementation compared to the model itself, not to a hand transcription of it.
|
||||
- A mismatch must name which side is wrong, so each case carries both answers.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The model cannot be executed. Use `model-test-from-spec` with a hand transcription.
|
||||
- A checker run is slow per case: batch many cases into one call, or the test will be too slow to run in CI.
|
||||
|
||||
## Set up
|
||||
|
||||
Build the checker once and pin its revision. Write the glue: run each random
|
||||
case through the implementation, write the case and the implementation's answer
|
||||
as a file in the checker's input format, run the checker once for the whole
|
||||
batch, and fail if it reports any mismatch. Fail loudly if the checker is missing
|
||||
(never skip silently): one reference project makes the test fail when `lake` is absent.
|
||||
|
||||
## Minimal example (Python; `checker.py` stands in for the formal model's binary)
|
||||
|
||||
# test_vs_checker.py
|
||||
import json, subprocess, sys
|
||||
from hypothesis import given, settings, strategies as st
|
||||
|
||||
def impl_total(prices): # implementation under test
|
||||
return sum(prices)
|
||||
|
||||
CASES = st.lists(st.integers(0, 10**6), max_size=20)
|
||||
|
||||
@settings(max_examples=50, deadline=None)
|
||||
@given(st.lists(CASES, min_size=1, max_size=20))
|
||||
def test_against_checker(batch):
|
||||
cases = [{"input": c, "got": impl_total(c)} for c in batch]
|
||||
out = subprocess.run([sys.executable, "checker.py"], input=json.dumps(cases),
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
mismatches = json.loads(out)
|
||||
assert mismatches == [], mismatches
|
||||
|
||||
# checker.py (the "executable spec": here a trivial model)
|
||||
import json, sys
|
||||
cases = json.load(sys.stdin)
|
||||
print(json.dumps([c for c in cases if sum(c["input"]) != c["got"]]))
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_vs_checker.py
|
||||
|
||||
Passing looks like: `1 passed`, exit 0.
|
||||
Failure shows the batch and the mismatch list from the checker, exit 1.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "diff-formal-model", "claim": "the implementation agrees with the formal model's checker on generated cases", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_vs_checker.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 900}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Only the cases generated, and only the commands the checker's input format can express. List what it cannot say.
|
||||
- The checker may skip outcomes it does not know (one reference project's checker ignores refusal words it does not list); count skipped cases and fail if too many.
|
||||
- The model may not match the intended behaviour. This shows code and model agree, not that either is right.
|
||||
- Check the check: change the implementation by one rule and see the checker report a mismatch.
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: differential-old-vs-new
|
||||
title: Differential testing of new code against the previous version
|
||||
answers: Did my refactor or rewrite keep the behaviour of the old code on inputs I did not think of?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: general, parsing, money, migration
|
||||
cost: medium
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- You are refactoring, optimising or rewriting code whose behaviour must not change.
|
||||
- The old version is trusted by its users, even if not proved.
|
||||
- You can keep both versions side by side for the length of the change (old copy in the test tree, a tagged release, or a git worktree of the old commit).
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The behaviour is meant to change. Then compare only the parts that must not change, or use `metamorphic`.
|
||||
- The old version has known bugs you do not want to keep; agreement would preserve them. Record the known differences explicitly.
|
||||
|
||||
## Set up
|
||||
|
||||
Freeze the old implementation as a module the test can import (copy it as
|
||||
`old_impl.py`, or build the old commit in a worktree and call it as a program).
|
||||
Delete the copy when the change is merged and its job is done.
|
||||
|
||||
## Minimal example (Python; a faster word counter against the original)
|
||||
|
||||
from collections import Counter
|
||||
from hypothesis import given, strategies as st
|
||||
|
||||
def old_count(text): # frozen original
|
||||
counts = {}
|
||||
for w in text.split():
|
||||
counts[w] = counts.get(w, 0) + 1
|
||||
return counts
|
||||
|
||||
def new_count(text): # rewrite under test
|
||||
return dict(Counter(text.split()))
|
||||
|
||||
@given(st.text(alphabet=" \n\tab é", max_size=200))
|
||||
def test_new_matches_old(text):
|
||||
assert new_count(text) == old_count(text)
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_old_vs_new.py
|
||||
|
||||
Passing looks like: `1 passed`, exit 0.
|
||||
Failure prints the shrunk input and both outputs, exit 1.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "refactor-same-behaviour", "claim": "new_count returns what the old implementation returned on generated text", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_old_vs_new.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- It compares outputs on generated inputs only. Side effects (files, logs, timing) are not compared unless you read them back.
|
||||
- The alphabet decides what is tried: include the awkward characters, empty input and very large ones. In the example, a non-breaking space is the kind of case that separates `split()` rewrites.
|
||||
- Errors count too: compare raised exceptions and messages, not only returned values.
|
||||
- Check the check: change the new code by one character and confirm the test fails.
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: differential-reference
|
||||
title: Differential testing against an independent reference implementation
|
||||
answers: Does my implementation give the same answer as an independent, trusted one on random inputs?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: general, parsing, money
|
||||
cost: medium
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- Another library, tool or program already computes the same thing (a standard library, a database, a reference tool run in a container).
|
||||
- The result is hard to state as a law but easy to compare.
|
||||
- You wrote a faster or custom version of something with a trusted slow version.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The reference shares code or an algorithm with your implementation; agreement then proves little. Prefer one written independently.
|
||||
- Both may legitimately differ (rounding rules, ordering of ties). Decide first what counts as equal.
|
||||
- A prior version of your own code is the reference: use `differential-old-vs-new`.
|
||||
|
||||
## Set up
|
||||
|
||||
Choose the reference and pin its version. A program in a container is fine:
|
||||
call it through a function that takes an input and returns a normalised answer.
|
||||
Generate inputs with `hypothesis`, `proptest` or `fast-check`.
|
||||
|
||||
## Minimal example (Python: a custom decimal rounder against `decimal`)
|
||||
|
||||
from decimal import Decimal, ROUND_HALF_EVEN
|
||||
from hypothesis import given, strategies as st
|
||||
|
||||
def my_round_cents(units: int, scale: int) -> int:
|
||||
"""units / 10**scale, rounded half to even, in cents (integers only)."""
|
||||
q, r = divmod(units * 100, 10**scale)
|
||||
twice = 2 * r
|
||||
if twice > 10**scale or (twice == 10**scale and q % 2 == 1):
|
||||
q += 1
|
||||
return q
|
||||
|
||||
def reference(units: int, scale: int) -> int:
|
||||
d = Decimal(units).scaleb(-scale).quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN)
|
||||
return int(d.scaleb(2))
|
||||
|
||||
@given(st.integers(-10**12, 10**12), st.integers(0, 9))
|
||||
def test_matches_reference(units, scale):
|
||||
assert my_round_cents(units, scale) == reference(units, scale)
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_diff.py
|
||||
|
||||
Passing looks like: `1 passed`, exit 0.
|
||||
Failure prints the shrunk input and both answers, exit 1.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "diff-rounding", "claim": "my rounding equals Python's decimal on generated amounts", "kind": "money", "rung": 2, "cmd": "python3 -m pytest -q test_diff.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- It shows agreement, not correctness: if the reference has the same bug or misreads the spec, both pass.
|
||||
- Generated inputs that the reference rejects or that both treat identically make the pass thin; check the distribution (include edge scales, negatives, ties).
|
||||
- Pin the reference version and record it; a drifting reference changes the answer.
|
||||
- Check the check: introduce an off-by-one in the tie rule and see it fail.
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: fast-check
|
||||
title: Property testing in TypeScript and JavaScript with fast-check
|
||||
answers: Does this JavaScript or TypeScript function hold its law for generated inputs, and what is the smallest counterexample?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: typescript, javascript
|
||||
kinds: general, parsing, money, state-machine
|
||||
cost: low
|
||||
detect: node --version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- A function or module has a law (round trip, idempotence, order, agreement with a simple version) and you use Node, Jest, Vitest or the built-in `node:test`.
|
||||
- You want shrinking and a replayable seed.
|
||||
- You want to test a sequence of operations against a model (see `stateful-model-test`).
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The code is browser-only and cannot run under Node; run the same property in the browser test runner instead.
|
||||
- You need coverage-guided search. Use `jazzer`.
|
||||
|
||||
## Set up
|
||||
|
||||
npm install --save-dev fast-check
|
||||
|
||||
fast-check runs inside any runner. The example uses `node --test`, which needs
|
||||
no extra install.
|
||||
|
||||
## Minimal example (`props.test.mjs`)
|
||||
|
||||
import test from 'node:test';
|
||||
import fc from 'fast-check';
|
||||
|
||||
const encode = (b) => Buffer.from(b).toString('hex');
|
||||
const decode = (s) => Uint8Array.from(Buffer.from(s, 'hex'));
|
||||
|
||||
test('round trip', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.uint8Array({ maxLength: 256 }), (bytes) =>
|
||||
Buffer.compare(Buffer.from(decode(encode(bytes))), Buffer.from(bytes)) === 0),
|
||||
{ numRuns: 1000 },
|
||||
);
|
||||
});
|
||||
|
||||
## Run
|
||||
|
||||
node --test props.test.mjs
|
||||
|
||||
Passing looks like: `ℹ pass 1` and `ℹ fail 0`, exit 0.
|
||||
Failure shows `Counterexample: [...]`, `Shrunk N time(s)` and a line
|
||||
`{ seed: -2075209501, path: "..." }`, exit non-zero. Replay it by passing the
|
||||
same values: `fc.assert(prop, { seed: -2075209501, path: "8:4:..." })`. Pin
|
||||
important cases permanently with `{ examples: [[...]] }`.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "prop-round-trip-js", "claim": "decode(encode(x)) equals x for generated byte arrays", "kind": "parsing", "rung": 2, "cmd": "node --test props.test.mjs", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- It samples (100 runs by default; `numRuns` raises it). The arbitrary decides what is ever tried, so check its bounds against real inputs.
|
||||
- A property that returns `true` for any input is vacuous. Test the test: break the code on purpose, confirm a counterexample appears, restore it.
|
||||
- Number generators include `NaN`, `-0` and huge values only if you ask; `fc.integer()` is not `fc.double()`.
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: fault-injection-storage
|
||||
title: Fault injection for storage (power loss, disk full, short writes)
|
||||
answers: If the machine dies or the disk fills in the middle of a write, do the data reopen correctly with nothing lost that was acknowledged?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: state-machine, general
|
||||
cost: medium
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- Code writes its own files (journal, snapshot, backup) and claims to be crash-safe or atomic.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- A database makes the guarantee and you only use its API: test your use of transactions instead.
|
||||
- You need real kernel or hardware faults (reordered writes, lost fsync); this simulates file contents only.
|
||||
|
||||
## Set up
|
||||
|
||||
Make the last write observable: record the file bytes before and after it. Then
|
||||
simulate each fault by building the damaged file yourself and reopening it:
|
||||
|
||||
- power loss: for every cut `k` in `1..len(last_write)`, the file is `before + last[:k]`;
|
||||
- disk full or short write: a write function that raises `OSError` after N bytes.
|
||||
|
||||
## Minimal example (Python; a checksummed append-only log)
|
||||
|
||||
import os, tempfile, zlib
|
||||
|
||||
class Log:
|
||||
def __init__(self, path):
|
||||
self.path, self.items = path, []
|
||||
if os.path.exists(path):
|
||||
raw = open(path, "rb").read()
|
||||
good = 0
|
||||
for line in raw.splitlines(keepends=True):
|
||||
body, _, crc = line.rstrip(b"\n").rpartition(b" ")
|
||||
if not line.endswith(b"\n") or not crc.isdigit() or zlib.crc32(body) != int(crc):
|
||||
break # torn tail: drop it
|
||||
self.items.append(body.decode()); good += len(line)
|
||||
if good < len(raw):
|
||||
open(path, "r+b").truncate(good) # heal
|
||||
def append(self, text):
|
||||
line = text.encode() + b" " + str(zlib.crc32(text.encode())).encode() + b"\n"
|
||||
with open(self.path, "ab") as f:
|
||||
f.write(line); f.flush(); os.fsync(f.fileno())
|
||||
self.items.append(text)
|
||||
|
||||
def test_power_loss_at_every_byte_of_the_last_append():
|
||||
p = os.path.join(tempfile.mkdtemp(), "log")
|
||||
log = Log(p); log.append("one"); log.append("two")
|
||||
before = open(p, "rb").read()
|
||||
log.append("three")
|
||||
last = open(p, "rb").read()[len(before):]
|
||||
for k in range(1, len(last)): # every cut short of the whole line
|
||||
open(p, "wb").write(before + last[:k])
|
||||
assert Log(p).items == ["one", "two"], f"cut at {k}"
|
||||
assert open(p, "rb").read() == before, f"not healed at {k}"
|
||||
open(p, "wb").write(before + last)
|
||||
assert Log(p).items == ["one", "two", "three"]
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_faults.py
|
||||
|
||||
Passing looks like: `1 passed`, exit 0. Failure names the byte cut (`cut at 7`).
|
||||
One reference project's store also checks that reports after reopening equal those from before.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "torn-write-recovery", "claim": "a power cut at any byte of the last append reopens to the state before it", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_faults.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- It covers truncation of the last write only. Torn writes that leave garbage in the middle, reordered writes, a lost `fsync` and media errors need other tests or a real crash rig.
|
||||
- Also check an acknowledged write is never lost, not only that the file opens.
|
||||
- Check the check: remove the CRC check or the truncate and see it fail.
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: generator-coverage
|
||||
title: Checking that random tests actually reach interesting cases
|
||||
answers: Is my property or model test really exercising edge cases and rare commands, or is it passing because it never gets there?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: general, state-machine
|
||||
cost: low
|
||||
detect: python3 -c "import hypothesis"
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- You wrote a property, model or fuzz test and it passes on the first try.
|
||||
- The generator filters, rejects or chooses by weights, so most cases may be boring or discarded.
|
||||
- A model test might never post, reverse or close anything.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The test is a fixed example.
|
||||
|
||||
## Set up
|
||||
|
||||
Count what happens. In Hypothesis use `event()` and `target()` and read
|
||||
`--hypothesis-show-statistics`; in proptest print a count per accepted command and per
|
||||
refusal (one reference project's model test does this under `MODEL_STATS=1`); in fast-check use
|
||||
`fc.statistics`; in a fuzzer use `cargo fuzz coverage` or the coverage output.
|
||||
|
||||
## Minimal example (Python)
|
||||
|
||||
from hypothesis import given, event, strategies as st
|
||||
|
||||
@given(st.integers(-5, 150), st.integers(0, 100))
|
||||
def test_withdraw_cases_all_occur(amount, balance):
|
||||
if amount <= 0:
|
||||
event("bad amount")
|
||||
elif amount > balance:
|
||||
event("insufficient")
|
||||
else:
|
||||
event("success")
|
||||
# ... the real assertions about withdraw(amount, balance) go here
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_cov.py --hypothesis-show-statistics
|
||||
|
||||
Passing looks like: `1 passed` and, in the statistics block, each event
|
||||
(`bad amount`, `insufficient`, `success`) with a share well above zero. Failure here is
|
||||
a reading task: any event at 0 percent or under about 1 percent means that branch is
|
||||
effectively untested, and the generator needs fixing. To make this automatic, assert
|
||||
on counts with a collected dictionary in a small harness, or fail on health-check
|
||||
warnings (`HealthCheck.filter_too_much`, `too_slow`) by not suppressing them.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "generators-reach-cases", "claim": "the withdraw property test exercises bad, insufficient and successful cases", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_cov.py --hypothesis-show-statistics", "expect": {"exit": 0, "stdout_contains": "success"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Events show that a case occurred, not that the assertion beside it is strong.
|
||||
- A generator that reaches every named case can still miss ones you did not name; add boundary values by hand (`@example`).
|
||||
- Check the check: narrow the generator (balance always 0) and confirm "success" disappears from the statistics.
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: go-fuzz
|
||||
title: Native Go fuzzing with go test -fuzz
|
||||
answers: Can any input make this Go function panic, hang or break an invariant?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: go
|
||||
kinds: parsing, general
|
||||
cost: low
|
||||
detect: go version
|
||||
ran_here: no
|
||||
verified: docs
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- A Go function parses or processes input from outside: decoders, importers, request handlers.
|
||||
- You want the standard toolchain only, with saved failing inputs that become regression tests automatically.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The input must be structured values and you want shrinking: `go-rapid`.
|
||||
- The target needs more than one second a call; the engine treats that as a hang.
|
||||
|
||||
## Set up
|
||||
|
||||
Nothing to install beyond Go. Write a `FuzzXxx` function in a `*_test.go` file with
|
||||
seeds via `f.Add`. Supported argument types: `string`, `[]byte`, the integer and
|
||||
float types, and `bool`.
|
||||
|
||||
## Minimal example (`parse_test.go`)
|
||||
|
||||
package pair
|
||||
|
||||
import "testing"
|
||||
|
||||
func FuzzParsePair(f *testing.F) {
|
||||
f.Add("1,2")
|
||||
f.Add("")
|
||||
f.Fuzz(func(t *testing.T, s string) {
|
||||
a, b, err := ParsePair(s)
|
||||
if err == nil && (a < 0 || b < 0) {
|
||||
t.Fatalf("accepted a negative value from %q", s)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
## Run
|
||||
|
||||
go test -run=FuzzParsePair ./... # replays seeds and saved failures only
|
||||
go test -fuzz=FuzzParsePair -fuzztime=30s # fuzzes for 30 seconds
|
||||
|
||||
`-fuzz` takes a regex that must match exactly one fuzz test in the package.
|
||||
Passing looks like: the fuzz run ends at the time limit with exit 0 and no `--- FAIL`.
|
||||
Failure writes a minimised input to `testdata/fuzz/FuzzParsePair/<hash>`, prints
|
||||
`FAIL`, and exits 1. Commit that file: from then on plain `go test` replays it as a
|
||||
unit test. Re-run just that case with `go test -run=FuzzParsePair/<hash>`.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "fuzz-parse-pair-go", "claim": "ParsePair survives 30 seconds of fuzzing and every saved failing input", "kind": "parsing", "rung": 2, "cmd": "go test -run=FuzzParsePair ./... && go test -fuzz=FuzzParsePair -fuzztime=30s", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- A clean run means nothing was found in that time. Coverage guidance works best on AMD64 and ARM64.
|
||||
- Only the failures that panic, call `t.Fatal`, or run over time are caught; wrong answers need assertions in the target.
|
||||
- Not run here (Go is not installed on this machine). Flags, directory layout and types are from the official Go fuzzing documentation. Check the check: add a deliberate panic behind a seed-adjacent input and see it found.
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: go-rapid
|
||||
title: Property testing in Go with rapid
|
||||
answers: Does this Go code hold its law for generated inputs, and what is the smallest failing case?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: go
|
||||
kinds: general, parsing, money, state-machine
|
||||
cost: low
|
||||
detect: go version
|
||||
ran_here: no
|
||||
verified: docs
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- Go code has a law (round trip, sorted output, idempotence, agreement with a model) and you want shrinking.
|
||||
- You want a stateful model test using `T.Repeat` (see `stateful-model-test`).
|
||||
|
||||
## Do not use when
|
||||
|
||||
- You want coverage-guided search: use `go-fuzz`. rapid can be wired into it with `rapid.MakeFuzz`, but the fuzzing engine then does the guiding, not rapid.
|
||||
- A table of examples already covers the cases that matter (see the `test-quality` section).
|
||||
|
||||
## Set up
|
||||
|
||||
go get pgregory.net/rapid
|
||||
# in a *_test.go file: import "pgregory.net/rapid"
|
||||
|
||||
## Minimal example
|
||||
|
||||
package hexcodec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"pgregory.net/rapid"
|
||||
)
|
||||
|
||||
func TestRoundTrip(t *testing.T) {
|
||||
rapid.Check(t, func(t *rapid.T) {
|
||||
data := rapid.SliceOf(rapid.Byte()).Draw(t, "data")
|
||||
got, err := hex.DecodeString(hex.EncodeToString(data))
|
||||
if err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatalf("round trip failed for %v: %v, %v", data, got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
## Run
|
||||
|
||||
go test -run TestRoundTrip ./...
|
||||
go test -rapid.checks=10000 -run TestRoundTrip ./...
|
||||
|
||||
Passing looks like: `ok <package>` and exit 0.
|
||||
Failure shows the minimal failing draw (`data = []byte{...}`) and `FAIL`, exit 1.
|
||||
rapid saves minimised failing cases and re-runs them automatically; the
|
||||
directory was not confirmed against the docs here, so look for a new
|
||||
`testdata/` subdirectory after a failure and commit it. Each flag also has a
|
||||
`RAPID_` environment variable (for example `RAPID_CHECKS`).
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "prop-round-trip-go", "claim": "hex decode of encode returns the input for generated byte slices", "kind": "parsing", "rung": 2, "cmd": "go test -run TestRoundTrip ./...", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- 100 checks by default; it samples. Raise `-rapid.checks` for important laws.
|
||||
- `t.Skip` in a property discards the case; if most cases skip, the pass is nearly empty.
|
||||
- Not run here (Go is not installed on this machine). The example, `-rapid.checks`, the `RAPID_` variables, `T.Repeat` and `MakeFuzz` come from the package documentation; the failure-file location and `-rapid.seed` could not be confirmed. Break the code on purpose to see the check fail.
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: hostile-input-from-schema
|
||||
title: Hostile arguments generated from an API or tool schema
|
||||
answers: Does every call my API or tool accepts survive wrong, missing, huge and strange arguments with a clean error and no crash?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: parsing, general
|
||||
cost: medium
|
||||
detect: python3 -c "import hypothesis_jsonschema"
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- A server, CLI or agent tool publishes a schema (JSON Schema, OpenAPI, MCP `tools/list`) for its inputs.
|
||||
- A panic or internal error reachable by one request is a denial of service or loses data.
|
||||
- You need to show that after hostile calls the server still serves and its data still reopens.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- There is no schema; write one, or fuzz the raw handler with `cargo-fuzz` or `atheris`.
|
||||
- You only care about valid calls: use ordinary tests.
|
||||
|
||||
## Set up
|
||||
|
||||
pip install hypothesis hypothesis-jsonschema pytest
|
||||
|
||||
For each operation, generate valid arguments from its schema, then make them
|
||||
hostile: wrong types, missing and extra fields, empty and huge strings, negative,
|
||||
fractional and maximum numbers, control characters, absurd dates.
|
||||
|
||||
## Minimal example
|
||||
|
||||
from hypothesis import given, settings, strategies as st
|
||||
from hypothesis_jsonschema import from_schema
|
||||
|
||||
SCHEMA = {"type": "object", "required": ["cents", "memo"], "properties": {
|
||||
"cents": {"type": "integer", "minimum": 0}, "memo": {"type": "string"}}}
|
||||
|
||||
def handle(args): # the thing under test: result or clean refusal
|
||||
if not isinstance(args, dict) or not isinstance(args.get("cents"), int) \
|
||||
or isinstance(args.get("cents"), bool) or args["cents"] < 0:
|
||||
return {"error": "invalid_arguments"}
|
||||
return {"ok": len(str(args.get("memo", "")))}
|
||||
|
||||
hostile = st.one_of(
|
||||
from_schema(SCHEMA),
|
||||
st.recursive(st.none() | st.booleans() | st.integers() | st.floats() | st.text(),
|
||||
lambda c: st.lists(c, max_size=3) | st.dictionaries(st.text(max_size=5), c, max_size=3)))
|
||||
|
||||
@settings(max_examples=300)
|
||||
@given(hostile)
|
||||
def test_no_crash_clean_error(args):
|
||||
out = handle(args) # any exception here is a failure
|
||||
assert "ok" in out or out.get("error")
|
||||
assert handle({"cents": 1, "memo": "x"}) == {"ok": 1} # still serving afterwards
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_hostile.py
|
||||
|
||||
Passing looks like: `1 passed`, exit 0. Failure shows the shrunk argument that raised or
|
||||
got no clean answer.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "hostile-args", "claim": "no generated or mangled argument crashes the handler; each gets a result or a clean error", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q test_hostile.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 600}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Only the shapes generated. A server whose crash needs a particular combination across fields or calls needs a stateful sequence (`stateful-model-test`).
|
||||
- "Clean error" is whatever your assert accepts; define it (error code, no stack trace, no data change).
|
||||
- Check after the hostile calls that the server still answers and the stored data reopens. One reference project's suite does both: every tool is called with hostile arguments, then a restarted server must still read the books.
|
||||
- Check the check: add a deliberate crash on one input class (`cents` above 2**63) and see it found.
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: hypothesis
|
||||
title: Property testing in Python with Hypothesis
|
||||
answers: Does this Python function keep its promise for every input Hypothesis can generate, and what is the smallest input that breaks it?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: python
|
||||
kinds: general, parsing, money, state-machine
|
||||
cost: low
|
||||
detect: python3 -c "import hypothesis"
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- A function has a law that must hold for all inputs and one example test shows only one case.
|
||||
- You want shrinking to a minimal failing input and automatic replay of earlier failures.
|
||||
- Money in integer cents, parsers, serialisers, sort or search code.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- No packages may be installed. Use `python-stdlib-property`.
|
||||
- The function is slow (over about 50 ms a call): Hypothesis will run it hundreds of times. Lower `max_examples` or test a smaller unit.
|
||||
- The input space is a coverage problem for a native parser. Use `atheris`.
|
||||
|
||||
## Set up
|
||||
|
||||
python3 -m venv .venv && .venv/bin/pip install hypothesis pytest
|
||||
|
||||
Put tests in `tests/test_props.py`. Hypothesis stores failures in `.hypothesis/`
|
||||
(local, normally git-ignored); pin important ones with `@example(...)`.
|
||||
|
||||
## Minimal example
|
||||
|
||||
from hypothesis import given, settings, strategies as st
|
||||
|
||||
def encode(b: bytes) -> str:
|
||||
return b.hex()
|
||||
|
||||
def decode(s: str) -> bytes:
|
||||
return bytes.fromhex(s)
|
||||
|
||||
@settings(max_examples=500)
|
||||
@given(st.binary(max_size=256))
|
||||
def test_round_trip(data):
|
||||
assert decode(encode(data)) == data
|
||||
|
||||
# money: integer cents, never floats
|
||||
@given(st.integers(0, 10**9), st.integers(0, 10**9))
|
||||
def test_add_commutes(a, b):
|
||||
assert a + b == b + a
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q tests/test_props.py
|
||||
|
||||
Passing looks like: `2 passed` and exit 0.
|
||||
Failure shows `Falsifying example: test_round_trip(data=b'\x00')` (shrunk) and
|
||||
exit 1. Add `--hypothesis-seed=0` to make a run reproducible in CI, and
|
||||
`--hypothesis-show-statistics` to see how many examples were valid.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "prop-round-trip-py", "claim": "decode(encode(x)) == x for generated byte strings", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q tests/test_props.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- It samples; the default is 100 examples. Raise `max_examples` for important laws and keep strategies as wide as real input.
|
||||
- Overusing `assume()` or `.filter()` makes most examples discarded; Hypothesis warns with a health-check failure. Fix the strategy, do not suppress the check.
|
||||
- To check the test can fail, break the code on purpose and see a shrunk `Falsifying example`. A fixed seed (`derandomize=True`) repeats the same sample forever, so run it with a random seed too.
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: jazzer
|
||||
title: Fuzzing the JVM and JavaScript with Jazzer and Jazzer.js
|
||||
answers: Can any input make this Java, Kotlin or Node code throw an unexpected exception, hang or hit a known bug pattern?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: java, kotlin, javascript, typescript
|
||||
kinds: parsing, general
|
||||
cost: medium
|
||||
detect: jazzer --help
|
||||
ran_here: no
|
||||
verified: docs
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- JVM or Node code parses or processes untrusted input and should throw only documented errors.
|
||||
- You want fuzz tests that run as ordinary unit tests (replaying saved crashes) in CI and as a long fuzz job on demand.
|
||||
- You want built-in detectors for common problems (injection sinks, unsafe deserialisation).
|
||||
|
||||
## Do not use when
|
||||
|
||||
- You want shrinking and structured values: `jqwik` or `fast-check`.
|
||||
- The code is Python (`atheris`) or Go (`go-fuzz`).
|
||||
|
||||
## Set up
|
||||
|
||||
JVM (JUnit 5): add `com.code-intelligence:jazzer-junit` as a test dependency
|
||||
(Maven Central; use the current version). A standalone `jazzer` binary is on the
|
||||
project's GitHub releases page.
|
||||
Node: `npm install --save-dev @jazzer.js/core` (and `@jazzer.js/jest-runner` for Jest).
|
||||
|
||||
## Minimal example (JVM, `ParserFuzzTest.java`)
|
||||
|
||||
import com.code_intelligence.jazzer.junit.FuzzTest;
|
||||
|
||||
class ParserFuzzTest {
|
||||
@FuzzTest
|
||||
void parsePairNeverCrashes(String input) {
|
||||
try {
|
||||
Parser.parsePair(input);
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// the documented error; any other exception is a finding
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Node equivalent (`fuzz.js`): `module.exports.fuzz = function (data /* Buffer */) { parsePair(data.toString()); };`
|
||||
|
||||
## Run
|
||||
|
||||
JAZZER_FUZZ=1 mvn test -Dtest=ParserFuzzTest # fuzzing mode
|
||||
mvn test # regression mode: replays saved crashes only
|
||||
npx jazzer fuzz # Node; see `npx jazzer --help` for corpus and time flags
|
||||
|
||||
Without `JAZZER_FUZZ=1` the JUnit tests only replay saved inputs, so a plain test run
|
||||
is quick and never fuzzes. Passing looks like: tests pass, exit 0. Failure reports the
|
||||
stack trace and writes the crashing input under
|
||||
`src/test/resources/<package>/<Class>Inputs/<method>/`; commit it so regression
|
||||
mode replays it. A time budget for the JVM and Node jobs is a libFuzzer flag
|
||||
(`-max_total_time=60`); I could not confirm from the docs how each wrapper passes it.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "fuzz-parser-jvm", "claim": "parsePair throws only IllegalArgumentException and all saved crashing inputs still pass", "kind": "parsing", "rung": 2, "cmd": "mvn -q test -Dtest=ParserFuzzTest", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
|
||||
|
||||
This replays the saved inputs; a fuzzing-mode job is a separate scheduled run.
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- In regression mode it only re-checks saved inputs; it does not search.
|
||||
- A fuzzing run finding nothing is not a proof; budget and seed corpus matter.
|
||||
- Not run here (no JDK is set on this machine). `@FuzzTest`, `JAZZER_FUZZ`, the artifact location and the Node install and signature are from the project READMEs; Node corpus and time flags were not confirmed. Check the check: plant a crash and see it found.
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: jqwik
|
||||
title: Property testing on the JVM with jqwik
|
||||
answers: Does this Java or Kotlin code hold its law for generated inputs, and what is the smallest failing sample?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: java, kotlin
|
||||
kinds: general, parsing, money, state-machine
|
||||
cost: medium
|
||||
detect: java -version
|
||||
ran_here: no
|
||||
verified: docs
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- JVM code has a law that must hold for all inputs and you run tests with Gradle or Maven.
|
||||
- You want shrinking, replayable seeds and generators built from annotations.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The author asks agents not to use it: since version 1.10 the jqwik user guide has an "Anti-AI Usage Clause" saying "This project is not meant to be used by any “AI” coding agents at all" and adding that the test engine prints a line to stdout on every run telling agents not to use the library; the main JVM alternative is Kotest's property testing (`io.kotest:kotest-property`, Kotlin API, actively released), and for plain Java `junit-quickcheck` exists but has had no commits since 2024.
|
||||
- You need coverage-guided search for a parser. Use `jazzer`.
|
||||
- The project is locked to JUnit 4 only; jqwik runs as its own JUnit Platform engine.
|
||||
|
||||
## Set up
|
||||
|
||||
Gradle (versions as in the jqwik user guide at the time of writing; check for newer):
|
||||
|
||||
testImplementation "net.jqwik:jqwik:1.10.2"
|
||||
test { useJUnitPlatform { includeEngines 'jqwik' } }
|
||||
|
||||
Maven: dependency `net.jqwik:jqwik:1.10.2`, scope `test`. Add `-parameters` to
|
||||
the Java compiler flags so failure reports show argument names.
|
||||
|
||||
## Minimal example
|
||||
|
||||
import net.jqwik.api.*;
|
||||
|
||||
class RoundTripProperties {
|
||||
static String encode(byte[] b) { return java.util.HexFormat.of().formatHex(b); }
|
||||
static byte[] decode(String s) { return java.util.HexFormat.of().parseHex(s); }
|
||||
|
||||
@Property(tries = 1000)
|
||||
boolean roundTrips(@ForAll byte[] data) {
|
||||
return java.util.Arrays.equals(decode(encode(data)), data);
|
||||
}
|
||||
}
|
||||
|
||||
## Run
|
||||
|
||||
./gradlew test # or: mvn test
|
||||
|
||||
Passing looks like: the build succeeds, exit 0, the test report shows the property
|
||||
with `tries = 1000` and no failures.
|
||||
Failure shows `Shrunk Sample (N steps)` and `Original Sample` plus a `seed`; the
|
||||
build exits non-zero. By default the next run tries the failing sample first
|
||||
(`afterFailure = SAMPLE_FIRST`); jqwik keeps this in a local database file, so check
|
||||
whether your build wipes it. Reproduce explicitly with `@Property(seed = "...")`.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "prop-round-trip-jvm", "claim": "decode(encode(x)) equals x for generated byte arrays", "kind": "parsing", "rung": 2, "cmd": "./gradlew test --tests 'RoundTripProperties'", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- It samples 1000 tries by default; edge cases (empty, extremes) are favoured but not exhaustive.
|
||||
- A fixed `seed` left in committed code freezes the sample; use `whenFixedSeed = FAIL` to forbid it.
|
||||
- If the engine is not on the test classpath the property is silently never run: confirm the report lists it. Break the code once and see it fail.
|
||||
- Not run here (no JDK version is set on this machine). Coordinates, annotations and the shrinking output are from the user guide; the failure-database location was not confirmed.
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: metamorphic
|
||||
title: Metamorphic testing when there is no oracle
|
||||
answers: Even though I cannot say what the right answer is, does changing the input in a known way change the output in the way it must?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: general, parsing, money
|
||||
cost: low
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- You cannot compute the expected output independently (search ranking, compilers, numeric code, image or report generation) but you know how the output must relate across two related inputs.
|
||||
- Typical relations: reordering the input does not change the result; scaling inputs scales outputs; adding an irrelevant item does not change the answer; a query with a stricter filter returns a subset.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- An oracle or reference exists. Use `differential-reference`.
|
||||
- The relation is only "decode undoes encode". That is `round-trip`.
|
||||
|
||||
## Set up
|
||||
|
||||
Pick relations from the domain, write each as a function of (input, transformed
|
||||
input), and run them on generated inputs with `hypothesis`, `proptest` or
|
||||
`fast-check`. One relation per test so a failure names it.
|
||||
|
||||
## Minimal example (Python; a median function)
|
||||
|
||||
from statistics import median
|
||||
from hypothesis import given, strategies as st
|
||||
|
||||
def my_median(xs): # under test
|
||||
s = sorted(xs)
|
||||
n = len(s)
|
||||
return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2
|
||||
|
||||
nums = st.lists(st.integers(-10**6, 10**6), min_size=1, max_size=50)
|
||||
|
||||
@given(nums, st.randoms())
|
||||
def test_order_does_not_matter(xs, rnd):
|
||||
ys = xs[:]; rnd.shuffle(ys)
|
||||
assert my_median(ys) == my_median(xs)
|
||||
|
||||
@given(nums, st.integers(-1000, 1000))
|
||||
def test_shift_shifts_median(xs, k):
|
||||
assert my_median([x + k for x in xs]) == my_median(xs) + k
|
||||
|
||||
@given(nums, st.integers(1, 1000))
|
||||
def test_scale_scales_median(xs, k):
|
||||
assert my_median([x * k for x in xs]) == my_median(xs) * k
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_metamorphic.py
|
||||
|
||||
Passing looks like: `3 passed`, exit 0. Failure names the relation and shrinks the input.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "meta-median", "claim": "median is order-independent and shifts and scales with its inputs", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_metamorphic.py", "expect": {"exit": 0, "stdout_contains": "3 passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- A relation only constrains the output, so a wrong function can satisfy one. Use several relations that together pin the behaviour down.
|
||||
- It never proves the output is the right value, only that it is consistent.
|
||||
- Check the check: replace the function with a plausible wrong one (the mean, the first element) and see at least one relation fail.
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: model-test-from-spec
|
||||
title: Model test transcribed from a formal spec (TLA+ or Lean)
|
||||
answers: Does the implementation behave like the formally specified design, step by step, including what it must refuse?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: state-machine, money
|
||||
cost: high
|
||||
detect: python3 -c "import hypothesis"
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- A TLA+, Lean or similar model of the design exists (or is being written) and its properties are proved or model-checked.
|
||||
- You need the proof to reach the code: the proved design is only worth something if the implementation does what it says.
|
||||
- Refusal rules matter (what must be rejected, and why), not just happy paths.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- There is no formal model. Write a plain `stateful-model-test` instead.
|
||||
- The model can be run directly as a program; then use `differential-executable-spec`, which needs no transcription.
|
||||
|
||||
## Set up
|
||||
|
||||
Write the model as a small pure function in the implementation's language, one
|
||||
branch per spec action, from the spec text and not from the implementation.
|
||||
Name each branch after the spec rule it transcribes. Then use the tooling from
|
||||
`stateful-model-test` to drive both with random command sequences.
|
||||
|
||||
## Minimal example (Python; the spec fragment is a TLA+ `Withdraw` action)
|
||||
|
||||
from hypothesis import strategies as st
|
||||
from hypothesis.stateful import RuleBasedStateMachine, rule
|
||||
|
||||
# Spec: Withdraw(n) == n > 0 /\ n <= balance /\ balance' = balance - n
|
||||
def spec_withdraw(balance, n): # returns (new_balance, refusal)
|
||||
if n <= 0: return balance, "bad_amount"
|
||||
if n > balance: return balance, "insufficient"
|
||||
return balance - n, None
|
||||
|
||||
class Account: # implementation under test
|
||||
def __init__(self): self.balance = 100
|
||||
def withdraw(self, n):
|
||||
if n <= 0: return "bad_amount"
|
||||
if n > self.balance: return "insufficient"
|
||||
self.balance -= n
|
||||
|
||||
class AgainstSpec(RuleBasedStateMachine):
|
||||
def __init__(self):
|
||||
super().__init__(); self.impl, self.balance = Account(), 100
|
||||
|
||||
@rule(n=st.integers(-5, 150))
|
||||
def withdraw(self, n):
|
||||
self.balance, want = spec_withdraw(self.balance, n)
|
||||
assert self.impl.withdraw(n) == want # same decision, same reason
|
||||
assert self.impl.balance == self.balance
|
||||
|
||||
TestAgainstSpec = AgainstSpec.TestCase
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_against_spec.py
|
||||
|
||||
Passing looks like: `1 passed`, exit 0. Failure names the command that diverged, with
|
||||
the shrunk sequence. Keep the spec's rule ids in comments so a mismatch points at a rule.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "model-vs-spec", "claim": "the implementation accepts and refuses commands as the TLA+ Withdraw action does", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_against_spec.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- The transcription is by hand. If it drifts from the spec, you test your reading of the spec; have it reviewed against the spec text.
|
||||
- It samples sequences. The proof covers all of them; this only shows no counterexample was found.
|
||||
- Commands the generator cannot express are not compared. List them. (One reference project's Lean differential test lists the model commands its input format cannot reach and leaves those to review.)
|
||||
- Make the test fail on purpose: change one comparison in the implementation, or let the model allow something the spec forbids.
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
id: old-data-compatibility
|
||||
title: Compatibility with data written by older and newer versions
|
||||
answers: Do files written by earlier versions still open to their recorded figures, and is data from a newer version reported as newer rather than corrupt?
|
||||
rung: 3
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: migration, state-machine, money
|
||||
cost: medium
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- The program reads files, databases or journals that users keep across upgrades.
|
||||
- You change a format, a schema or the rules for computing a stored figure.
|
||||
- An old version may meet newer data (downgrade, shared folder, restored backup).
|
||||
|
||||
## Do not use when
|
||||
|
||||
- You want sampled inputs: use `round-trip`; this uses fixed fixtures.
|
||||
|
||||
## Set up
|
||||
|
||||
1. When a format version ships, write real data with that version and commit it
|
||||
as `tests/fixtures/<version>/` together with `expected.json`, the figures the
|
||||
version itself computed. Never regenerate old fixtures with new code.
|
||||
2. Keep a newer-format fixture (or fake one with a bumped format field).
|
||||
|
||||
## Minimal example (Python)
|
||||
|
||||
import json, pathlib, tempfile
|
||||
|
||||
CURRENT = 2
|
||||
|
||||
def open_book(path):
|
||||
data = json.loads(pathlib.Path(path).read_text()) # raises on garbage
|
||||
v = data.get("format")
|
||||
if v is None or not isinstance(v, int):
|
||||
raise ValueError("corrupt: no format")
|
||||
if v > CURRENT:
|
||||
raise RuntimeError(f"newer: written by format {v}, this reader knows {CURRENT}")
|
||||
return {"total": sum(data["cents"])} # v1 and v2 both store `cents`
|
||||
|
||||
def test_old_fixture_reopens_to_recorded_figures():
|
||||
got = open_book("fixtures/v1/book.json")
|
||||
assert got == json.load(open("fixtures/v1/expected.json"))
|
||||
|
||||
def test_newer_is_reported_as_newer_and_left_untouched():
|
||||
p = pathlib.Path(tempfile.mkdtemp()) / "b.json"
|
||||
p.write_text(json.dumps({"format": 3, "cents": [1]}))
|
||||
before = p.read_bytes()
|
||||
try:
|
||||
open_book(p); assert False
|
||||
except RuntimeError as e:
|
||||
assert str(e).startswith("newer")
|
||||
assert p.read_bytes() == before # never repaired or rewritten
|
||||
|
||||
def test_damage_is_still_corrupt():
|
||||
p = pathlib.Path(tempfile.mkdtemp()) / "b.json"
|
||||
p.write_text("{not json")
|
||||
try:
|
||||
open_book(p); assert False
|
||||
except ValueError: pass
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_compat.py
|
||||
|
||||
Passing looks like: `3 passed`, exit 0. Failure shows which fixture gave other figures,
|
||||
or a newer file reported as corrupt (or the reverse).
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "old-data-compat", "claim": "v1 fixtures reopen to recorded figures; newer data is reported newer and untouched; damage stays corrupt", "kind": "migration", "rung": 3, "cmd": "python3 -m pytest -q test_compat.py", "expect": {"exit": 0, "stdout_contains": "3 passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Only the fixtures you have: keep one per released format.
|
||||
- Expected figures come from the old version; never regenerate them to make a test pass.
|
||||
- It does not show an upgrade is safe on real data: test the upgrade step on a copy.
|
||||
- Check the check: edit a fixture's figure and see the test fail; bump a format number and see "newer" appear.
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: proptest
|
||||
title: Property testing in Rust with proptest
|
||||
answers: Does this Rust function keep its promise for every input I can generate, not just the few I thought of?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: rust
|
||||
kinds: general, parsing, money, state-machine
|
||||
cost: low
|
||||
detect: cargo --version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- A pure function or data structure has a law that must hold for all inputs: round trip, idempotence, agreement with a slow reference, "never panics".
|
||||
- You want a failure reduced to a small input (shrinking) and replayed on every later run.
|
||||
- Money, parsing or index arithmetic, where the dangerous inputs are ones nobody writes by hand.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The law cannot be stated without re-implementing the function. Use `metamorphic` or `differential-reference`.
|
||||
- The property needs coverage-guided search of a deep parser. Use `cargo-fuzz`.
|
||||
- A proof is affordable and a sample is not enough. See the `prove` section.
|
||||
|
||||
## Set up
|
||||
|
||||
cargo add --dev proptest
|
||||
|
||||
Put the test in `#[cfg(test)]` in the crate or in `tests/props.rs`. Commit the
|
||||
`proptest-regressions` files that proptest writes (see `regression-seed-hygiene`).
|
||||
|
||||
## Minimal example
|
||||
|
||||
pub fn encode(x: &[u8]) -> String { x.iter().map(|b| format!("{:02x}", b)).collect() }
|
||||
pub fn decode(s: &str) -> Option<Vec<u8>> {
|
||||
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(1000))]
|
||||
#[test]
|
||||
fn round_trip(bytes in proptest::collection::vec(any::<u8>(), 0..256)) {
|
||||
prop_assert_eq!(decode(&encode(&bytes)), Some(bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
## Run
|
||||
|
||||
cargo test round_trip
|
||||
PROPTEST_CASES=10000 cargo test round_trip # more cases, same test
|
||||
|
||||
Passing looks like: `test tests::round_trip ... ok` and exit 0.
|
||||
Failure shows `minimal failing input: bytes = [0]` after shrinking, exit 101, and
|
||||
a line saying the seed was saved to a `proptest-regressions/...` file. Later runs
|
||||
replay that seed first. To make a test cheap for mutation testing or a slow
|
||||
host, `PROPTEST_MAX_SHRINK_ITERS=0` turns shrinking off.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "prop-round-trip", "claim": "decode(encode(x)) == x for generated byte strings", "kind": "parsing", "rung": 2, "cmd": "cargo test round_trip", "expect": {"exit": 0, "stdout_contains": "1 passed"}, "tier": "deep", "timeout_s": 600}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- It samples. 1000 cases of small inputs say nothing about the huge or odd ones the strategy never produces: check the ranges (`0..256`) against real input sizes.
|
||||
- A filter such as `prop_assume!` that rejects most cases makes a pass nearly empty. proptest aborts with "too many local rejects" when that happens; do not raise the limit to silence it.
|
||||
- To check the test can fail, break the code on purpose (change `{:02x}` to `{:x}` in `encode`) and see it fail with a shrunk input, then restore it. `cargo-mutants` does this at scale.
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: python-stdlib-property
|
||||
title: Property-style tests with only the Python standard library
|
||||
answers: Can I check a law over many generated inputs when I may not install any package?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: python
|
||||
kinds: general, parsing, money
|
||||
cost: low
|
||||
detect: python3 --version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- No third-party packages are allowed or available.
|
||||
- The law is simple (round trip, ordering, agreement with a reference) and a bounded, seeded random loop is enough.
|
||||
- You need a quick sample before deciding whether to bring in `hypothesis`.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- Packages are allowed: `hypothesis` shrinks failures and remembers them; this does not.
|
||||
- The input has structure that blind random bytes rarely satisfy (valid JSON, balanced entries). Write a structured generator or use `structure-aware-fuzzing`.
|
||||
|
||||
## Set up
|
||||
|
||||
Nothing to install. Put the test in `tests/test_props.py` and run it with `unittest`.
|
||||
|
||||
## Minimal example
|
||||
|
||||
import os, random, unittest
|
||||
|
||||
def encode(b): return b.hex()
|
||||
def decode(s): return bytes.fromhex(s)
|
||||
|
||||
class Props(unittest.TestCase):
|
||||
def test_round_trip(self):
|
||||
fixed = [0, 1, 2] # always run: reproducible
|
||||
fresh = [random.randrange(2**32) for _ in range(3)] # new ground each run
|
||||
extra = [int(s) for s in os.environ.get("SEEDS", "").split(",") if s]
|
||||
for seed in fixed + fresh + extra:
|
||||
rng = random.Random(seed)
|
||||
for _ in range(500):
|
||||
data = bytes(rng.randrange(256) for _ in range(rng.randrange(64)))
|
||||
with self.subTest(seed=seed, data=data):
|
||||
self.assertEqual(decode(encode(data)), data)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m unittest discover -s tests
|
||||
|
||||
Passing looks like: `Ran 1 test` then `OK`, exit 0.
|
||||
Failure shows `FAIL: test_round_trip (seed=..., data=...)` with the seed and input
|
||||
in the subTest label, exit 1. Reproduce a failing fresh seed with
|
||||
`SEEDS=<seed> python3 -m unittest discover -s tests`, then copy it into `fixed`.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "prop-round-trip-stdlib", "claim": "decode(encode(x)) == x over seeded random inputs", "kind": "parsing", "rung": 2, "cmd": "python3 -m unittest discover -s tests", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- There is no shrinking: the failing input may be large. Print it, then reduce by hand.
|
||||
- Uniform random bytes seldom hit edge cases (empty, maximum, boundary values). Add them to the generator explicitly.
|
||||
- The checker only sees what the generator makes. Test the check by breaking the code on purpose and seeing it fail.
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: regression-seed-hygiene
|
||||
title: Keeping failing seeds checked in, replayed and never orphaned
|
||||
answers: Once a random test or fuzzer found a bug, is that exact input still replayed on every run so the bug cannot return?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: general, parsing, state-machine
|
||||
cost: low
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- You use proptest, Hypothesis, fast-check, a fuzzer or rapid, and a failure has been found, or will be.
|
||||
- A random test went red once and green on re-run, and nobody recorded why.
|
||||
- You are finishing a bug fix found by a random or fuzz test.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The suite has only fixed example tests; those already replay.
|
||||
|
||||
## Set up
|
||||
|
||||
Know where each tool keeps failures, and commit those:
|
||||
|
||||
- proptest: `proptest-regressions/*.txt` (or `*.proptest-regressions` beside the test file); the path is printed on failure.
|
||||
- cargo-fuzz: `fuzz/artifacts/<target>/crash-*`; copy fixed cases to `fuzz/seeds/<target>/`.
|
||||
- Go native fuzzing: `testdata/fuzz/FuzzName/<hash>`; plain `go test` replays them.
|
||||
- Hypothesis: `.hypothesis/` is local; pin the minimal case with `@example(...)` in the test.
|
||||
- fast-check: pass `{ seed, path }` to reproduce, or add `examples: [[...]]` to keep it.
|
||||
|
||||
## Minimal example (Hypothesis: pin the shrunk failure)
|
||||
|
||||
from hypothesis import given, example, strategies as st
|
||||
|
||||
def parse_amount(s):
|
||||
return int(s.replace(",", "")) # fixed: used to reject "1,000"
|
||||
|
||||
@given(st.integers(0, 10**9).map(lambda n: f"{n:,}"))
|
||||
@example("1,000") # the case the fuzzer found; stays forever
|
||||
def test_parse_amount(text):
|
||||
assert parse_amount(text) == int(text.replace(",", ""))
|
||||
|
||||
A cheap guard that none are orphaned (a deleted test leaves its seed file behind):
|
||||
|
||||
# check_seeds.sh: every seed file maps to an existing test file
|
||||
for f in proptest-regressions/*.txt; do
|
||||
t=$(basename "$f" .txt); [ -e "src/$t.rs" ] || [ -e "tests/$t.rs" ] || { echo "orphaned: $f"; exit 1; }
|
||||
done
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_amount.py
|
||||
sh check_seeds.sh
|
||||
|
||||
Passing looks like: `1 passed`, exit 0, and no `orphaned:` line. A removed pin makes
|
||||
the pinned case vanish silently, so review diffs of `@example` and seed files.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "seeds-replayed", "claim": "every saved failing input is replayed and no seed file is orphaned", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_amount.py && sh check_seeds.sh", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Replay proves the old bug is not back, not that the area is clean.
|
||||
- A seed recorded for an old test shape may no longer reach the same code after a refactor (proptest seeds depend on the strategy); for important bugs also add a plain named example test.
|
||||
- Check the check: revert the fix and confirm the pinned or saved case fails by itself, with random generation turned off (`derandomize=True`, or a replay of only the seed file).
|
||||
@@ -0,0 +1,78 @@
|
||||
---
|
||||
id: replay-equivalence
|
||||
title: Replay equivalence for event-sourced and journalled state
|
||||
answers: Is the live state exactly what you get by replaying the log from scratch, and does a refused command leave no trace?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: state-machine, money
|
||||
cost: medium
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- State is built from a log of events or journal lines (event sourcing, write-ahead logs, ledgers, undo stacks).
|
||||
- Restart, backup restore and replication rebuild state by replay, so any drift between live and replayed state is data loss waiting to happen.
|
||||
- Commands can be refused (validation, closed period, limits).
|
||||
|
||||
## Do not use when
|
||||
|
||||
- State is stored directly and no log exists. Use `fault-injection-storage` and `round-trip`.
|
||||
|
||||
## Set up
|
||||
|
||||
Expose two things: a way to apply a command (which may append to the log and
|
||||
change live state) and a way to build state from the log alone. Drive both with
|
||||
random command sequences, including commands that must be refused.
|
||||
|
||||
## Minimal example (Python)
|
||||
|
||||
from hypothesis import given, strategies as st
|
||||
|
||||
class Store:
|
||||
def __init__(self): self.log, self.balance = [], 0
|
||||
@staticmethod
|
||||
def fold(log): # state from the log alone
|
||||
b = 0
|
||||
for kind, n in log:
|
||||
b += n if kind == "dep" else -n
|
||||
return b
|
||||
def command(self, kind, n):
|
||||
if n <= 0 or (kind == "wd" and n > self.balance):
|
||||
return "refused"
|
||||
self.log.append((kind, n))
|
||||
self.balance += n if kind == "dep" else -n
|
||||
return "ok"
|
||||
|
||||
cmds = st.lists(st.tuples(st.sampled_from(["dep", "wd"]), st.integers(-3, 50)), max_size=40)
|
||||
|
||||
@given(cmds)
|
||||
def test_live_equals_replay_and_refusals_leave_no_trace(commands):
|
||||
s = Store()
|
||||
for kind, n in commands:
|
||||
log_before, state_before = list(s.log), s.balance
|
||||
if s.command(kind, n) == "refused":
|
||||
assert s.log == log_before # nothing written
|
||||
assert s.balance == state_before # nothing changed
|
||||
assert s.balance == Store.fold(s.log) # live == replay, after every command
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_replay.py
|
||||
|
||||
Passing looks like: `1 passed`, exit 0. Failure shows the shortest command list where live
|
||||
and replayed state differ, or where a refusal wrote something.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "replay-equivalence", "claim": "live state equals state replayed from the log after any command sequence, and refused commands change nothing", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_replay.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Replay may use the same code as the live path, and then agrees trivially. Make replay a separate, simpler fold, or replay through the persisted bytes (write the log, reopen, compare).
|
||||
- Compare everything observable (balances, indexes, derived reports), not one number; a field left out hides drift.
|
||||
- Include refused commands in the generator, or the "no trace" half is never tested. Count how many were refused.
|
||||
- Check the check: make a refused command append to the log, or make replay skip one event type, and see it fail.
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: round-trip
|
||||
title: Round-trip properties for encode/decode, serialise/parse and do/undo
|
||||
answers: Does undoing an operation always return exactly what I started with, for every input I can generate?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: any
|
||||
kinds: parsing, general, money
|
||||
cost: low
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- A serialiser and a parser, an encoder and a decoder, a compressor and decompressor, or a do and an undo operation exist.
|
||||
- Data is saved and reloaded (files, wire formats, journal lines, backups).
|
||||
- You want a cheap check that loses no information, with no oracle needed.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The encoding is lossy by design; test the part that must survive instead.
|
||||
- Only one direction exists; use `metamorphic` or `algebraic-laws`.
|
||||
|
||||
## Set up
|
||||
|
||||
Generate values of the in-memory type (not strings of the encoded form), encode,
|
||||
decode, compare. Also test the other direction where it matters: for any text
|
||||
the parser accepts, encoding the parsed value gives the canonical text again.
|
||||
|
||||
## Minimal example (Python; JSON of integer cents)
|
||||
|
||||
import json
|
||||
from hypothesis import given, strategies as st
|
||||
|
||||
entry = st.fixed_dictionaries({
|
||||
"memo": st.text(max_size=40),
|
||||
"cents": st.integers(-2**63, 2**63 - 1),
|
||||
"tags": st.lists(st.text(max_size=8), max_size=5),
|
||||
})
|
||||
|
||||
@given(entry)
|
||||
def test_value_round_trip(e):
|
||||
assert json.loads(json.dumps(e)) == e
|
||||
|
||||
@given(entry)
|
||||
def test_text_is_stable(e):
|
||||
text = json.dumps(e, sort_keys=True)
|
||||
assert json.dumps(json.loads(text), sort_keys=True) == text
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_round_trip.py
|
||||
|
||||
Passing looks like: `2 passed`, exit 0.
|
||||
Failure shows the shrunk value that came back changed, exit 1.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "round-trip-entry", "claim": "entries survive serialise then parse unchanged", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q test_round_trip.py", "expect": {"exit": 0, "stdout_contains": "2 passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- It shows no loss, not that the encoding is right: a format that stores the wrong thing round-trips perfectly. Add a golden file or reference parser for the format itself.
|
||||
- It only covers values the generator makes. Give it the awkward ones: empty, maximum, negative, non-ASCII, a trailing newline, NaN if floats are allowed.
|
||||
- Equal after the round trip can hide equality that is too loose (`1 == 1.0`, `0 == -0.0`); compare types and canonical text too.
|
||||
- Check the check: drop a field from the encoder and see the test fail.
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: stateful-model-test
|
||||
title: Stateful model testing against a simple in-memory model
|
||||
answers: After any sequence of operations, does the real system agree with a trivially simple model of what it should do?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: rust, python, typescript, go
|
||||
kinds: state-machine, general, money
|
||||
cost: medium
|
||||
detect: python3 -c "import hypothesis"
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- The system has state and commands (a store, ledger, cache, queue, editor buffer) and bugs appear only after particular sequences.
|
||||
- You can write a model in a few dozen lines using lists and dictionaries, with no performance tricks.
|
||||
- You need to show that refused commands change nothing and that accepted ones do what the model says.
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The model would be as complex as the system. Then the two share bugs; use `model-test-from-spec` or `differential-reference` instead.
|
||||
- The behaviour is stateless: use `proptest`, `hypothesis` or `fast-check` directly.
|
||||
- The commands race each other. See the `concurrency` section.
|
||||
|
||||
## Set up
|
||||
|
||||
Python: `pip install hypothesis`. Rust: `cargo add --dev proptest proptest-state-machine`.
|
||||
TypeScript: `npm i -D fast-check` (`fc.commands`, `fc.modelRun`). Go: `rapid`'s `T.Repeat`.
|
||||
|
||||
## Minimal example (Python, Hypothesis `RuleBasedStateMachine`)
|
||||
|
||||
from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
|
||||
from hypothesis import strategies as st
|
||||
|
||||
class Stack: # the system under test
|
||||
def __init__(self): self.items = []
|
||||
def push(self, x): self.items.append(x)
|
||||
def pop(self): return self.items.pop()
|
||||
|
||||
class StackMachine(RuleBasedStateMachine):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.sut, self.model = Stack(), []
|
||||
|
||||
@rule(x=st.integers())
|
||||
def push(self, x):
|
||||
self.sut.push(x); self.model.append(x)
|
||||
|
||||
@rule()
|
||||
def pop(self):
|
||||
if self.model: # only when the model allows it
|
||||
assert self.sut.pop() == self.model.pop()
|
||||
|
||||
@invariant()
|
||||
def same_contents(self):
|
||||
assert self.sut.items == self.model
|
||||
|
||||
TestStack = StackMachine.TestCase
|
||||
|
||||
## Run
|
||||
|
||||
python3 -m pytest -q test_stack.py
|
||||
|
||||
Passing looks like: `1 passed`, exit 0.
|
||||
Failure prints the shortest failing sequence as `state.push(x=0)`, `state.push(x=1)`,
|
||||
`state.pop()`, exit 1. Rust prints `minimal failing input` with the transition list;
|
||||
fast-check prints `Counterexample: [push(0),push(1),pop()]`.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "model-stack", "claim": "the stack agrees with a list model after any command sequence", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_stack.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Sequences are short and random; a bug needing a rare long sequence can hide. Weight the generator toward commands that interact (post then reverse, close then add).
|
||||
- A model that never reaches interesting states passes vacuously. Count how often each accepted command and each refusal occurs (one reference project's ledger test prints these under `MODEL_STATS=1`; its first version never posted an entry and agreed with the model for the wrong reason).
|
||||
- Check the check: make the model wrong on purpose (for example allow a second reversal) and see the test fail quickly.
|
||||
- It compares only what you read back. Compare every observable: results, refusals, and a full read of the state.
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: structure-aware-fuzzing
|
||||
title: Structure-aware fuzzing with `arbitrary` and grammar-based inputs
|
||||
answers: Can sequences of valid-looking operations, not just random bytes, break the code or its invariants?
|
||||
rung: 2
|
||||
section: many-inputs
|
||||
languages: rust
|
||||
kinds: state-machine, parsing, money
|
||||
cost: medium
|
||||
detect: cargo fuzz --version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
|
||||
- Raw bytes almost never form valid input (JSON, command lists, balanced entries), so a plain fuzzer wastes its time on rejections.
|
||||
- You want the fuzzer to drive a sequence of operations on a state machine and check invariants after each.
|
||||
- The fuzz target should check more than "no panic": a model, a round trip, "a refused command changes nothing".
|
||||
|
||||
## Do not use when
|
||||
|
||||
- The input really is arbitrary bytes (a file format parser): use `cargo-fuzz` with `&[u8]`.
|
||||
- You want shrinking and readable counterexamples: `proptest` is better at that.
|
||||
|
||||
## Set up
|
||||
|
||||
cargo add arbitrary --features derive # in the fuzz crate (cargo fuzz init already adds it)
|
||||
|
||||
Derive `Arbitrary` on the input types. For grammar-style input (valid SQL,
|
||||
JSON), write a small generator that turns the fuzzer's bytes into a valid
|
||||
document with `Unstructured`, or use a grammar-based fuzzer such as `Grammarinator`.
|
||||
|
||||
## Minimal example (`fuzz/fuzz_targets/fuzz_target_1.rs`)
|
||||
|
||||
#![no_main]
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
// in the library crate:
|
||||
// #[derive(Debug, arbitrary::Arbitrary)]
|
||||
// pub enum Op { Deposit(u32), Withdraw(u32) }
|
||||
// Account::apply(&mut self, &Op) -> Result<(), &'static str>
|
||||
|
||||
fuzz_target!(|ops: Vec<mycrate::Op>| {
|
||||
let mut acct = mycrate::Account::default();
|
||||
let mut model: u64 = 0;
|
||||
for op in &ops {
|
||||
let before = acct.cents;
|
||||
if acct.apply(op).is_ok() {
|
||||
match op {
|
||||
mycrate::Op::Deposit(n) => model += *n as u64,
|
||||
mycrate::Op::Withdraw(n) => model -= *n as u64,
|
||||
}
|
||||
} else {
|
||||
assert_eq!(acct.cents, before, "refused op changed state");
|
||||
}
|
||||
assert_eq!(acct.cents as u64, model, "balance diverged from model");
|
||||
}
|
||||
});
|
||||
|
||||
## Run
|
||||
|
||||
RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 -- -max_total_time=60
|
||||
|
||||
Passing looks like: `Done N runs in 60 second(s)`, exit 0.
|
||||
Failure prints the panic or assertion and the input as the `Debug` of the Rust
|
||||
value (`[Withdraw(...)]`), then exits 1 with a crash file in `fuzz/artifacts/`.
|
||||
Print an old crash as Rust values with `cargo fuzz fmt fuzz_target_1 <crash-file>`.
|
||||
|
||||
## As a contract check
|
||||
|
||||
{"id": "fuzz-account-ops", "claim": "no fuzzed operation sequence breaks the account model or changes state on refusal", "kind": "state-machine", "rung": 2, "cmd": "cd fuzz-host && RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 -- -max_total_time=60", "expect": {"exit": 0, "stdout_contains": "Done"}, "tier": "deep", "timeout_s": 600}
|
||||
|
||||
## What a pass does not prove
|
||||
|
||||
- Only what the run reached in its time budget; a clean run is not a proof.
|
||||
- A derived `Arbitrary` makes uniform-looking values. If the interesting values (zero, maximum, the same account twice) are rare, bias the generator by hand.
|
||||
- The invariants are only as good as the asserts. One reference project's operation-sequence target checks that the trial balance balances after any sequence; without that assert the same run would only look for panics.
|
||||
- Check the check: seed a bug (the example subtracts one extra cent on withdrawal) and see the fuzzer find it within seconds.
|
||||
Reference in new issue
Block a user