From 762d68c5413b83130e19903149eb60a3555a9c89 Mon Sep 17 00:00:00 2001 From: Anthony Lloyd Date: Wed, 25 Nov 2026 09:22:29 +0000 Subject: [PATCH] skill properties --- plugins/cscheck/.claude-plugin/plugin.json | 2 +- plugins/cscheck/.codex-plugin/plugin.json | 2 +- plugins/cscheck/README.md | 7 +-- plugins/cscheck/plugin.json | 2 +- .../cscheck/skills/closing-test-gaps/SKILL.md | 6 +-- .../cscheck/skills/finding-test-gaps/SKILL.md | 4 +- .../skills/writing-cscheck-tests/SKILL.md | 45 ++++++++++++++----- 7 files changed, 46 insertions(+), 22 deletions(-) diff --git a/plugins/cscheck/.claude-plugin/plugin.json b/plugins/cscheck/.claude-plugin/plugin.json index 4c2b391..f8beb4d 100644 --- a/plugins/cscheck/.claude-plugin/plugin.json +++ b/plugins/cscheck/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "cscheck", - "version": "0.1.1", + "version": "0.1.2", "description": "Find what a C# project's tests miss, and write tests that find bugs.", "author": { "name": "Anthony Lloyd" diff --git a/plugins/cscheck/.codex-plugin/plugin.json b/plugins/cscheck/.codex-plugin/plugin.json index aa9ea9e..f781270 100644 --- a/plugins/cscheck/.codex-plugin/plugin.json +++ b/plugins/cscheck/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "cscheck", - "version": "0.1.1", + "version": "0.1.2", "description": "Find what a C# project's tests miss, and write tests that find bugs.", "skills": ["./skills/"] } diff --git a/plugins/cscheck/README.md b/plugins/cscheck/README.md index 8838301..a89fd34 100644 --- a/plugins/cscheck/README.md +++ b/plugins/cscheck/README.md @@ -4,9 +4,9 @@ Agent skills for [CsCheck](https://github.com/AnthonyLloyd/CsCheck). Each `SKILL ## Skills -- [writing-cscheck-tests](skills/writing-cscheck-tests/SKILL.md) writes or strengthens tests, preferring CsCheck properties when appropriate, falling back to normal tests for specific bugs. It covers `Sample`, `Equality`, `SampleModelBased`, `SampleMetamorphic`, `SampleParallel`, `Spec`, `Faster`, causal profiling, `Single` and `Check.Hash`. It also covers generators that give usable inputs and hit the edges, readable shrunk failures, how long to run before trusting a pass, when a property can replace example tests, and what changed in CsCheck 5. +- [writing-cscheck-tests](skills/writing-cscheck-tests/SKILL.md) writes or strengthens tests, preferring CsCheck properties when appropriate, falling back to normal tests for specific bugs. It covers `Sample`, `Equality`, `SampleModelBased`, `SampleMetamorphic`, `SampleParallel`, `Spec`, `Faster`, causal profiling, `Single` and `Check.Hash`. It also covers the kinds of property that find bugs, from a model to a metamorphic relation where there's no model, generators that give usable inputs and hit the edges, readable shrunk failures, how long to run before trusting a pass, when a property can replace example tests, and what changed in CsCheck 5. - [finding-test-gaps](skills/finding-test-gaps/SKILL.md) finds the weak spots that coverage and mutants reveal. Code coverage shows code no test runs, and a sweep of hand-picked mutants shows code the tests run but don't check. Each mutant is compiled and tested in a copy, so no source file in the repo changes. It reports the gaps, and writes the tests they need when asked. -- [closing-test-gaps](skills/closing-test-gaps/SKILL.md) hunts for the bugs behind the gaps by reading code against its siblings, docs, callers and history, and probing the edges of what it must support. It confirms each candidate with a probe or a CsCheck property, and ranks them by how likely each is to be real and to be live. +- [closing-test-gaps](skills/closing-test-gaps/SKILL.md) hunts for the bugs behind the gaps by reading code against its siblings, docs, callers and history, and probing the edges of what it must support. It confirms each candidate with a probe or a CsCheck property, and ranks them by how likely each is to be real and to be live, and the harm each would do. Together they make a loop: finding-test-gaps shows what the tests miss, closing-test-gaps finds the bugs behind it, writing-cscheck-tests writes the properties that close the gaps, and finding-test-gaps checks the new properties aren't hollow. @@ -77,10 +77,11 @@ Copy the folders in `plugins/cscheck/skills/` to the folder your agent reads ski ## Where the rules come from -From published research: +From published research and case studies: - **Reading a member's tests before writing its mutants:** on Python benchmark functions, LLMs shown the tests wrote mutants that slipped past them yet were real faults 79-88% of the time, against 12-23% without them (Kiele et al., "Beyond Rule-Based Mutation Testing: Test-Aware Mutant Generation Using Large Language Models", ESEM 2026, [arXiv:2609.35841](https://arxiv.org/abs/2609.35841)). - **Flagging mutants that change nothing, and judging equivalence from the code, not its comments:** at Meta, comments the mutant generator had added misled an LLM judging which mutants were equivalent. Dropping mutants identical to the original and stripping those comments first raised its precision from 0.79 to 0.95 and its recall from 0.47 to 0.96 (Foster et al., "Mutation-Guided LLM-based Test Generation at Meta", FSE 2025, [arXiv:2501.12862](https://arxiv.org/abs/2501.12862)). `mutants.cs` warns about a mutant that only changes whitespace or comments. - **Skipping logging, metrics, tracing and sleeps:** Google's mutation testing calls such code arid and skips it, along with debugging code such as asserts (Petrović et al., "Practical Mutation Testing at Scale: A view from Google", IEEE TSE 48(10), 2022, [arXiv:2102.11378](https://arxiv.org/abs/2102.11378)). +- **Each property's own coverage, another kind of property over more time, ties and values written different ways, and the smallest settings:** from ephyra, Datadog's property-based testing library for coding agents, whose case studies report over 70 bugs in SQLite and more in PostgreSQL, Lean and other systems. Its agent guide says "a new oracle often failed on its first run; an old oracle given more time rarely did" ([STARTUP.md](https://github.com/datadog-labs/ephyra/blob/main/STARTUP.md)). Among its SQLite bugs, rows went missing when a group held both 1 and 1.0, two showed only with a length limit set below a node's size, and by our count 26 of the 76 titles name an index, a query plan or an optimisation, which a relation with and without it can check ([SQLite bugs](https://github.com/datadog-labs/ephyra/tree/main/case-studies/sqlite/bugs)). From our own trials, run by the skills' author on a private codebase and on CsCheck itself, whose reports aren't published: - **Sweeping every member:** writing mutants only where a recipe seemed to fit skipped whole members, one of them with about 50 call sites. A sweep of every member then found 25 of the 28 gaps a blind judge rated worth a test, against 17 for Stryker.NET. It ran on the three files the rules were drawn from, so this shows the rules carry over, not that they generalise. diff --git a/plugins/cscheck/plugin.json b/plugins/cscheck/plugin.json index df24e41..7bfde8a 100644 --- a/plugins/cscheck/plugin.json +++ b/plugins/cscheck/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "cscheck", - "version": "0.1.1", + "version": "0.1.2", "description": "Find what a C# project's tests miss, and write tests that find bugs.", "author": { "name": "Anthony Lloyd" diff --git a/plugins/cscheck/skills/closing-test-gaps/SKILL.md b/plugins/cscheck/skills/closing-test-gaps/SKILL.md index 25b3e8c..392c2da 100644 --- a/plugins/cscheck/skills/closing-test-gaps/SKILL.md +++ b/plugins/cscheck/skills/closing-test-gaps/SKILL.md @@ -17,16 +17,16 @@ Read the code before testing it: in the trials, reading found most of the bugs b - its history: `git log -L ,:` on a member's lines, or `git log -p -n 20 -- `, shows special cases added or removed for one member, which its siblings may need too, workarounds that may have outlived their reason, and the code it replaced. In two runs the history led to three of six bugs; - its arithmetic: an operation done in a narrower type than its result, such as a `uint` shifted before it's widened, which drops the top bit, and values in different units compared or added, such as one fit's error measured on a log scale against others measured in ticks. 3. **Probe the edges of that domain,** with a probe or as generator cases: - - the smallest sizes it accepts: empty, one and two items, where statistics and estimators often read state they haven't filled yet; + - the smallest sizes it accepts: empty, one and two items, where statistics and estimators often read state they haven't filled yet, and the smallest settings, such as a capacity, batch or page size of 1, which take paths a default of 1,000 never does; - all values equal, all zero, already sorted; - each boundary the code or its docs name, from both sides; - a sign change where the domain spans zero, including `-0.0` in floating-point code that can produce it; - an integer type's extremes and a value with the top bit set, where the code does bit arithmetic or uses unsigned types; - what the callers produce at their own edges, such as zero from a timer too coarse to measure a fast action, or the first and last day of a range. 4. **Confirm a candidate** with a probe or a property. A probe is a `probe.cs` in a scratch folder that starts with `#:project `, run with `dotnet run -c Release --file probe.cs`. Use Release, since an IDE or language server usually holds the Debug output open. A probe only reaches public types. Give it the tests' target framework, such as `#:property TargetFramework=net10.0`, since a file-based app otherwise takes the SDK's, and pass it its inputs at run time, such as from `args`, rather than as constants, since the compiler works constant expressions out itself and can get a different answer from the runtime the tests use: in one run, a probe written with constants gave the opposite answer to the tests. To check that a property would catch a bug like the one suspected, break the code on purpose with finding-test-gaps' `mutants.cs`, which compiles the change in a copy and leaves the repo alone. -5. **Rank the candidates before fixing anything,** by how likely each is to be real and to be live. For live, find every caller and read the arguments it passes, at the call rather than the whole calling method: in one run a bug needed two flags both true, and no caller passed them that way, so it couldn't happen. Where config drives the code, read the configs too, and where logs or metrics can show the effect, check them, read-only and with the user's agreement for production: in one run the logs took a bug from likely to certain. Leave a failing property failing until the bug is fixed, but don't commit it failing: mark it with the test framework's explicit or skip attribute, naming the bug, or leave it out of the commit. +5. **Rank the candidates before fixing anything,** by how likely each is to be real and to be live, and how much harm it would do. For live, find every caller and read the arguments it passes, at the call rather than the whole calling method: in one run a bug needed two flags both true, and no caller passed them that way, so it couldn't happen. Where config drives the code, read the configs too, and where logs or metrics can show the effect, check them, read-only and with the user's agreement for production: in one run the logs took a bug from likely to certain. Leave a failing property failing until the bug is fixed, but don't commit it failing: mark it with the test framework's explicit or skip attribute, naming the bug, or leave it out of the commit. 6. **After a fix, test every sibling** of the fixed code, such as the other types, formats or cases it serves: 5 of 31 bugs in one study turned up while fixing two others. ## Report -Report the candidates ranked, each with its evidence (the probe's output, or the property's shrunk case), how likely it is to be real and to be live, and the fix it needs, before fixing any. +Report the candidates ranked, each with its evidence (the probe's output, or the property's shrunk case), the result expected and where that comes from, such as a sentence in the docs, how likely it is to be real and to be live, the harm it would do, and the fix it needs, before fixing any. diff --git a/plugins/cscheck/skills/finding-test-gaps/SKILL.md b/plugins/cscheck/skills/finding-test-gaps/SKILL.md index b1ae114..a56c3df 100644 --- a/plugins/cscheck/skills/finding-test-gaps/SKILL.md +++ b/plugins/cscheck/skills/finding-test-gaps/SKILL.md @@ -42,7 +42,7 @@ dotnet run --file /scripts/uncovered.cs -- /coverage-1 [` to the first command to run one. A Microsoft.Testing.Platform project, such as one using TUnit, collects the same report from its test app: `dotnet run -c Release --project -f -- --coverage --coverage-output-format cobertura --results-directory /coverage-1`, where `-f` is needed only for several target frameworks. Collect each run into a new folder (`coverage-2` and so on), since `uncovered.cs` merges every report under the folder. Given file names, it prints each file's lines not run, its branches partly taken and its members; given none, it ranks the files; given `--since `, it shows the changed lines no test ran, in the named files if any, by file name rather than type. Read [coverage.md](references/coverage.md) for what the output means and the blind spots. - Code no test runs needs a test before a mutant can say anything about it, and so do lines no test runs inside a member that does run, such as a branch for a holiday. Say what the code does and whether a caller depends on it, and test what matters. Make the first test an oracle or a property, not one example that runs every line: in one planted case, a test that ran every line of the method still passed with the bug, which only an input of three or more consecutive dates showed. -- Here, too, write the properties that reading the code shows are worth having, such as a round trip, an oracle or an invariant, in code that runs as well as in code that doesn't, as writing-cscheck-tests says. The sweep then measures them along with the old tests, so its survivors are what they all miss. When only measuring, offer them in the report instead. +- Here, too, write the properties that reading the code shows are worth having, such as a model, a round trip or an invariant, in code that runs as well as in code that doesn't, as writing-cscheck-tests says. The sweep then measures them along with the old tests, so its survivors are what they all miss. When only measuring, offer them in the report instead. - Once those tests are written, collect coverage again into a new folder, so the sweep knows which lines still don't run. - Give each block of lines that still doesn't run one of these reasons. That today's callers don't pass an input that reaches it isn't one (step 0). - No input the code must support reaches it. Say whether it's a guard for a state that can't happen, which can stay; dead code, to offer to delete; or a bug, where a wrong condition or caller keeps out the input that should reach it, which goes with the bug candidates. @@ -73,7 +73,7 @@ Writing mutants wherever a recipe seems to fit skips whole members, even ones wi Then write by hand, for each member, mutants.md's by-hand kinds and those the repo's bug history shows: in the blind trial they were nearly a third of the survivors. Note them in the sweep table's "By hand" column, or why a member has none. 4. Mutants only change code that's there, so they can't show a missing case: a key no map has, or an enum member one path handles and a parallel path doesn't. Note these as you read, and give them a test over every enum member or key, or one comparing the parallel paths. -5. While reading, note what a property could check, such as a round trip, an oracle or an invariant, and anything that looks like a bug. Hunt the bug candidates in step 3, where the survivors can point at more. +5. While reading, note what a property could check, such as a model, a round trip or an invariant, and anything that looks like a bug. Hunt the bug candidates in step 3, where the survivors can point at more. 6. Keep the plan in the table step 1 started in `/sweep.md`: fill in each member's mutants from the list and by hand, its property (or "none"), and what was skipped and why. Note the missing cases and bug candidates under the headings below it. That way nothing is skipped silently, and no property idea is lost before the tests are written. Write it out whole when you first fill it in, then change it with small edits rather than rewriting it, since in the trials output was the largest cost of a session. ### Run diff --git a/plugins/cscheck/skills/writing-cscheck-tests/SKILL.md b/plugins/cscheck/skills/writing-cscheck-tests/SKILL.md index ae58114..4a137f2 100644 --- a/plugins/cscheck/skills/writing-cscheck-tests/SKILL.md +++ b/plugins/cscheck/skills/writing-cscheck-tests/SKILL.md @@ -13,7 +13,7 @@ CsCheck is a random testing library for .NET. You compose a generator, `Gen`, | To check | Use | Read | |---|---|---| -| A rule over many inputs: a round trip, an oracle, an invariant | `gen.Sample(...)` | this file | +| A rule over many inputs: a model, a metamorphic relation, a round trip, an invariant | `gen.Sample(...)` | this file | | `Equals`, `GetHashCode` and `IEquatable` agree, and each field counts or doesn't on purpose | `gen.Equality(...)` | this file | | A stateful type against a simple model of it, such as a `HashSet` | `SampleModelBased` | [stateful.md](references/stateful.md) | | Two ways of reaching one result agree | `SampleMetamorphic` | [stateful.md](references/stateful.md) | @@ -58,29 +58,49 @@ What makes a generator find bugs: - **Give usable inputs.** Build them so every sample tests something, such as valid dates in the range the code handles rather than any `DateTime`; then the code rejecting one is a failure. Where filtering is simpler than building, use `Where`: it draws again, and after `CsCheck_WhereLimit` (100) rejections in a row the test fails with "The generator threw." and the inner exception "Failing Where max count", so a generator that rarely gives usable inputs fails loudly. - **Never skip inside the check**, such as an early `return true` for inputs the code rejects: a skipped sample counts as a pass. One property skipped nearly all of its random dates like that, and the skip hid a bug in the fifth week of a month. Don't check less for some inputs either: a property that checked only the median below 5 items, with `if (a.Length < 5) return `, hid a bug in the quartiles at 1 and 2 items. Where the rule really differs for some inputs, state it for them, or give them a property of their own. - **Generate the edges on purpose,** since a uniform range almost never hits them: `Gen.Frequency((1, Gen.OneOf(a, b)), (9, Gen.Int[a, b]))` gives the ends a tenth of the time. An offset of exactly 0 was 1 value in 36,001 of one generator, and a bug at 0 survived until it was `Gen.OneOf(Gen.Const(0), Gen.Int[0, 36_000])`. Making half of the generated ranges 1-10 days long found two bugs that longer ranges never hit. +- **Generate ties, and one value written different ways.** Two values drawn on their own are almost never equal, so make the second a copy of the first some of the time: `Gen.Select(Gen.Int, Gen.Int, Gen.Int[0, 3], (a, b, c) => (a, c == 0 ? a : b))` ties a quarter of the time. Keys, timestamps and anything sorted, matched or deduplicated need ties. Equal values can differ too: `1m` and `1.00m` are equal but print as `1` and `1.00`, `-0.0` equals `0.0` but prints as `-0`, `==` on two `DateTime`s ignores their `Kind`, two `DateTimeOffset`s at different offsets can be one instant, and strings can be equal under the comparer used. Code that groups, caches, deduplicates or keys on such values should treat them alike: SQLite dropped rows when a group held both 1 and 1.0. - **Don't filter away a region.** A `Where`, or an implication, that drops a whole region hollows a property as a skip does: a `Where` that kept business hours dropped every weekend, which is where the bug was. Generate such regions on purpose: weekends, holidays, the hours either side of a cut-off, and time zones with and without daylight saving. Pass the code a `TimeZoneInfo` or a `TimeProvider` rather than relying on the machine's zone. - **Generate what production passes, and the rest of the domain.** Find how the callers build the input and the values every caller passes, and make sure the generator gives those, since one built from the types alone can miss them. Don't stop there: a failure on input the code must support but no caller makes yet, such as a weekend date where today's callers only pass business days, is a bug too, only a less urgent one. - **For an `IEnumerable` parameter, generate lazy sequences too,** not only arrays: a `Count` fast path answers arrays and lists, so its bug only shows on a sequence that can be enumerated only once. Where the code returns lazy sequences of sequences, enumerate them in the order the real caller does, since some only work when each inner one is read before the next. - **For a wire format such as JSON, build both sides' inputs through their real serialisers,** not hand-written JSON, fixtures or comments. In one planted case the fixtures lacked a field one side adds, which was the bug. - **Generate every shape the format's spec or doc comment allows,** not only those in the sample data: each fraction length from 0 to 9 digits, and both `Z` and offsets. A timestamp parser threw for the 1-6 digits its doc comment allows, because every sample payload had 9, and an RFC 3339 parser rejected the 8-9 digits that Go and Java write. - **Give a parser malformed input too:** valid input with junk or a stray delimiter after it should be rejected. Parser combinators such as Pidgin stop where the grammar does unless it ends by requiring the end of input, so a template with a stray `}` after it parsed silently, as if the `}` weren't there. -- **Look at what a generator gives** by running it once through the classify overload, `gen.Sample(x => x.Kind.ToString(), writeLine)`, whose string is a label, not a failure message: it writes how often each label came up, even when the test fails. A `/` in a label nests rows with subtotals, and a null label counts as `Null Count`. `logger: Logging.CreateTycheLogger()` writes the samples for Tyche, a viewer for property-based testing data, instead; dispose it when done. +- **Look at what a generator gives** by running it once through the classify overload, `gen.Sample(x => x.Kind.ToString(), writeLine)`, whose string is a label, not a failure message: it writes how often each label came up, even when the test fails. Label the shapes the code treats differently, such as empty, one item, all equal or on a boundary: a shape in 1% of samples is missed by over a third of 100-iteration runs, so give it more weight. A `/` in a label nests rows with subtotals, and a null label counts as `Null Count`. `logger: Logging.CreateTycheLogger()` writes the samples for Tyche, a viewer for property-based testing data, instead; dispose it when done. - **Keep each sample cheap,** since a longer run is how you trust a pass. Moq's `Mock.Of(x => x.P == value)` costs about 1 ms a call, dozens of times slower than `new Mock()` with `Setup(x => x.P).Returns(value)`. ## Properties that find bugs -Write them against the public API. Three kinds find bugs: -- **A round trip**: format then parse, serialise then deserialise, an id to its display name and back. -- **An oracle**: a simple version to compare with, such as counting business days one at a time; a rule the docs state; or, for a port of another library, the original's definition. Compare a port with its original first: that found one bug before any test ran, and explained three more within a minute of their shrunk cases. -- **An invariant**: a schedule's dates increase from start to end, a sorted output stays sorted, or a value that should change smoothly, such as one interpolated between dates, has no jumps. The smoothness one found two bugs the round trips couldn't see. - -Idempotency (normalising twice gives what normalising once does) and commutativity (independent updates in either order give the same result) are cheap to check too. Prefer a generator and `Sample` to a loop over hand-picked values: it covers more, and shrinks a failure to a simple case. +Write them against the public API, and take what each one checks from outside the code under test: a simpler version of it, its docs, a standard it follows, another system's output, or a rule all code must keep, such as not throwing on valid input. What the code returns today isn't a source, since a property built on it locks its bugs in. + +- **A model** is the most powerful property: a simple, obviously correct version of the code to compare every output with, so any wrong answer fails it, not only one that breaks a rule. Write it the slow, plain way, and not with the code's own helpers, or it shares their bugs: + - counting business days one at a time, for code that works the count out in one step; + - brute force over a small input, such as trying every pair or every subset, for an optimised search; + - the formula in the docs or a standard, written out plainly, for code that computes it a faster way; + - `BigInteger` arithmetic, for integer code with tricks to avoid overflow, such as a midpoint or the high half of a multiply; + - the old version, for a rewrite or an optimisation, kept in the tests until the new one is trusted; + - the original's definition, for a port of another library. Compare a port with its original first: that found one bug before any test ran, and explained three more within a minute of their shrunk cases; + - a `List`, `HashSet` or `Dictionary`, for a custom collection, with `SampleModelBased` ([stateful.md](references/stateful.md)). +- **A metamorphic relation**, where no model can be found: run the code on related inputs and check their outputs relate as they must, which needs no expected value: + - with and without a fast path, a cache or parallelism, and an incremental update against recomputing from scratch; + - the input in another order, where order shouldn't matter; + - the input split in two, against the two parts' results combined, such as for a sum or a count; + - the input scaled, such as every amount doubled, which should double a total; + - an item added that can't change the answer, such as one with no weight, or one a filter drops; + - more input, for a result that can only grow, such as a count or a maximum; + - idempotency, where normalising twice gives what normalising once does, and commutativity, where independent updates give the same result in either order. + + `SampleMetamorphic` ([stateful.md](references/stateful.md)) checks two ways of changing a stateful type from one start. +- **A round trip**: format then parse, serialise then deserialise, encode then decode, compress then decompress, an id to its display name and back. +- **An invariant**: a sort's output is in order and holds the input's items, rounded shares still sum to the total, a cache never holds more than its capacity, a schedule's dates increase from start to end, an interpolated value lies between its neighbours, and a value that should change smoothly, such as one interpolated between dates, has no jumps. The smoothness one found two bugs the round trips couldn't see. +- **No unexpected exception**: for every input the code must support, it returns, or throws only what its docs name, so a `TryParse` never throws and a second `Dispose` does nothing. It checks the least, but costs the least, so give one to any code that takes input from outside. + +Prefer a generator and `Sample` to a loop over hand-picked values: it covers more, and shrinks a failure to a simple case. Then: -- A round trip, or a property that compares a method with itself, can't see a bug both sides share, such as a holiday rule both directions call, or a formula that's wrong the same way both times. That needs an oracle, an invariant or an example test. +- A round trip or a metamorphic relation compares the code with itself, so it can't see a bug both sides share, such as a holiday rule both directions call, or a formula that's wrong the same way both times. That needs a model, an invariant or an example test. - Compare canonical values, such as a date or a regenerated output, not strings, when inputs have old spellings. - To test that a distribution is right, such as a shuffle being uniform, count outcomes into buckets and call `Check.ChiSquared(expected, actual)`, which needs every bucket to expect more than 5. -- A new property that fails has probably found a bug. Check the shrunk case against the code and its docs before changing the property, and never weaken the generator or the check to make it pass. +- A new property that fails has probably found a bug. Check the shrunk case against the code and its docs before changing the property, and never weaken the generator or the check to make it pass. If it fails on most inputs of code already in use, though, suspect the property first, since a bug that common would usually have been noticed. `Sample` stops at the first failure, so see the rate with the classify overload, labelling each input by whether it holds. ### Equality @@ -102,7 +122,7 @@ genOrder.Equality(f => f - **Never assert inside `Sample`.** NUnit records every failing `Assert.That`, which buries the shrunk case under dozens of failures. An exception the code throws is fine: CsCheck catches it and shrinks it like a false, and keeps it as the `InnerException`. Since CsCheck 5 its text isn't copied into the message. - A failure's message is a seed line with `(N shrinks, M skipped, K total)`, then the shrunk input, cut at 5,000 characters, with an array or list of more than 12 items shown as `L=n [first 6 ... last 6]` and other collections in full up to 999 items: pass `print:` to see more. `The generator threw.` means the generator failed, not the check. `skipped` counts shrink candidates that weren't smaller than the failure found so far, so they never ran: it isn't errors or `Where`-filtered inputs, and a large count is no problem. -- **Shrinking spends the same budget:** after the first failure, the remaining iterations or seconds only try smaller cases, so a failing run of the default 100 iterations barely shrinks. To shrink further, rerun with the printed seed as `seed:` and a larger `iter` or `time`; the seed's case runs first. +- **Shrinking spends the same budget:** after the first failure, the remaining iterations or seconds only try smaller cases, so a failing run of the default 100 iterations barely shrinks. To shrink further, rerun with the printed seed as `seed:` and a larger `iter` or `time`; the seed's case runs first. If that rerun passes, the failure depended on more than its input, such as the clock or state shared between samples or threads; `threads: 1` shows whether threads are the cause. - **CsCheck reports only the smallest failure.** To find the other kinds, leave the kind just found out of the generator with a `Where` on its input shape, rerun, and repeat until the property passes: one property showed three bugs in three runs. Then take the `Where` out, so the test still fails on the first kind. Where the domain is small enough to list, such as every weekday for a few years, a probe that loops over all of it once shows every kind of failure with its count in one run. - **Once a bug is fixed, keep its shrunk case as a plain example test.** A seed reproduces it only while the generator and CsCheck stay the same. @@ -112,9 +132,12 @@ One passing run isn't proof, since every run draws new inputs. Before trusting a - Run it longer in Release, filtered to the test: `dotnet test -c Release -e CsCheck_Time=60 --filter `, or `time: 60` while you try it; a `SampleFaults` test then takes (faults + 1) times as long. Or repeat the test. One property passed several runs before it found its bug. A seed only reproduces a failure; it adds no coverage. - Then remove the `time:` or `iter:` you added, as with `writeLine:`, so the test runs at the suite's default. If 100 iterations can miss a case, such as the one failing name among a few dozen, make each iteration check every name rather than raising `iter`. - Break the code on purpose, with one small change the property should catch, and check it fails within a long run. If it passes, the property is hollow. finding-test-gaps' `mutants.cs` does this without editing the repo; its `--only` rerun of a sweep's survivors is this check. +- See what it reaches: collect coverage as finding-test-gaps' step 1 does, with only the new property running and `CsCheck_Time` set, into a folder of its own, and read what `uncovered.cs` shows not run or partly taken in the members the property calls. Each is a kind of input the generator never makes, or dead code: widen the generator for each, one at a time, and measure again. The whole suite's coverage can't show this, since an example test that runs a line hides that the property never does. - `Sample` runs on every logical CPU at once, so the check must be thread-safe: make what it changes inside it or in the generator, with `Gen.Const(() => new ...)`, or pass `threads: 1`. - `iter: 0` or `time: 0` passed as arguments runs nothing and passes: only the settings are validated, not the arguments. +Once a property is trusted, another kind of property on the same code, such as an invariant beside a round trip, finds more bugs than running the first one longer: a new property often fails on its first run, where an old one given more time rarely does. + ## Replacing example tests A trusted property can make the example tests of the same code redundant. To find which: