nullean.entities · .net

Executable specificationsfor .NET.

Declare your domain's rules once. Validate, generate, test, monitor and document from them.

dotnet add package Nullean.Entities
nuget ↗
dotnet add package Nullean.Entities.CsCheck
nuget ↗

The core has no dependencies. Add CsCheck to a test project for the generated tests.

the five-minute film · recorded with reel

the whole idea, in code

Three rules, named. One line tests them.

OrderConstraints.csthree rules, named
[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);
}
OrderTests.csthe whole test
[Test]
public Task The_good_order_passes_every_axis() =>
    AutoTest.For(OrderConstraints.Instance, Orders).RunAsync();

the gap

A type system can only encode so much.

decimal Total compiles at -5. A record has a shape, not rules.

  1. Can the total ever be negative?
  2. Is cancelling twice the same as once?
  3. Does the version only go up?
Order.csthe usual answer
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
}
  • The intent. An if says what, never why.
  • A list. Nobody can ask which rules an Order has.
  • A test. A rule inside a constructor cannot be tested on its own.
  • Reuse. The API, the options and the docs cannot read it.

one declaration

Rules as first-class metadata.

A rule is a value with a name and a sentence. Write it once; everything else reads it.

TotalNeverNegative
01

Validates where a value is built

A factory returns a Result<T>, not an exception three calls later.

Rules.Validated(order)
02

Answers the API

A bad request becomes ProblemDetails, keyed by the field that broke.

.ValidateConstraints()
03

Checks options at start-up

Bad configuration fails on boot, worded Member: message.

.ValidateConstraints(ServerRules)
04

Tests itself

CsCheck generates the cases from the rules. You write no test code for them.

AutoTest.For(...)
05

Draws the diagram

A state machine prints its Mermaid, so the docs show what the code enforces.

stateDiagram-v2
06

Briefs your agent

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

Model your world.

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.

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)

Time

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))

State machines

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)))

Behaviour of operations

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")

Values that cannot be built invalid

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 ?? ""));

The outside world

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

Built on CsCheck.

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.

Entities on top

First-class propertiesthe rules you declare, named and discoverable
Nine axeseach rule's shape says which questions to ask
AutoTestfinds the operations and runs every axis

CsCheck the engine

GeneratorsGen<T>, composed
Shrinkingto the smallest failing case
Seedsreplay exactly that case
Model-basedand parallel testing

Your rules are the properties

Each 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.

  • total-never-negativeAlways01 invariant
  • cancel-is-repeatableIdempotent02 idempotency
  • version-never-goes-backMonotonic03 monotonicity
  • label-ignores-line-orderOrderIndependent08 confluence
  • confirmed-orders-have-linesWhen · Requires01 invariant, guarded

AutoTest finds the operations AddLine Confirm Ship Cancel · every public method that returns an Order

the tests you did not write

One line. Nine axes.

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();
The nine questions and the bug each catches
#AxisQuestionThe bug it catchesAnimation
1Invariant an operation that lets a bad value in
2Idempotency a retry that changes state twice 12
3Monotonicity an older result overwriting a newer one
4Conservation totals that drift ≠total
5Absence a cancelled order that still ships CancelledShipped
6Temporal a promise missed by one unlucky gap deadline
7Liveness the endless spinner
8Confluence two rebuilds publishing different results a babb aba≠
9Vacancy a green test that checked nothing ✓ greenrulenever reached

when it breaks

A failure you can read. So can your agent.

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.

Monotonicity failedquestion 3
generated value

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")
  1. 1 A rule fails and prints the report.
  2. 2 The agent reads the rule, the operation and the law.
  3. 3 The agent fixes the code.
  4. 4 .Seed("7ub38ErvzD2a") replays the exact case.

start here

Write the rule once.

dotnet add package Nullean.Entities
nuget ↗
dotnet add package Nullean.Entities.CsCheck
nuget ↗

The core has no dependencies. Add CsCheck to a test project for the generated tests.