Skip to content

Property-based and table-driven tests

Difficulty: Advanced

Key concepts

  • table-driven test
  • property-based test
  • invariant
  • generator
  • fixed seed
  • shrinking
  • metamorphic property
  • test oracle
  • How to write a table-driven test: one row per case, each with the reason it is there, so a new case is one new line.
  • How to write a property-based test: state what must be true for every input, then check it on thousands of generated inputs.
  • Why the inputs come from a fixed seed, why the standard library’s random distributions are not used for that, and why the generator should favour small and awkward values.
  • What shrinking is: turning a failing input with eight people and a total of 999,210 cents into one with three people and 6 cents. And why it finds a small example, not always the smallest.
  • What a metamorphic property is: a check that compares two calls, for when nobody can say what the right answer is.
  • Where each kind of test is strong, and where it misses things the other one catches.

An expense-sharing app splits a bill between people, either equally or in proportion to something: nights stayed, kilometres travelled. Money is whole cents, so a split rarely comes out even. Three people cannot each pay a third of 100.00. The rules:

  • S1. The parts add up to the total, exactly. No cent is lost or made up.
  • S2. Each part is its exact share rounded down or rounded up to the next cent. A share that is already a whole number of cents is not rounded.
  • S3. The cents left over after rounding down go, one each, to the parts that were rounded down the most. Among equal ones, they go to the earliest in the list, so the same bill always splits the same way.
  • S4. A bill with no people, a negative amount or weight, or only zero weights is refused. So are amounts and weights too large to multiply safely.

The interface is one function, plus a shorthand for equal splits:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

split.hpp
// Cents is std::int64_t, a 64-bit whole number (defined above): money is
// counted in whole cents so that no fractions of a cent, and no floating-
// point rounding, ever appear.
//
// The two limits. Large enough for any bill, small enough that total * weight
// cannot overflow a 64-bit integer: 10^12 * 10^6 is 10^18, below the
// largest int64_t, about 9.2 * 10^18. `inline constexpr` makes each a
// compile-time constant that can live in a header included by many files.
// The ' marks in 1'000'000 are digit separators, only there for reading.
inline constexpr Cents max_total = 1'000'000'000'000; // ten billion in whole units
inline constexpr int max_weight = 1'000'000;
// Splits `total` into one part per weight, in proportion to the weights.
// The parts always add up to `total`. Each part is its exact share
// rounded down or up; a share of whole cents is not rounded. The cents
// left over after rounding down go, one each, to the parts whose exact
// shares were rounded down the most, and among equal ones, to the
// earliest. Example: split(100, {1, 2}) is {33, 67}; the exact shares are
// 33.33... and 66.66..., and the one cent left over goes to the second
// part, whose share lost more (0.66...) when rounded down.
// Throws std::invalid_argument if there are no weights, a
// weight or the total is negative, or every weight is zero;
// std::out_of_range if total > max_total or a weight > max_weight.
[[nodiscard]] std::vector<Cents> split(Cents total, const std::vector<int>& weights);
// split(total, {1, 1, ..., 1}) with `people` ones: the first people get
// the extra cents (every share loses the same amount when rounded down, so
// the tie rule gives them to the earliest): split_equally(10, 3) is
// {4, 3, 3}. Throws std::invalid_argument if people < 1.
[[nodiscard]] std::vector<Cents> split_equally(Cents total, int people);

It works by rounding every share down, remembering how much was rounded away, and then handing the cents left over to the largest roundings first. std::stable_sort keeps equal ones in their original order, which is S3’s tie rule:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

split.cpp
// The whole algorithm, in three stages: (1) refuse bad input before doing
// anything, (2) give every part its exact share rounded down, noting how
// much each one lost, (3) hand the few cents still missing to the parts
// that lost the most. `weights` is passed by const reference: read, never
// copied or changed. The result is a new vector, one part per weight.
std::vector<Cents> split(Cents total, const std::vector<int>& weights) {
// Stage 1: every check comes first, so a refused call works nothing out.
if (weights.empty()) throw std::invalid_argument("split: no weights");
if (total < 0) throw std::invalid_argument("split: negative total");
if (total > max_total) throw std::out_of_range("split: total too large");
// Add up the weights, checking each one on the way. weight_sum is a
// Cents (64 bits) so that the sum of many large weights cannot overflow.
Cents weight_sum = 0;
for (const int w : weights) {
if (w < 0) throw std::invalid_argument("split: negative weight");
if (w > max_weight) throw std::out_of_range("split: weight too large");
weight_sum += w;
}
// Checked last, because it needs the sum; it also rules out dividing
// by zero below.
if (weight_sum == 0) throw std::invalid_argument("split: every weight is zero");
// Stage 2. Each exact share is `total * w / weight_sum`. Round it down, and
// remember what was rounded away.
// parts[i] and rounded_away[i] belong to weights[i]; both vectors start
// with one zero per weight.
std::vector<Cents> parts(weights.size());
std::vector<Cents> rounded_away(weights.size());
Cents given = 0; // how many cents the rounded-down parts hand out
for (std::size_t i = 0; i < weights.size(); ++i) {
// Multiply before dividing, in whole numbers: dividing first would
// throw away the fraction before it could be counted. The limits in
// split.hpp keep this product inside 64 bits.
const Cents exact_times_sum = total * weights[i];
// Integer division rounds down here (neither number is negative)...
parts[i] = exact_times_sum / weight_sum;
// ...and % is the remainder it dropped. The cents rounded away are
// rounded_away[i] / weight_sum; comparing the remainders alone is
// enough, because every part shares the same weight_sum.
rounded_away[i] = exact_times_sum % weight_sum;
given += parts[i];
}
// Stage 3. Fewer cents are left than there are parts. Hand them out, one
// each, largest rounding first; stable_sort keeps ties in order.
// (Why fewer: each part lost less than one cent, so together they lost
// less than one cent per part, and what they lost is a whole number.)
// `order` starts as the indexes 0, 1, 2, ...; std::iota fills a range
// with a value and the numbers after it.
std::vector<std::size_t> order(weights.size());
std::iota(order.begin(), order.end(), std::size_t{0});
// Sort the indexes, not the parts, so each part keeps its place in the
// answer. The lambda says "a goes before b if a lost more"; it captures
// rounded_away by reference ([&]) to read it. std::stable_sort, unlike
// std::sort, never reorders two equal elements, so among equal
// remainders the earlier index stays first: the tie rule.
std::stable_sort(order.begin(), order.end(), [&](std::size_t a, std::size_t b) {
return rounded_away[a] > rounded_away[b];
});
// `left` counts the cents still to give and `k` walks along `order`.
// Each step gives one cent to the next index in the sorted order. `k` is
// a Cents to match `left`, so it is cast to std::size_t to index.
for (Cents left = total - given, k = 0; left > 0; --left, ++k) {
++parts[order[static_cast<std::size_t>(k)]];
}
return parts;
}
How this code works: split, step by step
  1. Refuse bad input first. No weights, a negative total or weight, numbers above the limits, or weights that add up to zero: each one throws before anything is worked out. The last check also makes sure the divisions below never divide by zero.
  2. Round every share down. For each weight, total * weight is the exact share multiplied by weight_sum, so it is still a whole number. Dividing it by weight_sum with integer division gives the share rounded down, and % gives the remainder that was dropped. A bigger remainder means the part lost more when it was rounded down.
  3. Count what is missing. given adds up the rounded-down parts, and total - given cents are still to hand out. Each part lost less than one cent, so fewer cents are missing than there are parts.
  4. Decide who gets them. order holds the indexes 0, 1, 2, ..., sorted so that the largest remainder comes first. std::stable_sort keeps equal remainders in their original order, so a tie goes to the earliest part.
  5. Hand them out. The last loop gives one cent to each index at the front of order until none are left.

A worked example: split(11, {1, 2, 3}). The weights add up to 6.

i weight total * weight parts[i] (÷ 6) rounded_away[i] (% 6) exact share
0 1 11 1 5 1.833…
1 2 22 3 4 3.666…
2 3 33 5 3 5.5

given is 9, so 2 cents are left. Sorted by remainder, largest first, order is 0, 1, 2. The two cents go to parts 0 and 1, and the answer is {2, 4, 5}, which adds up to 11. The smallest weight gets an extra cent, because its share lost the most (5/6 of a cent) when rounded down.

A tie: split(2, {1, 3}). The weights add up to 4; 2 * 1 is 0 remainder 2 and 2 * 3 is 6, so 1 remainder 2. One cent is left and the remainders are equal, so the stable sort leaves order as 0, 1 and the cent goes to part 0: {1, 1}. With the weights the other way round, {3, 1}, part 0 is the weight 3, which becomes 2: {2, 0}. Those are the table’s two rows “tied remainders” and “same weights, other order”.

The demo splits three bills:

Expected output
dinner for three, split equally, 100.00: 33.34 33.33 33.33
a cabin, by nights stayed (2, 3, 3), 500.00: 125.00 187.50 187.50
a taxi, by kilometres (4, 7, 11), 33.01: 6.00 10.50 16.51

This is a small function with a lot of cases. Some of them are easy to get wrong: two people tied for the extra cent, a weight of zero, fewer cents than people, the largest allowed numbers. Writing one LLD_TEST per case would bury each case’s input in boilerplate. There are two better ways to cover many inputs: list them, or describe them.

A table-driven test keeps the cases as data, one row each, and runs the same check on every row:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_split_table.cpp
// One row per case: the reason it is here, the input, and the answer
// worked out by hand. A new case is one new line.
// LLD_TEST(name) defines one test, and the site's small test header,
// lld_test.hpp, runs every test it defines. This test checks each row of
// the table with one loop instead of one test per case.
LLD_TEST(split_gives_the_expected_parts_for_each_row) {
// The shape of one row, declared inside the test because nothing else
// needs it. `why` points to a plain C string literal, printed on failure.
struct Row {
const char* why;
Cents total;
std::vector<int> weights;
std::vector<Cents> expected;
};
// Each brace list fills one Row in order: why, total, weights, expected.
// For example, 100 cents by weights {1, 2}: the exact shares are 33.33...
// and 66.66..., so both round down to 33 and 66, and the cent left over
// goes to the second part, which lost more (0.66... against 0.33...).
const std::vector<Row> rows{
{"divides exactly", 300, {1, 1, 1}, {100, 100, 100}},
{"one cent over: to the first", 100, {1, 1, 1}, {34, 33, 33}},
{"two cents over: to the first two", 101, {1, 1, 1}, {34, 34, 33}},
{"fewer cents than people", 2, {1, 1, 1, 1}, {1, 1, 0, 0}},
{"nothing to split", 0, {1, 2}, {0, 0}},
{"one person gets it all", 999, {7}, {999}},
{"proportional, exact", 100, {1, 1, 2}, {25, 25, 50}},
{"extra cent to the larger remainder", 100, {1, 2}, {33, 67}},
{"a zero weight gets nothing", 50, {0, 1, 0}, {0, 50, 0}},
{"tied remainders: to the earliest", 2, {1, 3}, {1, 1}},
{"same weights, other order", 2, {3, 1}, {2, 0}},
{"largest allowed numbers", money::max_total, {money::max_weight, money::max_weight},
{money::max_total / 2, money::max_total / 2}},
};
// Run every row. A wrong row is reported and the loop goes on, so one
// failure does not hide the others.
for (const Row& row : rows) {
const std::vector<Cents> actual = split(row.total, row.weights);
// Two vectors are == when they have the same size and the same
// elements in the same order.
if (actual != row.expected) {
// report_failure is what the LLD_CHECK macros call underneath; it is
// called directly here so the message can say which row failed
// and show both answers. show() prints a vector as {1, 2, 3}.
// __FILE__ and __LINE__ are the file name and line number.
::lld::test::report_failure(__FILE__, __LINE__,
std::string(row.why) + ": got " + show(actual) +
", expected " + show(row.expected));
}
}
}

A few choices make this work:

  • Every row says why it is there. “Tied remainders: to the earliest” tells a reader which rule the row checks, and tells whoever breaks it what they broke. It is printed with the failure.
  • The expected answers are worked out by hand, from the rules, not by running the code and copying what it printed. A table copied from the output checks only that the code has not changed, bugs included.
  • One failing row does not stop the others. The test reports each wrong row and goes on, so a change that breaks three rules shows three lines, not one.
  • Pairs of rows pin a rule. “Tied remainders: to the earliest” and “same weights, other order” give the same weights in both orders and expect different answers. Together they say that order matters, and how.

Refused inputs get a table of their own, because the check is different: each row must throw.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_split_table.cpp
// Every refused input that throws std::invalid_argument is one row of a
// second table; the two too-large cases and split_equally are plain checks.
LLD_TEST(split_refuses_each_kind_of_bad_input) {
// No `expected` column: the expected answer for every row is "throws".
struct Row {
const char* why;
Cents total;
std::vector<int> weights;
};
const std::vector<Row> invalid{
{"no weights", 100, {}},
{"negative total", -1, {1}},
{"negative weight", 100, {1, -1}},
{"every weight zero", 100, {0, 0}},
};
for (const Row& row : invalid) {
try {
// split is [[nodiscard]]; static_cast<void> throws the result away
// on purpose. If split throws, the next line is skipped.
static_cast<void>(split(row.total, row.weights));
// Reached only if split returned normally: that is the failure.
::lld::test::report_failure(__FILE__, __LINE__, std::string(row.why) + ": no throw");
} catch (const std::invalid_argument&) {
// The expected exception: the row passes, nothing to do. Any
// other exception escapes, and the test runner reports it as a failure.
}
}
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// that type. {1} and {money::max_weight + 1} become the weights vector.
LLD_CHECK_THROWS(split(money::max_total + 1, {1}), std::out_of_range);
LLD_CHECK_THROWS(split(100, {money::max_weight + 1}), std::out_of_range);
LLD_CHECK_THROWS(split_equally(100, 0), std::invalid_argument);
}

The two std::out_of_range cases are plain checks rather than rows: with two kinds of exception, the table would need a column saying which one to expect, which is more machinery than two lines.

To see the table catch something, a scratch program, not part of the example, linked the same tests against a plausible but wrong split. It compiled without warnings with both compilers (its includes and namespace are left out here):

// Scratch: a plausible but wrong split, linked in place of split.cpp.
// Each part but the last is its exact share, rounded to the nearest
// cent; the last part gets whatever is left, so the parts always add up.
//
// Where it goes wrong: each part is rounded on its own, with no rule for
// who gets the extra cents, and the last part absorbs every rounding
// error. Nothing stops "whatever is left" from being too small or even
// negative.
std::vector<Cents> split(Cents total, const std::vector<int>& weights) {
// Adds the weights as doubles: the 0.0 start value makes the sum a double.
const double sum = std::accumulate(weights.begin(), weights.end(), 0.0);
if (sum == 0) return std::vector<Cents>(weights.size(), 0); // no checks, but no division by zero
std::vector<Cents> parts;
Cents given = 0;
// `i + 1 < weights.size()` stops one early: every part but the last.
for (std::size_t i = 0; i + 1 < weights.size(); ++i) {
// std::llround rounds to the nearest whole number, halves away
// from zero: 33.33... becomes 33 and 0.5 becomes 1.
parts.push_back(std::llround(static_cast<double>(total) * weights[i] / sum));
given += parts.back();
}
// The last part is the rest. With 2 cents and four equal weights, the
// first three parts round 0.5 up to 1 each, and this is 2 - 3 = -1.
// With 100 cents and three, it is 100 - 33 - 33 = 34: the extra cent
// goes to the last person, not the first.
parts.push_back(total - given);
return parts;
}

The value table’s two failures (paths shortened; the same with GCC and Clang):

test_split_table.cpp:71: check failed: one cent over: to the first: got {33, 33, 34}, expected {34, 33, 33}
test_split_table.cpp:71: check failed: fewer cents than people: got {1, 1, 1, -1}, expected {1, 1, 0, 0}

The scratch split checks nothing (it only avoids dividing by zero when every weight is zero), so every row of the error table failed as well, and so did the split_equally test: 10 failed checks in all, the other 8 not shown here. The second line above is the interesting one. Rounding 0.5 up, three times, gave away more than there was, and the last person was asked to pay minus one cent. The parts still add up.

A table is the right tool when the interesting cases can be listed and the answers worked out by hand. It is direct: each row is an example a reader can check with a pencil. And it is the most direct way to pin a policy, a choice the rules make that could have been made differently, such as who gets the extra cent.

Its limit is the person writing it. A table holds the cases someone thought of. The negative part above was caught because someone wrote the row “fewer cents than people”; nothing in a table finds the case nobody wrote.

A property is a statement that must hold for every valid input. S1 is one, almost word for word: for any total and any weights, the parts add up to the total. A property-based test generates many inputs and checks the statement on each. It does not need to know the right answer for any of them.

This example’s properties come straight from the rules:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_split_properties.cpp
// How each property test reads: prop::check(name, seed, runs, generate,
// shrink, holds) makes `runs` (2000) random inputs with `generate`, starting
// from the fixed `seed`, and calls `holds` on each. `holds` is the lambda at
// the end: it gets one SplitInput (a total and a list of weights) and
// returns true if the property is true for it. On the first false, the
// checker uses `shrink` to find a simpler failing input and reports it.
// The lambdas capture nothing ([]): everything they need is the input.
// S1: one part per weight, and the parts add up to the total exactly.
LLD_TEST(the_parts_add_up_to_the_total) {
prop::check("parts add up", seed, runs, generate, shrink, [](const SplitInput& in) {
const std::vector<Cents> parts = split(in.total, in.weights);
// std::accumulate adds up a range, starting from its last argument.
// Cents{0} makes the running sum a 64-bit Cents; a plain 0 would make
// it an int, which is too small for large totals.
return parts.size() == in.weights.size() &&
std::accumulate(parts.begin(), parts.end(), Cents{0}) == in.total;
});
}
// S2: each part is its exact share rounded down, or that plus one cent; a
// share that is already whole cents must not be changed at all.
LLD_TEST(each_part_is_its_exact_share_rounded_down_or_one_cent_more) {
prop::check("within a cent", seed, runs, generate, shrink, [](const SplitInput& in) {
const std::vector<Cents> parts = split(in.total, in.weights);
// "Assume true, look for a false": any bad part returns false at
// once; if the loop finishes, every part was fine.
for (std::size_t i = 0; i < parts.size(); ++i) {
const Cents exact_times_sum = in.total * in.weights[i];
const Cents down = exact_times_sum / weight_sum(in);
const bool exact = exact_times_sum % weight_sum(in) == 0;
// Allowed: exactly `down`, or `down + 1` when the share was not
// whole. So it fails if the part is not `down` and either the
// share was whole (no rounding allowed) or the part is not
// `down + 1` either.
if (parts[i] != down && (exact || parts[i] != down + 1)) return false;
}
return true;
});
}
// Monotonic: no rule says it directly, but it follows from S2 and S3. If
// person `i` has a larger weight than person `j`, `i` must not pay less.
LLD_TEST(a_larger_weight_never_gets_a_smaller_part) {
prop::check("monotonic", seed, runs, generate, shrink, [](const SplitInput& in) {
const std::vector<Cents> parts = split(in.total, in.weights);
// Compare every pair `(i, j)`, both ways round. With at most 8 people
// that is at most 64 comparisons per input.
for (std::size_t i = 0; i < parts.size(); ++i) {
for (std::size_t j = 0; j < parts.size(); ++j) {
if (in.weights[i] > in.weights[j] && parts[i] < parts[j]) return false;
}
}
return true;
});
}
  • Parts add up is S1, and also checks that there is one part per weight.
  • Within a cent is S2. It works out the rounded-down share, which is part of what split does, so it is close to repeating the code. It stays useful because it checks a range, not an answer: it does not say who gets the extra cents.
  • Monotonic says that a larger weight never gets a smaller part. No rule says that in so many words; it follows from S2 and S3 together. A consequence of the rules is often a good property, because a bug that breaks a rule tends to break its consequences too.

Not every property is worth the same. Against the scratch split above, parts add up passed: the scratch version gives the last person whatever is left, so its parts add up by construction, however wrong they are. So did the scale property below: doubling every weight leaves the scratch version’s floating-point shares exactly the same, so it makes the same mistakes. One property, however true, can be satisfied by a wrong answer. A few, from different rules, are much harder to fool.

The inputs come from a generator, a function from a random number engine to an input:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

split_input.hpp
// Small numbers on purpose: ties, zeros, and totals smaller than the
// number of people are where rounding goes wrong, and with weights up
// to a million they would almost never be generated. Half the totals
// are tiny for the same reason.
// Takes the random engine by reference (std::mt19937&) so each call moves it
// on: the next call gets new numbers, and the same seed always gives the
// same sequence of inputs. prop::pick(rng, low, high) returns a number from
// low to high, both included.
inline SplitInput generate(std::mt19937& rng) {
SplitInput in;
// A coin toss (0 or 1) chooses the size: 0 to 20 cents, or 0 to 1,000,000.
// The ?: picks the first choice when the toss is 0. The toss is drawn
// first, and only the chosen branch draws another number.
in.total = prop::pick(rng, 0, 1) == 0 ? prop::pick(rng, 0, 20) : prop::pick(rng, 0, 1'000'000);
// pick returns a std::int64_t, so the results are cast to the types
// used here: a std::size_t count and int weights. 1 to 8 people, each
// with a weight from 0 to 5.
const auto people = static_cast<std::size_t>(prop::pick(rng, 1, 8));
for (std::size_t i = 0; i < people; ++i) {
in.weights.push_back(static_cast<int>(prop::pick(rng, 0, 5)));
}
// All zeros is an input split refuses, not one it splits, so it is
// repaired here: the first weight becomes 1. Every input is valid.
if (std::accumulate(in.weights.begin(), in.weights.end(), 0) == 0) in.weights[0] = 1;
return in;
}

Its numbers are small on purpose. Rounding goes wrong at ties, zero weights, and totals smaller than the number of people. With weights from 0 to a million, two people would almost never get the same weight, and a total of 2 cents would almost never come up. Weights from 0 to 5 make ties common. Half the totals are tiny for the same reason, and the other half are large, so the sizes in between are covered too. A generator that picks uniformly from everything allowed mostly produces cases where nothing interesting happens.

What this generator never does is go near the limits: totals stop at 1,000,000 cents and weights at 5, so the overflow boundary is covered only by the table’s last row. That split of the work is typical: the table for the exact edges, the generator for the space in between. The small weights also keep the scale property below valid, because doubled weights must stay within max_weight.

The engine starts from a fixed seed, so every run of the test checks the same 2,000 inputs, and a failure can be repeated. That needs more care than it seems:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

property.hpp
// A number in [low, high], for low <= high, from the generator. std::mt19937's output is
// fixed by the standard for a given seed, but the distributions, such
// as std::uniform_int_distribution, may differ between standard
// libraries. Mapping the raw output ourselves keeps a seed's inputs the
// same everywhere. The two calls are separate statements because the
// order of two calls in one expression is unspecified. The modulo is
// slightly uneven, which does not matter for tests.
//
// How: std::mt19937 gives 32 random bits per call. Two calls are joined
// into one 64-bit number (`first << 32` moves the first 32 bits to the top
// half, and `|` puts the second in the bottom half). `raw % range` is then
// a number from 0 to range - 1, and adding `low` shifts it into
// [low, high]. Example: pick(rng, 0, 5) has range 6, so raw % 6 is 0 to 5.
// Unsigned, so all 64 random bits fit, % is never negative, and overflow wraps.
inline std::int64_t pick(std::mt19937& rng, std::int64_t low, std::int64_t high) {
// How many values there are to choose from: high - low + 1.
const auto range = static_cast<std::uint64_t>(high - low) + 1;
const std::uint64_t first = rng();
const std::uint64_t second = rng();
// Each output fits in 32 bits, so shifting one left by 32 cannot lose any.
const std::uint64_t raw = (first << 32) | second;
return low + static_cast<std::int64_t>(raw % range);
}

std::mt19937’s output for a given seed is fixed by the standard, so it is the same with any compiler. The standard distributions, such as std::uniform_int_distribution, are not: each standard library may turn the same engine output into different numbers. A test that used them could generate different inputs with GCC’s library than with another one, and a failure seen on one machine might not happen on another. pick does the mapping itself, with a modulo that is slightly uneven, which does not matter here.

The checker is short. Its interesting part is what it does after a failure:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

property.hpp
// Checks `holds` on `runs` inputs made by `generate(rng)`. On the first
// failure, repeatedly replaces the input with the first of
// `shrink(input)` that still fails, until none does, then reports that
// input with the seed and run number, so the failure can be repeated.
// `shrink` must return only valid inputs, each simpler than its
// argument, so that shrinking ends.
//
// It is a template so that it works for any input type: Generate, Shrink,
// and Holds are whatever the caller passes (here, plain functions and a
// lambda), and the compiler checks that the calls below make sense for
// them. The input type is whatever `generate` returns; it needs an
// operator<< so the report can print it.
template <class Generate, class Shrink, class Holds>
void check(const std::string& name, std::uint32_t seed, int runs, Generate generate,
Shrink shrink, Holds holds) {
// One engine for the whole check, started from the seed: run 0 always
// gets the same input, run 1 the next one, and so on.
std::mt19937 rng(seed);
for (int run = 0; run < runs; ++run) {
auto input = generate(rng);
if (holds(input)) continue; // the property is true here: next input
// A failure. Keep a copy of the input as generated, for the report,
// then shrink `input` itself.
const auto original = input;
// Repeat until a whole pass finds no simpler failing candidate.
// `simpler` starts true so the loop runs at least once; each pass
// sets it false and only a candidate that still fails sets it true.
for (bool simpler = true; simpler;) {
simpler = false;
// shrink(input) returns a new vector that lives until this
// range-for ends, so `candidate` may refer into it safely.
for (auto& candidate : shrink(input)) {
if (!holds(candidate)) {
// Still fails, and is simpler: it becomes the input.
// Moving is safe because the candidate list is not used
// again; `break` leaves it, and the next pass asks shrink
// for candidates of the new input. This is greedy: the
// first failing candidate wins, and it never looks back.
input = std::move(candidate);
simpler = true;
break;
}
}
}
// Build the message in a string stream, using the input's
// operator<<, and report it once. The seed and run number let anyone
// repeat the failure. \" is a double quote inside the string.
std::ostringstream message;
message << "property \"" << name << "\" failed (seed " << seed << ", run " << run
<< ")\n generated: " << original << "\n shrunk to: " << input;
::lld::test::report_failure(__FILE__, __LINE__, message.str());
return; // report the first failure only; the rest would be noise
}
}

A random failing input is usually big and noisy. Shrinking replaces it, step by step, with a simpler input that still fails, until none of the simpler candidates it tries still fails. The checker only asks for candidates; the input type knows what simpler means:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

split_input.hpp
// Simpler versions of a failing input, biggest steps first: a smaller
// total, one person fewer, or a smaller weight. Every candidate is still a
// valid input (at least one weight, not all zero).
// Takes the failing input read-only and returns a list of candidates; it
// does not test them. prop::check tries them in this order and keeps the
// first that still fails. Every candidate is strictly smaller in one way,
// so repeated shrinking must end.
inline std::vector<SplitInput> shrink(const SplitInput& in) {
std::vector<SplitInput> out;
// total - total, total - total/2, total - total/4, ..., total - 1:
// big jumps towards zero first, then smaller ones. `step /= 2` halves
// the step with integer division, and the loop ends when it reaches 0.
// For a total of 6 the candidates' totals are 0, 3, 5. Each brace pair
// {total, weights} builds a SplitInput with a copy of the weights.
for (Cents step = in.total; step > 0; step /= 2) {
out.push_back({in.total - step, in.weights});
}
// One person fewer, each way: drop weight 0, then weight 1, and so on.
// The size() > 1 test skips this when there is only one weight, since
// a split needs at least one.
for (std::size_t i = 0; in.weights.size() > 1 && i < in.weights.size(); ++i) {
// A full copy of the input; erasing from the copy leaves `in` as is.
// begin() + i is an iterator to element i; the cast to ptrdiff_t
// (the signed type used for iterator steps) avoids a sign-conversion warning.
SplitInput fewer = in;
fewer.weights.erase(fewer.weights.begin() + static_cast<std::ptrdiff_t>(i));
// std::move hands the copy's vector over to `out` instead of copying
// it again; `fewer` is not used afterwards.
out.push_back(std::move(fewer));
}
// One weight lowered by 1, each way. A zero weight cannot go lower.
for (std::size_t i = 0; i < in.weights.size(); ++i) {
if (in.weights[i] == 0) continue;
SplitInput lighter = in;
--lighter.weights[i];
out.push_back(std::move(lighter));
}
// Dropping or lowering a weight can leave only zeros, which split
// refuses. std::erase_if (C++20) removes every candidate the lambda
// says yes to, so the list holds valid inputs only.
std::erase_if(out, [](const SplitInput& c) {
return std::accumulate(c.weights.begin(), c.weights.end(), 0) == 0;
});
return out;
}
How this code works: How check and shrink work together
  1. check makes one input with generate and asks holds about it. If the property holds, it moves on to the next run.
  2. On the first input that fails, it keeps a copy, original, for the report.
  3. It asks shrink for a list of simpler candidates and tries them in order. The first one that still fails replaces input, and the search starts again from it, with a new list of candidates.
  4. When a whole list goes by and every candidate passes, nothing simpler is known to fail, so the loop stops. The checker reports both the original and the shrunk input, with the seed and the run number, and stops checking: one failure is enough.

Shrinking always ends, because each candidate is smaller than its parent in one way (a smaller total, one weight fewer, or one weight lower), and none of those can go down for ever.

The candidates for one input. The page’s output above ended at total 6, weights {5, 3, 4}. shrink offers, in this order:

kind candidates
smaller total total 0, then total 3, then total 5
one weight fewer {3, 4}, then {5, 4}, then {5, 3}
one weight lowered {4, 3, 4}, then {5, 2, 4}, then {5, 3, 3}

The totals come from steps of 6, 3, and 1 (6 halved is 3, 3 halved is 1, 1 halved is 0, which ends the loop). Every candidate keeps the other part of the input as it was. None of these is all zeros, so std::erase_if removes nothing. Because the checker stopped at this input, every one of these nine candidates passed the property.

Each candidate makes one thing smaller: the total, the number of people, or one weight. The total is tried first in big steps, then smaller ones: a total of 999,210 first tries 0, then 499,605 cents less, and so on down to one cent less. Every candidate is still a valid input; a shrinker that produced an invalid one would turn a real failure into a different failure, about the input.

The same properties, against the scratch split (paths shortened; the same with GCC and Clang):

property.hpp:97: check failed: property "within a cent" failed (seed 20261119, run 0)
generated: total 999210, weights {5, 5, 5, 1, 3, 3, 1, 5}
shrunk to: total 6, weights {5, 3, 4}
property.hpp:97: check failed: property "monotonic" failed (seed 20261119, run 56)
generated: total 5, weights {4, 3, 1, 1, 1, 2}
shrunk to: total 3, weights {1, 1, 1, 2}
4 test(s), 2 failure(s)

The first input, from the first run, was too big to check by hand. The shrunk one is not: 6 cents for weights 5, 3, and 4 means exact shares of 2.5, 1.5, and 2. Rounding to the nearest gives 3 and 2, which leaves 1 for the last person, whose share was 2. That is the bug, found from a random input and explained by a small one.

The second failure says something the table did not: a person with weight 2 paid less than people with weight 1. No row was written for that, because nobody thought of it.

Shrinking is a search, and a greedy one: it takes the first simpler candidate that still fails and never looks back. An earlier version of this shrinker, for the total, tried only half of it and one cent less; it removed and lowered weights as the current one does. It produced this, with GCC, against the same scratch split:

property.hpp:97: check failed: property "within a cent" failed (seed 20261119, run 0)
generated: total 999210, weights {5, 5, 5, 1, 3, 3, 1, 5}
shrunk to: total 999208, weights {5, 5, 1, 3, 1, 5}
property.hpp:97: check failed: property "monotonic" failed (seed 20261119, run 56)
generated: total 5, weights {4, 3, 1, 1, 1, 2}
shrunk to: total 1, weights {3, 1, 1, 2}
4 test(s), 2 failure(s)

For the first property, it got stuck: half of 999,208 passed, so did one cent less, and so did every list with one weight fewer or one weight lowered. For the second, it found a smaller total than the current shrinker does. Neither version is wrong; the result depends on which candidates are tried, and in which order. A shrinker finds a small failing input, not always the smallest. It is worth trying a few kinds of step, big ones first, and then looking at the result as a starting point for understanding the bug, not as a proof of minimality.

A property can be wrong as easily as the code. This one sounds obviously true: reverse the list of weights, and the parts come out reversed. A scratch program checked it against the real split; it compiled without warnings with both compilers:

LLD_TEST(reversing_the_weights_reverses_the_parts) {
prop::check("reversal", 20261119, 2000, generate, shrink, [](const SplitInput& in) {
// rbegin() and rend() walk the weights backwards, so this builds a
// reversed copy: {1, 2, 3} becomes {3, 2, 1}.
std::vector<int> reversed(in.weights.rbegin(), in.weights.rend());
std::vector<Cents> parts = split(in.total, reversed);
// Reverse the answer back, so part i belongs to weight i again.
std::reverse(parts.begin(), parts.end());
// The claim: the same parts as splitting the original order. It is
// false when there is a tie, because the tie rule depends on order.
return parts == split(in.total, in.weights);
});
}

It fails on the first input (paths shortened; the same with GCC and Clang):

property.hpp:97: check failed: property "reversal" failed (seed 20261119, run 0)
generated: total 999210, weights {5, 5, 5, 1, 3, 3, 1, 5}
shrunk to: total 1, weights {5, 5}
1 test(s), 1 failure(s)

One cent, two people with the same weight. The cent goes to the earliest, by S3, and reversing the list changes who is earliest. The code is right, and the property is wrong. When a property fails, the first question is which of the two is mistaken; the answer here sends you back to the rules, not the code. The table already pins this behaviour with its pair of rows in both orders.

The output also shows the shrinker’s limit again. The simplest failing input is 1 cent with weights {1, 1}, but each of the shrinker’s steps lowers one weight, and {4, 5} or {5, 4} pass: the cent then goes to the larger weight in both orders. Getting from {5, 5} to {1, 1} needs both weights lowered together. A candidate that divides every weight by their greatest common divisor would find it.

Sometimes nobody can say what the right answer is, only how two answers relate. Doubling every weight describes the same proportions, so it must give exactly the same parts:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_split_properties.cpp
// A metamorphic property relates two calls instead of checking one
// answer: doubling every weight describes the same proportions, so it
// must give exactly the same parts. No test needs to know what the
// parts should be.
LLD_TEST(scaling_every_weight_changes_nothing) {
prop::check("scale invariant", seed, runs, generate, shrink, [](const SplitInput& in) {
// A copy of the weights, each doubled in place: `int& w` is a
// reference to the element in `doubled`, so `w *= 2` changes it.
// in.weights itself is const and untouched. The generator keeps
// weights at most 5, so doubled ones stay far below max_weight.
std::vector<int> doubled = in.weights;
for (int& w : doubled) w *= 2;
// Same total, same proportions: the two answers must be equal.
return split(in.total, in.weights) == split(in.total, doubled);
});
}

That is a metamorphic property: change the input in a way whose effect you know, and check that the output changes in that way, or not at all. It needs no knowledge of the right parts. It is often how search, image filters, compilers, and simulations are tested, where computing the expected answer is as hard as writing the code: adding a filter never returns more results; translating a shape moves its bounding box by the same amount. The reversal property above was also metamorphic, and wrong; a metamorphic property is a claim about the rules like any other.

Both kinds are ordinary unit tests in the build. The example gives them different labels, so they can be run apart:

Terminal window
ctest -L unit # the table tests, among others
ctest -L property # the property tests

On this machine, the four property tests, 8,000 inputs in all, take a few hundredths of a second, so there is no reason to keep them out of the normal build. A property test that takes minutes, because its inputs are big or the code is slow, is a candidate for the separate long run described in the trade-off above.

When this approach fits, and when it does not

Section titled “When this approach fits, and when it does not”

Tables and properties fit pure functions with many cases: rounding, parsing, formatting, sorting, scheduling rules, conversions. They also fit any pair of functions that undo each other, such as encode and decode, save and load: “decoding what was encoded gives back the original” is one of the most useful properties there is.

They fit less well when:

  • There are a handful of cases. Three hand-written tests are clearer than a table with three rows and a loop.
  • No property is simpler than the code. If the only way to state what is right is to compute it, the test becomes a second copy of the code. Use examples, a slow but obviously correct oracle, or a metamorphic property instead.
  • The input is hard to generate validly. A generator for valid programs, valid documents, or connected graphs can be bigger than the code under test. Generated inputs that are mostly invalid test the input checks and nothing else.
  • The code talks to the world. A property over a database or a network inherits their slowness and nondeterminism. Test the rules behind a port, as in Test doubles and seams, and keep the properties for the rules.

The two kinds work best together. The table pins the policies and the known awkward cases with exact answers; the properties sweep the space between them for anything nobody listed.

  • Expected answers copied from the output. The table then checks that nothing changed, bugs included. Work them out from the rules.
  • Rows with no reason. Six months later, nobody knows whether a row can be deleted, or what it meant when it fails.
  • A generator that never makes the awkward cases. Uniform values over the whole allowed range rarely produce ties, zeros, or empty lists. Bias towards small numbers and short lists.
  • The standard distributions with a fixed seed. The same seed can give different inputs with a different standard library. Map the engine’s output yourself, or use a library that does.
  • A failure message without the seed. A failure that cannot be repeated cannot be fixed with confidence.
  • Believing a shrunk input is the smallest. It is small, and usually enough. If it is not, add another kind of shrinking step.
  • Properties that are true of wrong answers. “The parts add up” alone is satisfied by a split that charges someone minus one cent. Check several properties from different rules.
  • Fixing the code when the property was wrong. Read the rules first.
  • “The extra cents go to whoever paid least last time.” S3 changes, so the table rows that pin it change, and the reversal property stays false. The parts must still add up. Within a cent still holds only if the new rule chooses among the parts that were rounded down; if it could give a cent to someone whose share was exact, or whose weight is zero, S2 itself has changed, and the property with it. Monotonic may no longer hold, because a heavier weight could now lose the extra cent to a lighter one; the rules, not the test, decide whether that is acceptable.
  • “Split in whole units for cash payments.” The unit of rounding changes from a cent to 100 cents, and a total that is not a whole number of units must be refused, or rounded first, which is a new rule and a new table row. S1 still holds for the totals allowed. S2 becomes “within one unit”, so that property’s arithmetic changes, and the generator must now make whole-unit totals most of the time, or most of its inputs would be refused.
  • “Support percentages that must add up to 100.” A new kind of input with its own validity rule. The generator must produce valid percentages most of the time, and the error table gains a row for percentages that do not add up.

Exercise: State a property for an algorithm

A tagging feature stores each item’s tags as a list. Before saving, it calls this function, declared as in the file the answer’s test was compiled from:

// The distinct tags, in sorted order.
std::vector<std::string> unique_sorted(std::vector<std::string> tags);
  1. State properties that, together, describe exactly what a correct unique_sorted returns, for any list of tags. Try not to describe how it works.
  2. Is “the result is no longer than the input” a good property? Why, or why not?
  3. Describe a generator for the inputs: what should it favour, and why?
  4. Optional: write the property test with this page’s prop::check.
Show the explained answer
  1. Two properties are enough, together:

    • Strictly increasing: each tag in the result is less than the next. This says both “sorted” and “no tag twice” at once.
    • The same tags: every tag in the input appears in the result, and every tag in the result appears in the input.

    There is only one strictly increasing list of a given set of tags, so these two pin the answer exactly, without saying how to compute it. Others are true, and can be handy: running it twice gives the same as running it once (idempotent), and shuffling the input does not change the result (a metamorphic property). Both follow from the first two, so they add no strength here, but they are easy to state when the first two are hard to check.

  2. It is true, but weak. An empty result satisfies it for every input. A property that a function returning nothing would pass is at most a sanity check, worth having only next to stronger ones.

  3. Draw tags from a small pool, such as "a", "b", and "ab", so that repeats are common, and include the empty list. Tags that share a prefix, like "a" and "ab", check that the order is string order. With a large pool of random strings, a repeat would almost never be generated, and the “unique” part would hardly be tested. Shrinking can simply remove one tag at a time.

  4. One way. This is the test part of a file that was compiled with both of this site’s compilers and run with a correct unique_sorted, where it passed; the includes, unique_sorted itself, and the unnamed namespace around the helpers are left out:

// A wrapper around the list, so that it has its own operator<< that
// prop::check can find (the text below the code explains why).
struct Tags {
std::vector<std::string> list;
};
std::ostream& operator<<(std::ostream& out, const Tags& tags) {
out << '{';
for (std::size_t i = 0; i < tags.list.size(); ++i) {
out << (i == 0 ? "" : ", ") << '"' << tags.list[i] << '"';
}
return out << '}';
}
// Up to six tags from a pool of three, so repeats are common, and
// sometimes none at all.
Tags generate(std::mt19937& rng) {
// `static`: the pool is made once and shared by every call.
static const char* const pool[] = {"a", "b", "ab"};
Tags tags;
// 0 to 6 tags, each one of the three pool entries, chosen by index 0 to 2.
const auto count = prop::pick(rng, 0, 6);
for (std::int64_t i = 0; i < count; ++i) tags.list.emplace_back(pool[prop::pick(rng, 0, 2)]);
return tags;
}
// One tag fewer, each way.
std::vector<Tags> shrink(const Tags& tags) {
std::vector<Tags> out;
for (std::size_t i = 0; i < tags.list.size(); ++i) {
Tags fewer = tags;
fewer.list.erase(fewer.list.begin() + static_cast<std::ptrdiff_t>(i));
out.push_back(std::move(fewer));
}
return out;
}
// True if `tag` is somewhere in `list`; std::find returns end() if not.
bool contains(const std::vector<std::string>& list, const std::string& tag) {
return std::find(list.begin(), list.end(), tag) != list.end();
}
LLD_TEST(unique_sorted_keeps_each_tag_once_in_order) {
prop::check("unique and sorted", 7, 500, generate, shrink, [](const Tags& in) {
const std::vector<std::string> out = unique_sorted(in.list);
// 1. Strictly increasing: sorted, and no tag twice.
// std::adjacent_find returns the first neighbour pair for which
// the test is true; here the test is "left >= right", which a
// strictly increasing list never has, so the answer is end().
const bool increasing =
std::adjacent_find(out.begin(), out.end(), std::greater_equal<>{}) == out.end();
// 2. The same tags: none lost, none added.
// std::all_of is true if the lambda is true for every element (and
// for an empty range). [&] lets the lambdas read `out` and `in`.
const bool same_tags =
std::all_of(in.list.begin(), in.list.end(),
[&](const std::string& tag) { return contains(out, tag); }) &&
std::all_of(out.begin(), out.end(),
[&](const std::string& tag) { return contains(in.list, tag); });
return increasing && same_tags;
});
}

Tags wraps the list so that prop::check can find its operator<<. An operator<< for std::vector<std::string> itself, declared after including property.hpp, would not be found from inside the checker’s template: the template’s ordinary lookup happens where it is defined, and the lookup at the call, argument-dependent lookup, searches only namespace std, where vector and string live. Clang 14 rejects such an operator<<, as the standard requires. GCC 11.4 accepts it, so code that relies on it compiles with one compiler and not another. Declaring it before the include works, but then depends on the order of includes; wrapping the list works everywhere.

With the std::sort call removed from unique_sorted, the same test reports (path shortened; the same with GCC and Clang):

property.hpp:97: check failed: property "unique and sorted" failed (seed 7, run 0)
generated: {"a", "b", "b", "a", "ab"}
shrunk to: {"b", "ab"}
1 test(s), 1 failure(s)

Two tags, out of order: the smallest input that shows the bug.

  • A table-driven test lists cases as rows, each with its reason and an answer worked out by hand. It is the way to pin policies and known awkward cases, but it holds only what someone thought of.
  • A property states what must hold for every valid input and is checked on many generated ones. Take properties from the rules and their consequences, keep them simpler than the code, and use several, because one can be satisfied by a wrong answer.
  • Generate from a fixed seed, map the engine’s output yourself rather than trusting the standard distributions to be portable, and favour small and awkward values. Put the seed and run in the failure.
  • Shrinking turns a random failure into a small one that explains the bug. It is greedy, so the result is small, not always the smallest.
  • A metamorphic property compares two calls, for when the right answer cannot be computed independently.
  • A failing property means the code or the property is wrong. Check the rules before fixing either.