Relations
Unique, References, Acyclic, NoChains: keys and trees, no database.
✓ every url is uniqueRule broken unique-page-urls: '/install' appears 2 times.
Constraints<DocumentationSet>
.Unique(d => d.Pages, p => p.Url)
nullean.entities · .net
Declare your domain's rules once. Validate, generate, test, monitor and document from them.
the five-minute film · recorded with reel
the whole idea, in code
[Constraints<Order>]
public static partial class OrderConstraints
{
public static readonly Constraint<Order> TotalNeverNegative =
Constraints<Order>.Always(
o => o.Total >= 0, "An order total is never negative.");
public static readonly Constraint<Order> CancelIsRepeatable =
Constraints<Order>.Idempotent(o => o.Cancel());
public static readonly Constraint<Order> VersionNeverGoesBack =
Constraints<Order>.Monotonic(
o => o.Version, MonotonicDirection.NonDecreasing);
}
[Test]
public Task The_good_order_passes_every_axis() =>
AutoTest.For(OrderConstraints.Instance, Orders).RunAsync();
the gap
decimal Total compiles at -5. A record has a shape, not rules.
public class Order
{
public Order(decimal total, int version)
{
if (total < 0) throw new ArgumentException(nameof(total));
Total = total; _version = version;
}
public decimal Total { get; }
public int Version
{
get => _version;
set => _version = value < _version
? throw new InvalidOperationException()
: value;
}
private int _version;
// and cancelling twice? there is nowhere to write that down
}
one declaration
A rule is a value with a name and a sentence. Write it once; everything else reads it.
A factory returns a Result<T>, not an exception three calls later.
Rules.Validated(order)
A bad request becomes ProblemDetails, keyed by the field that broke.
.ValidateConstraints()
Bad configuration fails on boot, worded Member: message.
.ValidateConstraints(ServerRules)
CsCheck generates the cases from the rules. You write no test code for them.
AutoTest.For(...)
A state machine prints its Mermaid, so the docs show what the code enforces.
stateDiagram-v2
Every rule has a name and a sentence an agent reads before it changes the code. The generated tests check what it wrote.
OrderConstraints.All
beyond one value
Rules reach past a single field: across rows, over time, through a lifecycle, out to the file system. Break each one to see what the rule says.
Unique, References, Acyclic, NoChains: keys and trees, no database.
✓ every url is uniqueRule broken unique-page-urls: '/install' appears 2 times.
Constraints<DocumentationSet>
.Unique(d => d.Pages, p => p.Url)
What must follow what within a deadline, and what must Never happen after something else.
✓ answered within the deadlineTemporal failed No matching event within 00:00:30 after Sent
After<ClientEvent.Sent>()
.Then<ClientEvent.Succeeded, ClientEvent.GaveUp>(
/* matched by RequestId */)
.Within(TimeSpan.FromSeconds(30))
States as case types, checked when the machine is defined. Mermaid in, Mermaid out.
✓ only the legal movesRejected 'Ship' is not a transition out of Draft (permitted: Place)
StateMachine<OrderState>.Define(m => m
.Initial<OrderState.Draft>(s => s
.On("Place")
.To<OrderState.Placed>(_ => new OrderState.Placed(0)))
Idempotent, Monotonic, Conserves, OrderIndependent: what a step may do.
✓ 16 before, 16 afterConservation failed A transfer cannot create or destroy money: was 16, became 15
Constraints<Transfer>.Conserves(
t => t.From.Balance + t.To.Balance,
"A transfer cannot create or destroy money")
Check in a factory, not a constructor, and hand back the reasons.
✓ a value, never an invalid oneReasons The amount must be greater than zero · The amount has at most two decimals · The currency is a three-letter code like EUR
public static Result<Money> Create(
decimal amount, string? currency) =>
Rules.Validated(new Money(amount, currency ?? ""));
Paths a model holds must exist, and stay inside the folder they belong to.
✓ every path exists, inside /docsRule broken '/docs/setup.md' does not exist.
Files<Docset>.Exist(d => d.Pages)
Files<Docset>.StayInside(
d => d.Root, d => d.Pages.Concat(d.Images))
the engine underneath
CsCheck is an excellent property-based testing library for .NET: fast, and it finds the smallest case that still fails. Entities builds on it, and adds what a test can't know without your rules.
Gen<T>, composedEach rule is a named value with a shape. The shape tells the tests what to ask, so nobody writes the property by hand. [Constraints<Order>] gathers them into OrderConstraints.All: add a rule, and it is found.
AutoTest finds the operations AddLine Confirm Ship Cancel · every public method that returns an Order
the tests you did not write
Most tests check one example. This line asks every rule you declared these nine questions, each one a kind of production bug. Hover, focus or tap a row to watch it happen; tap one to read its real failure.
await AutoTest.For(OrderConstraints.Instance, Orders).RunAsync();
| # | Axis | Question | The bug it catches | Animation |
|---|---|---|---|---|
| 1 | Invariant | an operation that lets a bad value in | ||
| 2 | Idempotency | a retry that changes state twice | ||
| 3 | Monotonicity | an older result overwriting a newer one | ||
| 4 | Conservation | totals that drift | ||
| 5 | Absence | a cancelled order that still ships | ||
| 6 | Temporal | a promise missed by one unlucky gap | ||
| 7 | Liveness | the endless spinner | ||
| 8 | Confluence | two rebuilds publishing different results | ||
| 9 | Vacancy | a green test that checked nothing |
Invariant failed.
Rule brokentotal-never-negative: An order total is never negative.
Smallest case found, after 1 shrink. .Seed("9Rmf9J10O1j6")
Idempotency failed.
Rule brokencancel-is-repeatable: doing it twice is not the same as doing it once.
This is the smallest case: nothing smaller failed. .Seed("0N0XIzNsQ0O2")
Monotonicity failed.
Rule brokenversion-never-goes-back: Expected NonDecreasing but moved from 1 to 0.
Smallest case found, after 4 shrinks. .Seed("7ub38ErvzD2a")
Conservation failed.
Rule brokenmoney-is-conserved did not conserve its value (was 16, became 15).
Smallest case found, after 2 shrinks. .Seed("db7hMFd37Kd8")
Absence failed.
Rule brokencancelled-orders-are-never-shipped
What happenedCancelled, then Shipped
Smallest case found, after 4 shrinks. .Seed("bJG2B9wvdYq4")
Temporal failed.
Rule brokenconfirmed-ships-within-a-minute
What happenedNo matching event within 00:01:00 after Confirmed
Smallest case found, after 5 shrinks. .Seed("0i1vmP3ChLc5")
Liveness failed.
Rule brokenevery-confirmed-order-ships
What happened1 instance(s) never reached the target event: order
Smallest case found, after 1 shrink. .Seed("9-RUpSdWxJb3")
Confluence failed.
Rule brokenfirst-sku-is-the-label: the result depends on the order the items are listed in.
Smallest case found, after 2 shrinks. .Seed("dsRrQRlF6jV2")
Vacancy: the test passed without proving anything.
Ruleconfirmed-orders-have-lines
Not exercisedits guard was never true for the 200 generated values, so the rule held without being exercised.
when it breaks
A failure names the rule, the operation and the value it started from, states the law and what breaking it costs, and arrives shrunk to the smallest case with a seed that replays it.
Illustrative path. The report states only the first value shape and the smallest case; ▒ stands for generated data.
Monotonicity failed.Rule broken version-never-goes-back: Expected NonDecreasing but moved from 1 to 0.Operation Reset()Started from Order { Lines = [], Status = Cancelled, Version = 1, Total = 0, Label = "" }Produced Order { Lines = [], Status = Cancelled, Version = 0, Total = 0, Label = "" }Law No operation moves a value that may only go one way in the other direction.Consequence An older result overwrites a newer one, a counter goes back or a timestamp regresses, without anything saying so.Smallest case found, after 4 shrinks. To run this case again: .Seed("7ub38ErvzD2a")