Skip to content

Stateful testing

A property draws one input and checks one thing. Much code is a thing you call many times: a bank, a cache, a queue. Its bugs are in the order of the calls. A stateful test names the steps that can be taken, draws runs of them in any order, and checks what must hold after every one, its invariants. When one breaks, proptastic shrinks the run to the fewest, simplest steps that still break it, and gives you a line that replays them.

This guide tests a bank with one bug that takes three steps in the right order to find: a deposit, a transfer out, then a withdrawal. Its withdrawal checks what was ever paid into the account, not what’s in it:

/**
* A bank whose withdrawal checks what was ever paid in, not what's
* there: after a transfer out, a withdrawal can pay out money the
* account no longer has.
*/
final class LeakyBank {
private final Map<String, Long> balances = new LinkedHashMap<>();
private final Map<String, Long> paidIn = new LinkedHashMap<>();
void deposit(String to, long amount) {
balances.merge(to, amount, Long::sum);
paidIn.merge(to, amount, Long::sum);
}
void withdraw(String from, long amount) {
if (paidIn.getOrDefault(from, 0L) >= amount) {
balances.merge(from, -amount, Long::sum);
paidIn.merge(from, -amount, Long::sum);
}
}
void transfer(String from, String to, long amount) {
if (balance(from) >= amount) {
balances.merge(from, -amount, Long::sum);
balances.merge(to, amount, Long::sum);
}
}

Each try starts a new state: the system under test, and a model that says what it should hold. The model is usually a few lines written by hand, here a map of what each balance should be. Follow a model starts from a smaller one, a counter’s i:

/** The bank under test, and what each balance should be. */
final class Accounts implements Banking {
final LeakyBank bank = new LeakyBank();
final Ledger model = new Ledger();
@Override
public void deposit(String to, long amount) {
bank.deposit(to, amount);
model.deposit(to, amount);
}
@Override
public void withdraw(String from, long amount) {
bank.withdraw(from, amount);
model.withdraw(from, amount);
}
@Override
public void transfer(String from, String to, long amount) {
bank.transfer(from, to, amount);
model.transfer(from, to, amount);
}
/** Whether the bank holds as much money as the model says. */
boolean moneyIsConserved() {
return bank.total() == model.total();
}
/** Whether every balance in the bank is zero or more. */
boolean noneBelowZero() {
return bank.balances().values().stream().allMatch(cents -> cents >= 0);
}
/**
* The bank's balances, {@code alice = -1, bob = 1}: what a failure
* shows after its last step.
*/
@Override
public String toString() {
return bank.balances().entrySet().stream()
.map(account -> account.getKey() + " = " + account.getValue())
.collect(Collectors.joining(", "));
}
}

The Ledger deposits, withdraws and transfers as a correct bank would, and Accounts does each on the bank and its model alike, so a step is one call. A toString of the state’s own is optional: when the state’s class defines one, a failure prints it after the step that broke it. It implements Banking, an interface of the three steps; the steps below don’t need it, and Steps from an interface shows what it gives.

static Steps<Accounts> theBank() {
return steps(Accounts::new)
.step("deposit", people(), amounts(), Accounts::deposit)
.step("withdraw", people(), amounts(), Accounts::withdraw)
.step("transfer", people(), people(), amounts(), Accounts::transfer)
.when(accounts -> accounts.bank.total() > 0)
.invariant("money is conserved", Accounts::moneyIsConserved)
.invariant("no balance goes below zero", Accounts::noneBelowZero);
}
  • steps(Accounts::new) gives the state each try starts from.
  • .step(name, domains…, body) is one step: its name, a domain for each of its arguments, and what it does with them. Up to six, as forAll takes. An argument can also come from handles or the state, below.
  • .when(…) is the precondition of the step before it. A transfer is only taken when the bank holds money. A step whose precondition doesn’t hold is skipped, and the run goes on.
  • .invariant(name, …) holds at the start and after every step, whatever ran. It’s named, so a failure can say which one broke.

people() is elements("alice", "bob"), and amounts() is longs().atLeast(1).atMost(100).

@Test
@Tag("failing")
void theBankKeepsItsBooks() {
forAll(theBank()).check();
}

forAll(steps).check() takes no lambda: the invariants are the check. .tries, .seed, .id and .example work as on any property. Each try draws a run of steps, eight on average and at most fifty, takes them one after another on a new state, and checks every invariant after each.

Terminal window
invariant "money is conserved" broke after step 3: withdraw("alice", 1)
theBankKeepsItsBooks failed after 9 tries (seed 0x1)
shrunk steps:
1. deposit("bob", 1)
2. transfer("bob", "alice", 1)
3. withdraw("alice", 1) ← bob = 0, alice = 1
pin it:
.example(
step("deposit", "bob", 1L),
step("transfer", "bob", "alice", 1L),
step("withdraw", "alice", 1L))
// typed pins come from @StepBuilder
rerun:
PROPTASTIC_SEED=0x1 ./gradlew test --tests 'StatefulBankTest.theBankKeepsItsBooks'

Read it:

  • The invariant that broke comes first, and the step after which it broke.
  • The shrunk steps are the fewest, simplest steps that still break it, numbered, as they were taken. Here: a deposit, a transfer out of that account into the other, then a withdrawal from the other, every amount 1. After the last comes the state, as its toString says it.
  • The pin replays exactly those steps: paste it before .check().

A step’s own assertions check that one step: a failure in one says step 3 failed: … under its assertion’s message, and a step that throws says step 3 threw: …. Shrinking keeps the failure it found: a smaller run that breaks some other invariant, or fails another way, isn’t the same bug.

@Test
@Tag("failing")
void theBankKeepsItsBooksPinned() {
forAll(theBank())
.example(
step("deposit", "bob", 1L),
step("transfer", "bob", "alice", 1L),
step("withdraw", "alice", 1L))
.tries(0)
.check();
}

Each step(name, arguments…) names a step and gives its arguments. A pinned run is taken as written, before the random tries, and never shrinks. It fails as the shrunk run did, its header saying failed on example 1 of 1.

A step’s domain can depend on the state: a withdrawal of at most the balance, a seat among those still free. fromState(state -> domain) in a domain’s place gives the domain as the state is when the run reaches the step, so every amount drawn is one the step can take. This purse refuses a withdrawal of everything in it:

/**
* A purse that refuses a withdrawal of everything in it: it checks
* {@code amount >= balance} where it means {@code amount > balance}.
*/
final class Purse {
private long balance;
void deposit(long amount) {
balance += amount;
}
boolean withdraw(long amount) {
if (amount >= balance) {
return false;
}
balance -= amount;
return true;
}
long balance() {
return balance;
}
}
static Steps<Purse> aPurse() {
return steps(Purse::new)
.step("deposit", amounts(), Purse::deposit)
.step(
"withdraw",
fromState(purse -> longs().atLeast(1).atMost(purse.balance())),
FromStateTest::withdraw)
.when(purse -> purse.balance() > 0);
}
/** A withdrawal the purse covers, which it must pay. */
static void withdraw(Purse purse, long amount) {
assertTrue(purse.withdraw(amount), "a covered withdrawal is paid");
}

The precondition is checked before the arguments are drawn, so the domain can rely on it: here, a balance of at least 1. A step whose precondition doesn’t hold draws nothing and is skipped.

@Test
@Tag("failing")
void aWithdrawalThePurseCoversIsPaid() {
forAll(aPurse()).check();
}
Terminal window
a covered withdrawal is paid ==> expected: <true> but was: <false>
step 2 failed: withdraw(1)
aWithdrawalThePurseCoversIsPaid failed after 1 try (seed 0x1)
shrunk steps:
1. deposit(1)
2. withdraw(1)
pin it:
.example(step("deposit", 1L), step("withdraw", 1L))
// typed pins come from @StepBuilder
rerun:
PROPTASTIC_SEED=0x1 ./gradlew test --tests 'FromStateTest.aWithdrawalThePurseCoversIsPaid'

The same check with amounts() and assume(amount <= purse.balance()) at the start of the step would draw amounts up to 100 and skip most withdrawals, so a run would seldom take one, and the withdrawal of exactly the balance would come up rarely. Shrinking works on the amount as on any draw: it shrinks toward the domain’s simplest, here 1.

A precondition on the arguments that a domain can’t say is still an assume(…) at the start of the step’s body: the step is skipped when it doesn’t hold, as one whose .when doesn’t, and the run goes on. Call it before the step changes anything.

When the operations already exist as records, steps(start, domain, apply) takes them as they are. A sealed interface of records gives the steps’ domain from its type with any(…):

/**
* One thing a customer asks the bank to do, done on the bank and its
* model alike.
*/
sealed interface Operation {
void applyTo(Accounts accounts);
record Deposit(String to, long amount) implements Operation {
@Override
public void applyTo(Accounts accounts) {
accounts.deposit(to, amount);
}
}
record Withdrawal(String from, long amount) implements Operation {
@Override
public void applyTo(Accounts accounts) {
accounts.withdraw(from, amount);
}
}
record Transfer(String from, String to, long amount) implements Operation {
@Override
public void applyTo(Accounts accounts) {
accounts.transfer(from, to, amount);
}
}
}
static Steps<Accounts> theBank() {
return steps(
Accounts::new,
any(Operation.class)
.with(Operation.Deposit::to, StatefulBankTest.people())
.with(Operation.Deposit::amount, StatefulBankTest.amounts())
.with(Operation.Withdrawal::from, StatefulBankTest.people())
.with(Operation.Withdrawal::amount, StatefulBankTest.amounts())
.with(Operation.Transfer::from, StatefulBankTest.people())
.with(Operation.Transfer::to, StatefulBankTest.people())
.with(Operation.Transfer::amount, StatefulBankTest.amounts()),
(accounts, operation) -> operation.applyTo(accounts))
.invariant("no balance goes below zero", Accounts::noneBelowZero);
}
@Test
@Tag("failing")
void everyOperationKeepsTheBooks() {
forAll(theBank()).check();
}

A failure prints each step as its record, and the pin replays the records, so it compiles and refactors with them. A record step’s precondition is its own: assume(…) in apply, or a check in the record.

Terminal window
invariant "no balance goes below zero" broke after step 3: new Operation.Withdrawal("alice", 1)
everyOperationKeepsTheBooks failed after 12 tries (seed 0x5eed)
shrunk steps:
1. new Operation.Deposit("alice", 1)
2. new Operation.Transfer("alice", "bob", 1)
3. new Operation.Withdrawal("alice", 1) ← alice = -1, bob = 1
pin it:
.example(
new Operation.Deposit("alice", 1L),
new Operation.Transfer("alice", "bob", 1L),
new Operation.Withdrawal("alice", 1L))
rerun:
PROPTASTIC_SEED=0x5eed ./gradlew test --tests 'OperationsTest.everyOperationKeepsTheBooks'

Written by hand, a step’s name is a string beside the method it calls: .step("deposit", …, Accounts::deposit). Nothing holds the two together. Rename the method and the step keeps its old name; give it another argument and the domains no longer line up, which you find out when the test runs. The pins have the same gap: step("deposit", "alice", 1L) is checked when it’s replayed, not when it’s compiled.

When the steps are a fixed set of calls on the state, say so once, as an interface, and mark it @StepBuilder. Each abstract method is a step, named by the method:

/** The steps a bank takes: each method is one, named as it is. */
@StepBuilder
interface Banking {
void deposit(String to, long amount);
void withdraw(String from, long amount);
void transfer(String from, String to, long amount);
}

proptastic’s annotation processor writes two classes beside it as the test code compiles. BankingSteps is the steps, with a method for each, its domains typed by the method’s parameters. .when and .invariant work as on any steps:

static BankingSteps<Accounts> theBank() {
return BankingSteps.steps(Accounts::new)
.deposit(people(), amounts())
.withdraw(people(), amounts())
.transfer(people(), people(), amounts())
.when(accounts -> accounts.bank.total() > 0)
.invariant("money is conserved", Accounts::moneyIsConserved)
.invariant("no balance goes below zero", Accounts::noneBelowZero);
}

BankingStep is one step, for a pin, and a failure’s pin it: line now writes it, as calls that read as the steps do, with the import they need under them. The run is the one the hand-written steps found, as the steps and their domains are the same:

Terminal window
invariant "money is conserved" broke after step 3: withdraw("alice", 1)
theBankKeepsItsBooks failed after 9 tries (seed 0x1)
shrunk steps:
1. deposit("bob", 1)
2. transfer("bob", "alice", 1)
3. withdraw("alice", 1) ← bob = 0, alice = 1
pin it:
.example(
deposit("bob", 1L),
transfer("bob", "alice", 1L),
withdraw("alice", 1L))
// import static stateful.BankingStep.*
rerun:
PROPTASTIC_SEED=0x1 ./gradlew test --tests 'BuiltStepsTest.theBankKeepsItsBooks'
@Test
@Tag("failing")
void theBankKeepsItsBooksPinned() {
forAll(theBank())
.example(
deposit("bob", 1L), // pasted from the failure, as it printed it
transfer("bob", "alice", 1L),
withdraw("alice", 1L))
.tries(0)
.check();
}

With import static stateful.BankingStep.*, as the note says, the pin pastes as it printed. Rename deposit in the interface and .deposit(…) and the pinned deposit(…) stop compiling, each at the line that uses it. Change its arguments and the domains and pins that no longer fit are compile errors too.

The processor runs only when proptastic is on the annotation processor path, as well as the test classpath:

dependencies {
testImplementation("io.proptastic:proptastic:1.0.0")
testAnnotationProcessor("io.proptastic:proptastic:1.0.0")
}

A build that compiles with -Xlint:all -Werror also needs -Xlint:-processing: once any processor runs, javac warns of every annotation none of them claims, JUnit’s @Test included.

Both run on the same engine, draw and shrink the same way, and can be mixed: a hand-written .step(…) can follow the generated ones. Generated steps are not required.

  • Write the steps by hand when a step isn’t one call: it draws its arguments with a precondition of its own (assume(…)), calls several things, or exists only in the test. Or when its name isn’t a method of the state: “From code to design” names the inherited desk’s steps for a spec’s actions, and calls its check where the spec says reserve. It’s also the form with no build setup.
  • Generate them when the steps are the state’s own methods and you’d rather the compiler kept the names, the arguments and the pins in step with them. The interface is also a list of what the test can do, in one place. That counts most where something else reads the names, as a spec does when a test follows it, or where the pins are long-lived: the guides’ tests of the fixed trading desk and of a deadlock generate theirs.
  • Use records when the operations already exist as records, as data your code passes around.

Each step is drawn as a span of recorded choices: a flag for one more step, the pick of the step, then its arguments. So proptastic’s shrinker works on a run as on anything else: it deletes whole steps, ends the run sooner, and makes each argument simpler. A step whose precondition no longer holds once an earlier one is deleted is skipped, its choices still read, so the steps after it keep theirs. The run ends at the first invariant that breaks, so a shrunk run always ends at the step that broke it.

The bank above names its accounts from a fixed list, alice and bob. Many systems hand out the names themselves: opening an account gives back its number, a connection gives back a session, and the steps after it need that value, not one drawn from a list. A step keeps such a value, and a later step draws one of the values kept so far.

This bank numbers its accounts as it opens them. Its transfer reads both balances before it writes either, so a transfer from an account to itself pays it twice:

/**
* A bank whose accounts are opened as they're needed, each with a
* number of its own: a transfer reads both balances before it writes
* either, so a transfer to the same account pays it twice.
*/
final class NumberedBank {
private final Map<Long, Long> balances = new LinkedHashMap<>();
private long next = 1;
long open() {
var number = next++;
balances.put(number, 0L);
return number;
}
void deposit(long account, long amount) {
balances.merge(account, amount, Long::sum);
}
void transfer(long from, long to, long amount) {
long fromBalance = balances.getOrDefault(from, 0L);
long toBalance = balances.getOrDefault(to, 0L);
if (fromBalance >= amount) {
balances.put(from, fromBalance - amount);
balances.put(to, toBalance + amount);
}
}
/** Closes the account, paying out what's in it. */
long close(long account) {
var paid = balances.getOrDefault(account, 0L);
balances.remove(account);
return paid;
}

The state is the bank and what it should hold, money paid in less money paid out:

/** The bank under test, and what it should hold: paid in, less paid out. */
final class Branch implements Branching {
final NumberedBank bank = new NumberedBank();
private long held;
@Override
public long open() {
return bank.open();
}
@Override
public void deposit(long account, long amount) {
bank.deposit(account, amount);
held += amount;
}
@Override
public void transfer(long from, long to, long amount) {
bank.transfer(from, to, amount);
}
void close(long account) {
held -= bank.close(account);
}
boolean moneyIsConserved() {
return bank.total() == held;
}
@Override
public String toString() {
return "holds " + bank.total() + ", should hold " + held;
}
}

handles("account") names the values steps keep. The open step keeps the number the bank gave back, and the other steps take accounts where a domain would go, so each draws an account the run has opened. Closing an account drops it, so no later step draws it:

static Steps<Branch> theBank() {
Handles<Long> accounts = handles("account");
return steps(Branch::new)
.step("open", branch -> accounts.keep(branch.open()))
.step("deposit", accounts, amounts(), Branch::deposit)
.step("transfer", accounts, accounts, amounts(), Branch::transfer)
.step(
"close",
accounts,
(branch, account) -> {
branch.close(account);
accounts.drop(account);
})
.invariant("money is conserved", Branch::moneyIsConserved);
}
  • handles(name) is the values, named for what they are. Each prints as its name and the order the run kept it: account1, account2.
  • .keep(value), inside a step, keeps a value the step made, and returns it.
  • In a domain’s place, the handles draw one of the values kept and not dropped. A step with none to draw, such as a deposit before any account is open, is skipped, as one whose precondition doesn’t hold.
  • .drop(value), inside a step, says the step is done with it: no later step draws it.
@Test
@Tag("failing")
void accountsOpenedAsNeededKeepTheBooks() {
forAll(theBank()).check();
}
Terminal window
invariant "money is conserved" broke after step 3: transfer(account1, account1, 1)
accountsOpenedAsNeededKeepTheBooks failed after 10 tries (seed 0x1)
shrunk steps:
1. var account1 = open()
2. deposit(account1, 1)
3. transfer(account1, account1, 1) ← holds 2, should hold 1
pin it:
.example(
step("open"),
step("deposit", handle("account", 1), 1L),
step("transfer", handle("account", 1), handle("account", 1), 1L))
// typed pins come from @StepBuilder
rerun:
PROPTASTIC_SEED=0x1 ./gradlew test --tests 'HandlesTest.accountsOpenedAsNeededKeepTheBooks'

The step that made a value says so, var account1 = open(), and the steps after it name it. The pin gives each handle by its name and number, handle("account", 1), the first account the run opened, whatever number the bank gave it. Written by hand, the steps pin by name; from an interface, below, the pin reads as the steps do:

@Test
@Tag("failing")
void accountsOpenedAsNeededKeepTheBooksPinned() {
forAll(theBank())
.example(
step("open"),
step("deposit", handle("account", 1), 1L),
step("transfer", handle("account", 1), handle("account", 1), 1L))
.tries(0)
.check();
}

A handle is drawn as a choice among the values kept, the first the simplest. So when shrinking deletes the step that opened an account, the steps that used it use another one, or are skipped when none is left, and every run it tries still makes sense. A seed replays the same steps, as the choices are the same.

In an interface of steps, @Handle("account") says which values are handles. On a method, the step keeps what the method returns; on a parameter, the step draws one the run kept, so its generated method takes no domain for it:

/** A branch's steps: open keeps an account, the others draw one. */
@StepBuilder
interface Branching {
@Handle("account")
long open();
void deposit(@Handle("account") long account, long amount);
void transfer(
@Handle("account") long from,
@Handle("account") long to, // perhaps the same account
long amount);
}

Branch implements it, its open() the bank’s. The closing step stays hand-written, as it drops the account it closes, and follows the generated ones:

static Steps<Branch> theBank() {
Handles<Long> accounts = handles("account");
return BranchingSteps.steps(Branch::new)
.open()
.deposit(amounts())
.transfer(amounts())
.step(
"close",
accounts,
(branch, account) -> {
branch.close(account);
accounts.drop(account);
})
.invariant("money is conserved", Branch::moneyIsConserved);
}
Terminal window
invariant "money is conserved" broke after step 3: transfer(account1, account1, 1)
accountsOpenedAsNeededKeepTheBooks failed after 10 tries (seed 0x1)
shrunk steps:
1. var account1 = open()
2. deposit(account1, 1)
3. transfer(account1, account1, 1) ← holds 2, should hold 1
pin it:
.example(
open(),
deposit(account(1), 1L),
transfer(account(1), account(1), 1L))
// import static stateful.BranchingStep.*
rerun:
PROPTASTIC_SEED=0x1 ./gradlew test --tests 'BuiltHandlesTest.accountsOpenedAsNeededKeepTheBooks'

BranchingStep has a reference for each name, account(1), the first account the run kept, and its pins take it where a step drew one. So the pin reads line for line as the steps do: var account1 = open() is open(), and deposit(account1, 1) is deposit(account(1), 1L):

@Test
@Tag("failing")
void accountsOpenedAsNeededKeepTheBooksPinned() {
forAll(theBank())
.example(
open(), // pasted from the failure, as it printed it
deposit(account(1), 1L),
transfer(account(1), account(1), 1L))
.tries(0)
.check();
}

A step pinned by name takes the same reference, step("close", account(2)); handle("account", 2) is the form for handles no step builder names:

@Test
@Tag("failing")
void aStepByNameTakesTheSameReference() {
forAll(theBank())
.example(
open(),
deposit(account(1), 1L),
open(),
step("close", account(2)),
transfer(account(1), account(1), 1L))
.tries(0)
.check();
}

The same steps can run on several threads at once, sharing one state: Concurrency shows how.

Privacy