Skip to content

Invariant

Some rules hold for an object’s whole life, not just after one call: a balance never goes below zero, a queue never holds more than its limit, a tree stays balanced. A bug often needs a particular run of operations to break one, and that’s the run nobody writes by hand. An invariant property draws the run, and checks the rule after every operation.

A music app queues the songs to play next, at most five:

Playlist.java
void add(String song) {
if (songs.size() <= LIMIT) {
songs.add(song);
}
}
void remove(String song) {
songs.remove(song);
}
int size() {
return songs.size();
}

A listener adds songs and removes them, in any order. Each change is a record that applies itself:

PlaylistChange.java
/** One thing a listener does to the playlist. */
sealed interface PlaylistChange permits AddSong, RemoveSong {
void applyTo(Playlist playlist);
}
AddSong.java
record AddSong(String song) implements PlaylistChange {
@Override
public void applyTo(Playlist playlist) {
playlist.add(song);
}
}
RemoveSong.java
record RemoveSong(String song) implements PlaylistChange {
@Override
public void applyTo(Playlist playlist) {
playlist.remove(song);
}
}

Draw a list of changes, apply them one at a time, and after each one check the rule: the playlist never holds more than five songs.

InvariantTest.java
@Test
void aPlaylistNeverHoldsMoreThanFiveSongs() {
forAll(lists(changes()).ofSize(atMost(20)))
.check(
changes -> {
var playlist = new Playlist();
for (var change : changes) {
change.applyTo(playlist);
var size = playlist.size();
assertTrue(size <= 5, "the playlist holds " + size);
}
});
}
InvariantTest.java
static Domain<PlaylistChange> changes() {
return oneOf(domain(songs(), AddSong::new), domain(songs(), RemoveSong::new));
}
static Domain<String> songs() {
return elements("Blackbird", "Yesterday");
}

Two songs are enough. What matters is how many adds and removes there are, and in what order.

Terminal window
the playlist holds 6 ==> expected: <true> but was: <false>
aPlaylistNeverHoldsMoreThanFiveSongs failed after 1 try (seed 0x57b677fd5a08f80c)
shrunk counterexample:
changes = [
new AddSong("Blackbird"),
new AddSong("Blackbird"),
new AddSong("Blackbird"),
new AddSong("Blackbird"),
new AddSong("Blackbird"),
new AddSong("Blackbird")]
// AddSong(song)
pin it:
.example(
List.of(
new AddSong("Blackbird"),
new AddSong("Blackbird"),
new AddSong("Blackbird"),
new AddSong("Blackbird"),
new AddSong("Blackbird"),
new AddSong("Blackbird")))
rerun:
PROPTASTIC_SEED=0x57b677fd5a08f80c ./gradlew test --tests 'InvariantTest.aPlaylistNeverHoldsMoreThanFiveSongs'

proptastic shrinks a failing list by dropping changes and making the rest simpler, for as long as the rule still breaks. That leaves six adds of the first song. add checks size() <= LIMIT, so with five songs queued it adds a sixth. It should be <.

When a value is too long for one line, as this list is, each fact goes on a line of its own, with the value below it. The pin it: line still pastes as it is.

The check runs after every change, not once at the end. Checked only at the end, the rule could break on the sixth add and hold again after a remove, and the property would pass.

  • an object changes over time, through a few kinds of operation: an account, a cart, a cache, a queue, a connection pool;
  • there’s a rule that must hold whatever ran before: a limit, a balance, an ordering, two fields that must agree;
  • bugs need a sequence to show: the sixth add, a remove after a clear, a deposit after a refused withdrawal.
  • An operation that does the wrong thing within the rules. A remove that does nothing keeps the playlist at five or fewer. Check what each operation should do, too, or compare the object with a simple model of it, as compare with a reference does.
  • Sequences longer than you draw. Up to 20 changes is enough here. A bug that needs 50 needs atMost(50).

An invariant is a condition that stays true while a program runs. Testing one over a drawn sequence of operations is the heart of stateful or model-based property testing: see Hughes, 2016 in further reading.

Privacy