/cscheck:writing-cscheck-testsfrom cscheck
Writes CsCheck property-based tests for .NET code that find bugs rather than just pass. Covers Sample, Equality, SampleModelBased, SampleMetamorphic, SampleParallel, Spec, Faster, causal profiling, Single and Check.Hash.
Ships in cscheck. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
CsCheck is a random testing library for .NET. You compose a generator, Gen<T>, and end it with a check such as Sample. There are no Arb classes and you never write a shrinker: a failure shrinks to a simpler case by itself, reproducibly from a seed. CsCheck works with any test framework or none, since a check fails by throwing CsCheckException; in Sample, the function you pass can return false instead.
| To check | Use | Read |
|---|---|---|
| A rule over many inputs: a round trip, an oracle, an invariant | gen.Sample(...) | this file |
Equals, GetHashCode and IEquatable<T> 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 |
| Two ways of reaching one result agree | SampleMetamorphic | stateful.md |
| A type is safe to use from several threads | SampleParallel | stateful.md |
| A protocol or rule book, proved over every reachable state, and code that conforms to it | Spec with Exhaustive, Faults, Conform, ConformExhaustive | spec.md |
| One implementation is faster than another | Faster | performance.md |
| Which part of a concurrent program to speed up | Causal.Profile | performance.md |
| Results don't change from version to version | Single and Check.Hash | regression.md |
Read the file for the check before writing one: each has rules the API doesn't make obvious.
using CsCheck, and follow them, reading what their generators make. CsCheck's own Tests project on GitHub is its example collection.dotnet add package CsCheck. Under central package management the PackageReference has no version, which goes in Directory.Packages.props. A language server can report CS0246 for CsCheck's types until it reloads the project, so trust the build.using CsCheck; even where you'd write names in full: Array, List, HashSet and friends are extension properties, so CsCheck.Gen.Int.Array without the using is error CS1061.writeLine: while writing a test: NUnit's TestContext.Progress.WriteLine, xUnit's ITestOutputHelper.WriteLine, TUnit's s => TestContext.Current?.OutputWriter.WriteLine(s) (a lambda, since ?. can't make a method group), MSTest's TestContext.WriteLine, or Console.WriteLine. With it a pass writes Passed N iterations. Remove it afterwards, except where it carries the result: the classify overload, classify: tables, a passing Faster and raiseexception: false.SampleAsync takes a Func<T, Task<bool>> or Func<T, Task>, with threads as the number of concurrent async workers. SampleModelBasedAsync and FasterAsync are the async forms of theirs.Compose them with LINQ: Select, SelectMany, Where and query syntax.
Gen.Int, Gen.Long, Gen.Short, Gen.Byte, Gen.UInt, Gen.ULong, Gen.Int128, Gen.Double, Gen.Float, Gen.Decimal, Gen.Bool, Gen.Char, Gen.String, Gen.Guid, Gen.DateTime, Gen.DateOnly, Gen.TimeOnly, Gen.DateTimeOffset, Gen.TimeSpan, Gen.Enum<T>().Gen.Int[0, 9], Gen.Long[start, finish], Gen.DateTime[start, finish], Gen.Char['a', 'z'], and Gen.Char["abc"] or Gen.String["abc"] to draw from the characters given. Sub-ranges: Gen.Int.Positive, Gen.Int.NonNegative, Gen.Int.Uniform, Gen.Double.Unit, Gen.Float.Unit, Gen.Char.AlphaNumeric, Gen.DateTime.Utc, Gen.DateTime.Local.gen.Array, gen.List, gen.HashSet, gen.ArrayUnique, Gen.Dictionary(keyGen, valueGen) and Gen.SortedDictionary(...). Their length is uniform from 0 to 127, or 1 to 128 with .Nonempty; set it with [n], [min, max] or [Gen<int>]. The length shrinks first. gen.Array2D draws each dimension from 0 to 127, and takes [a, b] for a fixed a by b, or [Gen<int>, Gen<int>]. Gen.Shuffle(array) permutes the array it's given, and Gen.Shuffle(array, length) or (array, min, max) picks that many of its elements.HashSet, ArrayUnique, Dictionary and SortedDictionary need that many distinct elements or keys: after 1,000 duplicates in a row the test fails with "The generator threw." So Gen.Int[0, 9].HashSet or Gen.Enum<T>().HashSet almost always fails; give a small domain a small length, such as Gen.Int[0, 9].HashSet[0, 5].Gen.Select(g1, g2, ...) gives a tuple, or a selector's result; Gen.SelectMany; gen.Where(...); Gen.OneOf(...) of values or generators; Gen.Frequency((weight, value or generator), ...); gen.Nullable() for a value type and gen.Null() for a class, both null 20% of the time unless given another fraction, such as gen.Null(0.1); Gen.Recursive<T>((depth, self) => ...).Gen.Select takes up to 16 generators with a selector, or 8 without one. For more, nest them, Gen.Select(Gen.Select(a, b, c, d), Gen.Select(e, f, g, h), (x, y) => ...), which shrinks the same as one flat Select. Query syntax (from a in ga from b in gb select ...) has no limit but shrinks the earlier values first, so keep it for values that depend on earlier ones.Gen.Const(x) hands out the same instance every time; Gen.Const(() => new X()) makes a new one per sample.OneOf and Frequency shrink toward their earlier arguments, so put the simplest case first, such as the leaf before the node in a Recursive. Gen.Recursive doesn't limit depth: return the leaf generator once the depth it passes reaches a maximum.What the defaults don't give you:
Gen.Short, Gen.Int, Gen.UInt, Gen.Long, Gen.ULong, Gen.Int128 and Gen.UInt128 favour small values, give their extremes on about 1 draw in 64 (MaxValue for the unsigned ones, where 0 is common anyway), and shrink toward 0. Gen.Byte, Gen.SByte and Gen.UShort are uniform, and so is a range such as Gen.Int[a, b], with no extra weight on its ends.Gen.Double covers -1e50 to 1e50 (Gen.Float and Gen.Decimal 1e25), mixing integers, simple fractions, numbers of up to four significant digits at every scale, and uniform values, but never NaN or infinity. Gen.Double.Special and Gen.Float.Special give NaN, the infinities, the extremes, Epsilon and small integers 1 time in 16, and raw bit patterns otherwise.Gen.Char and Gen.String only make printable ASCII, ' ' to '~'. For other text use Gen.Char[char.MinValue, char.MaxValue], lone surrogates included, or Gen.String[Gen.Char[...], min, max].Gen.DateTime is uniform over every tick from year 1 to 9999, with Kind unspecified, so nearly every date is centuries from today. Gen.DateTimeOffset covers 1800 to 2200, with any whole-minute offset up to 14 hours.What makes a generator find bugs:
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.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 <a weaker check>, 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.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.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.IEnumerable<T> 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.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.} after it parsed silently, as if the } weren't there.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.Mock.Of<T>(x => x.P == value) costs about 1 ms a call, dozens of times slower than new Mock<T>() with Setup(x => x.P).Returns(value).Write them against the public API. Three kinds find bugs:
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.
Then:
Check.ChiSquared(expected, actual), which needs every bucket to expect more than 5.Equality contracts break more often than they look: in one codebase an Equals and GetHashCode ignored a field, a CompareTo gave 0 for unequal values, and hash ^ x?.GetHashCode() ?? 0 bound as (hash ^ x?.GetHashCode()) ?? 0, so a null reset the hash. gen.Equality() checks Equals both ways, IEquatable<T> and GetHashCode agree, on equal clones and on random pairs; gen.Equality(comparer) checks an IEqualityComparer<T>. Declare the fields to check that each one counts, or doesn't, on purpose:
genOrder.Equality(f => f
.Compared((o, v) => o with { Id = v }, Gen.Int)
.Ignored((o, v) => o with { CachedTotal = v }, Gen.Decimal));
name:, in the inner exception. An Action<T, V> setter works for a mutable type.Math.Max(A, B), fits neither, and leaving it out fails too, since the two instances still differ in it: hold such fields fixed in the generator, or check that type with plain gen.Equality()..Case<TArm>(...) covers a hierarchy of subtypes, and C# unions on net11.CompareTo has no check of its own: write a Sample that Sign(a.CompareTo(b)) == -Sign(b.CompareTo(a)) and that it's 0 exactly when the values are equal, and that it's 0 on gen.Clone() pairs and transitive on triples.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.(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.seed: and a larger iter or time; the seed's case runs first.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.One passing run isn't proof, since every run draws new inputs. Before trusting a new property:
dotnet test -c Release -e CsCheck_Time=60 --filter <name>, 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.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.mutants.cs does this without editing the repo; its --only rerun of a sweep's survivors is this check.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.A trusted property can make the example tests of the same code redundant. To find which:
candidates.cs, give each one the property's name as its expect, and run them with its mutants.cs. A mutant that other tests kill and the property doesn't is reported as by <tests>, not <property> as expected. Rerun those with --only, run longer as finding-test-gaps' step 3 says, since a property can miss a mutant in one run and kill it in the next. The tests that still kill one the property misses check something it doesn't.Optional parameters on the checks: iter (default 100), time (seconds), seed, threads (the logical CPUs, but 1 for Exhaustive and Faults; below 1 means the default) and print. Faster, SampleModelBased, SampleMetamorphic, SampleParallel and Spec add their own, such as equal.
Environment variables set the defaults: CsCheck_Iter, CsCheck_Time, CsCheck_Seed, CsCheck_Threads, CsCheck_Timeout, CsCheck_Sigma, CsCheck_Replay, CsCheck_AllocAll, CsCheck_WarmUp, CsCheck_Ulps (default 4: Check.Print shows a double within that many ulps as a shorter number), CsCheck_WhereLimit (100) and CsCheck_SingleLimit (1,000,000).
time: wins, then CsCheck_Time, then an explicit iter:, then CsCheck_Iter, so CsCheck_Time lengthens every test that doesn't pass time:. CsCheck_Seed applies to every test, so pair it with a test filter.Check is first used; set Check.Iter, Check.Time and the others in code to change them during a run. A bad value fails every CsCheck call with a TypeInitializationException. Booleans accept true/false, yes/no, y/n and 1/0.Code written for 4.x, including most CsCheck code a model has seen, needs these changes:
Gen.OneOfConst and Gen.FrequencyConst are now overloads of Gen.OneOf and Gen.Frequency.Gen.UInt4 to Gen.UInt2048 are gone: Gen.UInt[0, N - 1] gives the same values. Gen.UInt128 now generates UInt128, so a cast such as (int)i still compiles but means something else.Check.ModelEqual is gone: models compare with Check.Equal, so bags count duplicates.Dbg, IRegression, RegressionExtensions and HashHelper are gone, and Hash.Add takes collections. ILogger is ISampleLogger, and Logging.CreateLogger and Logging.LogProcessor are gone: use Logging.CreateTycheLogger().MedianEstimator, Classifier, Timer and ThrowHelper are internal, as are the Hash and MedianEstimate constructors.GenOperationAsync<T> is gone: SampleParallel operations must be synchronous.Exhaustive, Sample and Conform return SpecReport<S> instead of SpecReport, as does the new ConformExhaustive. Exhaustive takes writeLine first, and AtMost<T> takes times after over. SampleFaults reports FaultOutcome.NotFound, not NotDetected, for a fault it misses.Check.Hash expected values change for Gen.Decimal, Gen.Double and Gen.Float, and for the integer generators that now give their extremes on 1 draw in 64.What SKILL.md sets; muted values are Claude Code's defaults
3 skills in this plugin
/closing-test-gapsHunts for bugs in C# and .NET code by reading it against what should agree with it (its siblings, docs, callers, history and the code it was ported from), probing the edges of what it must support, and confirming each candidate with a small probe or a CsCheck property, ranked by how likely each is to be real and to be live. Use when asked to find bugs or to check that code is right, e.g. "find the bugs in this parser", "is this calendar code right", "what could go wrong in this class", "check this for edge cases". To measure what the tests miss, use finding-test-gaps; to write the tests, writing-cscheck-tests./finding-test-gapsMeasures what C# unit tests don't check, with any test framework, CsCheck or not: code coverage for code no test runs, and a sweep of hand-picked mutants, compiled and run without editing the repo, for code the tests run but don't check. Use when asked how good the tests are or what they miss, e.g. "how good are the tests for LruCache", "what's untested in this project", "mutation test this method", "what do the tests on my branch miss", "do these tests actually check anything". It takes a test project, a source file, types or members, or a branch to compare with. To hunt for the bugs themselves, use closing-test-gaps, and to write the tests, writing-cscheck-tests.npx claudepluginhub anthonylloyd/cscheck --plugin cscheckOther plugins' skills for the same job