A bank account
A bank’s tests send 100 cents from alice to bob and check that the total didn’t move. They pass. The same bank makes a cent out of nothing when alice sends 50, and no test sends 50. This page builds a property that finds that bug on its own, in four steps: one transfer, the bug and what proptastic prints when it finds it, a list of transfers, and a rule checked after every step.
The bank keeps accounts by name, in cents. A transfer moves money only when the payer has it:
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 property below is a method in a JUnit test class, with two static imports:
io.proptastic.Proptastic.* and io.proptastic.bounds.Bounds.*.
1. One transfer
Section titled “1. One transfer”Whatever alice and bob have, and whatever alice sends, the bank should hold as much money after the transfer as before. That’s the property:
@Testvoid aTransferKeepsTheTotal() { forAll(balances(), balances(), amounts()) .check( (aliceHas, bobHas, amount) -> { var bank = new Bank(); bank.open("alice", aliceHas); bank.open("bob", bobHas); long totalBefore = bank.total();
bank.transfer("alice", "bob", amount);
assertEquals(totalBefore, bank.total()); });}Read it top to bottom:
forAll(balances(), balances(), amounts())draws three values: what alice has, what bob has, and how much alice sends.- The lambda’s parameters name them,
aliceHas,bobHasandamount. A failure prints them by those names. - The check opens the two accounts, notes
totalBefore, makes the transfer, and asserts that the total didn’t move.
proptastic runs the check many times, with new values each time. balances() and amounts() are
domains: they say which values can be drawn.
static Domain<Long> balances() { return longs().atLeast(0).atMost(1_000_000);}
static Domain<Long> amounts() { return longs().atLeast(1).atMost(1_000_000);}longs() draws any long. .atLeast(…) and .atMost(…) bound it, and both ends are included.
| Domain | Draws | Why |
|---|---|---|
balances() |
0 to 1,000,000 cents | The bank has no overdrafts, so a balance below 0 can’t happen. |
amounts() |
1 to 1,000,000 cents | Whether to refuse a transfer of nothing, or less, is a property of its own. Amounts go as high as balances, so many transfers are more than alice has: the bank refuses those, and the property checks that a refusal keeps the total too. |
2. Catch a bug
Section titled “2. Catch a bug”Now the bank charges one percent on each transfer, and keeps the fee in an account of its own,
fees. Here’s the change, with a bug in it:
void transfer(String from, String to, long amount) { long charged = amount + amount / 100; if (balance(from) >= charged) { balances.merge(from, -charged, Long::sum); balances.merge(to, amount, Long::sum); balances.merge("fees", Math.round(amount / 100.0), Long::sum); }}Run step 1’s property against the new bank:
@Testvoid aTransferWithAFeeKeepsTheTotal() { forAll(balances(), balances(), amounts()) .check( (aliceHas, bobHas, amount) -> { var bank = new BankWithAFee(); bank.open("alice", aliceHas); bank.open("bob", bobHas); long totalBefore = bank.total();
bank.transfer("alice", "bob", amount);
assertEquals(totalBefore, bank.total()); });}It fails with this message:
expected: <50> but was: <51>
aTransferWithAFeeKeepsTheTotal failed after 2 tries (seed 0x4f1c2a9e7b3d5f60) shrunk counterexample: aliceHas = 50, bobHas = 0, amount = 50 fails for any: bobHas pin it: .example(/* aliceHas */ 50L, /* bobHas */ 0L, /* amount */ 50L) rerun: PROPTASTIC_SEED=0x4f1c2a9e7b3d5f60 ./gradlew test --tests 'BankAccountTest.aTransferWithAFeeKeepsTheTotal'Read it:
- Your assertion’s own message comes first. The bank held 51 cents after the transfer, one more than the 50 it held before.
- The header names the test, says how many tries it took to fail, and gives the seed. The seed decides what’s drawn.
- The shrunk counterexample is the smallest input that still fails. proptastic found a failing
input among random ones, then made it smaller until it couldn’t. Here alice has 50 cents, bob has
none, and alice sends 50. One percent of 50 is half a cent. The transfer charges it rounded down,
which is nothing, and the bank keeps it rounded to the nearest cent, which is one. Values print
as you’d say them,
50; the pin below is Java source, so there alongreads50L. fails for anynames the values that played no part: with alice’s 50 and the 50 she sends held, it fails whatever bob has, so the bug is in the fee, not in his balance.pin itis a line to paste afterforAll(…). That input then runs first, every time, so the bug can’t come back unnoticed.rerunis the command that runs this one test again with the same seed, so it draws the same inputs.
Reading a failure goes through each line, and the shapes a failure takes besides this one.
The test from the top of the page passes on this bank. At 100 cents the fee is a whole cent, so the two roundings agree:
@Testvoid aTransferOf100KeepsTheTotal() { var bank = new BankWithAFee(); bank.open("alice", 1000); bank.open("bob", 0);
bank.transfer("alice", "bob", 100);
assertEquals(1000, bank.total());}3. A list of transfers
Section titled “3. A list of transfers”A bank runs one transfer after another. Draw a list of them:
@Testvoid transfersKeepTheTotal() { forAll(lists(transfers()).ofSize(atMost(20))) .check( transfers -> { var bank = new Bank(); bank.open("alice", 100); bank.open("bob", 100); long totalBefore = bank.total();
for (var transfer : transfers) { transfer.applyTo(bank); }
assertEquals(totalBefore, bank.total()); });}A transfer is a record:
record Transfer(String from, String to, long amount) implements Operation { @Override public void applyTo(Bank bank) { bank.transfer(from, to, amount); }}And this is the domain of transfers:
static Domain<Transfer> transfers() { return domain(people(), people(), smallAmounts(), Transfer::new);}
static Domain<String> people() { return elements("alice", "bob");}
static Domain<Long> smallAmounts() { return longs().atLeast(1).atMost(200);}domain(people(), people(), smallAmounts(), Transfer::new)draws a value from each domain and passes them, in order, toTransfer’s constructor: who pays, who’s paid, and how much.elements("alice", "bob")draws one of the values given. Who pays and who’s paid are drawn apart, so sometimes alice pays herself. The bank has to get that right too.- An amount is 1 to 200 cents. Both accounts start with 100, so 200 is all the money in the bank. Some transfers empty an account, and some are more than the payer has.
lists(transfers()).ofSize(atMost(20))draws lists of up to 20 transfers, the empty list included. That’s enough to mix every kind of transfer, and short enough to read when one fails.
The rule hasn’t changed. It’s checked once, at the end.
4. A rule after every step
Section titled “4. A rule after every step”Add deposits and withdrawals too. They change the total on purpose, so “the total doesn’t move” no longer holds. Pick a rule that holds after every step, whatever ran: no balance goes below zero. A rule like that is an invariant.
@Testvoid noBalanceGoesBelowZero() { forAll(lists(operations()).ofSize(atMost(20))) .check( operations -> { var bank = new Bank(); bank.open("alice", 100); bank.open("bob", 100);
for (var operation : operations) { operation.applyTo(bank);
assertThat(bank.balance("alice")).isNotNegative(); assertThat(bank.balance("bob")).isNotNegative(); } });}A deposit and a withdrawal are operations, as a transfer is. Each applies itself to the bank, so the loop doesn’t need to know which kind it has:
/** One thing a customer asks the bank to do. */sealed interface Operation permits Deposit, Withdrawal, Transfer { void applyTo(Bank bank);}record Deposit(String to, long amount) implements Operation { @Override public void applyTo(Bank bank) { bank.deposit(to, amount); }}record Withdrawal(String from, long amount) implements Operation { @Override public void applyTo(Bank bank) { bank.withdraw(from, amount); }}static Domain<Operation> operations() { return oneOf(deposits(), withdrawals(), transfers());}
static Domain<Deposit> deposits() { return domain(people(), smallAmounts(), Deposit::new);}
static Domain<Withdrawal> withdrawals() { return domain(people(), smallAmounts(), Withdrawal::new);}oneOf(deposits(), withdrawals(), transfers()) picks one of the domains given and draws from
it, so a list mixes all three kinds. Deposits and withdrawals take the same people and amounts as
transfers.
- Stateful testing: the same bank as steps taken in any order, each invariant checked after every one, with no loop or bookkeeping of your own, and a failure that names the step that broke it.
- Domains: every way to say what’s drawn, from bounded numbers to records and a choice of several kinds.
- The vocabulary: every word the chain uses, with its bounds and what a failure prints.
- Patterns: a page for each common kind of property, round trip to metamorphic.