test_engine.cpp is about a hundred lines, and every block in it is evidence for one claim in the brief. Reading a test suite this way, claim by claim, is how you judge whether it is enough: for each promise, find the assertion that would fail if the promise broke. If you cannot find one, the promise is untested, however many tests there are.
Predict and run
Predict before runningC++
#include <iostream>
#include <cassert>
int main() {
int live = 10;
const int before = live;
bool rejected = true;
if (!rejected) { live = 99; }
assert(live == before);
std::cout << "State preserved\n";
return 0;
}
Check your prediction
Text
State preserved
The pattern is the backbone of the suite: record the state, attempt something that must fail, compare the state. Checking only rejected would prove the engine noticed the problem, not that it cleaned up after it. The engine's version records export_inventory(engine.snapshot()) as a string, so the comparison covers every item, quantity and name at once.
Claims and their evidence
Types. Three static_asserts at the top of main: Engine is not copyable, is movable, and Rule has a virtual destructor. They fail at compile time, before any runtime test (Day 6).
Rule ownership. A CountingRule increments a counter on construction and decrements it on destruction. The test moves it into an engine, checks the source is empty and the count is 1, moves the engine, applies a batch, and checks the count returns to 0 when the engine's scope ends (Day 2). add_rule(nullptr) must be refused.
Late-failure rollback.Create{1,"Nuts",5}, Adjust{2,-99} must return invalid at index 1 and leave the export identical, with no Nuts (Day 4).
Error kinds and indices. Duplicate, missing for both Adjust and Rename, invalid ID, empty name, quantity 1001, delta 1001 and a name with a leading space each produce their own error, and none changes the export.
Policy timing.Create{3,"Large",1000}, Create{4,"Too much",500} is rejected by TotalLimit(1500) at index 1. A separate engine with a limit of 10 rejects Adjust{1,1}, Adjust{1,-1}: per-event checking, not final-only.
Limits. A 257-event batch is batch_too_large with no index. Exactly 100 items are accepted and the 101st is full.
Parsing and text. Ten malformed lines must be ParseErrors; three events round-trip through export_event and parse_event and also match exact strings; create|0007|0000|Owned normalizes; a parse from a temporary string returns an owned name (Day 5).
Snapshot independence. Changing a copy returned by snapshot() must not change the engine.
Report helper.count_events is checked with a selective predicate, a none predicate and an empty span (Day 3).
Model comparison. 500 seeded batches against a one-integer model (Day 6).
How mutations map to assertions
Each manifest mutant is killed by a specific block. Live-state mutation: the late-failure export comparison. Skipped policy: the rule_rejected assertions. Wrong index: result.index == 1. Omitted commit: the export after the first successful batch. Excluded equality: Create{1,"Max",10} against the limit-10 engine, which lands exactly on the limit. Wrong export quantity: the exact strings. Ignored predicate: the selective count_events check. When you add a feature, add its mutant to the list, and only then the test that kills it.
What the suite does not prove
None of these checks proves that arbitrary rule code is free of side effects, that the engine is thread safe, or that it survives allocation failure; the brief excludes all three. The sanitizer build (-fsanitize=address,undefined) adds evidence against invalid memory access and undefined arithmetic on the paths the tests run, and only on those paths.
Run the suite
Event engine contract testsC++#include "engine.h"
#include <cassert>
#include <iostream>
#include <type_traits>
static BatchResult apply(Engine& engine, std::initializer_list<Event> events) {
return engine.apply(std::span<const Event>(events.begin(), events.size()));
}
struct CountingRule final : Rule {
explicit CountingRule(int& live) : live_(live) { ++live_; }
~CountingRule() override { --live_; }
bool accepts(const Inventory&, const Event&) const override { return true; }
int& live_;
};
int main() {
static_assert(!std::is_copy_constructible_v<Engine>);
static_assert(std::is_move_constructible_v<Engine>);
static_assert(std::has_virtual_destructor_v<Rule>);
int live = 0;
{
Engine owner;
auto rule = std::make_unique<CountingRule>(live);
assert(owner.add_rule(std::move(rule)) && !rule && live == 1);
assert(!owner.add_rule(nullptr));
Engine moved = std::move(owner);
assert(live == 1);
assert(apply(moved, {Create{1,"Owned",1}}).error == Error::none);
}
assert(live == 0);
Engine engine;
assert(engine.add_rule(std::make_unique<TotalLimit>(1500)));
auto result = apply(engine, {Create{2,"Bolts",10}, Adjust{2,-3}});
assert(result.error == Error::none && !result.index);
const std::string original = export_inventory(engine.snapshot());
assert(original == "2|7|Bolts\n");
result = apply(engine, {Create{1,"Nuts",5}, Adjust{2,-99}});
assert(result.error == Error::invalid && result.index == 1);
assert(export_inventory(engine.snapshot()) == original);
result = apply(engine, {Create{2,"Replace",20}});
assert(result.error == Error::duplicate && result.index == 0);
assert(export_inventory(engine.snapshot()) == original);
assert(apply(engine, {Adjust{99,1}}).error == Error::missing);
assert(apply(engine, {Rename{99,"Missing"}}).error == Error::missing);
assert(apply(engine, {Create{0,"Bad",1}}).error == Error::invalid);
assert(apply(engine, {Create{3,"",1}}).error == Error::invalid);
assert(apply(engine, {Create{3,"Bad",1001}}).error == Error::invalid);
assert(apply(engine, {Adjust{2,1001}}).error == Error::invalid);
assert(apply(engine, {Rename{2," Bad"}}).error == Error::invalid);
assert(export_inventory(engine.snapshot()) == original);
assert(apply(engine, {Create{1,"Nuts",5}, Rename{2,"Steel bolts"}}).error == Error::none);
assert(export_inventory(engine.snapshot()) == "1|5|Nuts\n2|7|Steel bolts\n");
auto copy = engine.snapshot(); copy.find(1)->second.quantity = 999;
assert(engine.snapshot().find(1)->second.quantity == 5);
const std::string before_rule = export_inventory(engine.snapshot());
result = apply(engine, {Create{3,"Large",1000}, Create{4,"Too much",500}});
assert(result.error == Error::rule_rejected && result.index == 1);
assert(export_inventory(engine.snapshot()) == before_rule);
assert(apply(engine, {}).error == Error::none);
std::vector<Event> large(257, Adjust{2,0});
result = engine.apply(large);
assert(result.error == Error::batch_too_large && !result.index);
assert(export_inventory(engine.snapshot()) == before_rule);
const std::vector<std::string> bad{"", "create|1|2", "create|0|1|Bad", "adjust|1|+1",
"adjust|1|-", "rename|1| Bad", "rename|1|Bad|extra", "unknown|1|x",
"create|1|99999999999999999999999|Huge", "create|1|1|" + std::string(41,'x')};
for (const auto& line : bad) { assert(std::holds_alternative<ParseError>(parse_event(line))); }
const std::vector<Event> events{Create{7,"Keep title",0}, Adjust{7,-3}, Rename{7,"Renamed"}};
for (const Event& event : events) {
auto canonical = export_event(event);
ParseResult parsed = parse_event(canonical);
assert(std::holds_alternative<Event>(parsed));
assert(export_event(std::get<Event>(parsed)) == canonical);
}
assert(export_event(events[0]) == "create|7|0|Keep title");
assert(export_event(events[1]) == "adjust|7|-3");
assert(export_event(events[2]) == "rename|7|Renamed");
auto leading = parse_event("create|0007|0000|Owned");
assert(std::holds_alternative<Event>(leading));
assert(export_event(std::get<Event>(leading)) == "create|7|0|Owned");
ParseResult owned = parse_event(std::string("rename|7|Temporary"));
assert(export_event(std::get<Event>(owned)) == "rename|7|Temporary");
assert(count_events(events, [](const Event& e) { return std::holds_alternative<Adjust>(e); }) == 1);
assert(count_events(events, [](const Event&) { return false; }) == 0);
assert(count_events(std::span<const Event>{}, [](const Event&) { return true; }) == 0);
Engine reference_checked;
assert(apply(reference_checked,{Create{1,"Seeded",100}}).error == Error::none);
int reference_quantity = 100;
unsigned long seed = 12345;
for (int iteration = 0; iteration < 500; ++iteration) {
std::vector<Event> batch;
int candidate = reference_quantity;
bool valid = true;
for (int j = 0; j < 3; ++j) {
seed = (seed * 1103515245UL + 12345UL) & 0x7fffffffUL;
int delta = (int)(seed % 41) - 20;
batch.push_back(Adjust{1,delta});
if (valid) { candidate += delta; if (candidate < 0 || candidate > 1000) { valid = false; } }
}
result = reference_checked.apply(batch);
assert((result.error == Error::none) == valid);
if (valid) { reference_quantity = candidate; }
assert(reference_checked.snapshot().find(1)->second.quantity == reference_quantity);
}
Engine full;
for (int id = 1; id <= 100; ++id) { assert(apply(full,{Create{id,"Item",1000}}).error == Error::none); }
assert(apply(full,{Create{101,"Extra",1}}).error == Error::full);
assert(full.snapshot().size() == 100 && total_quantity(full.snapshot()) == 100000L);
Engine limit;
limit.add_rule(std::make_unique<TotalLimit>(10));
assert(apply(limit,{Create{1,"Max",10}}).error == Error::none);
assert(apply(limit,{Adjust{1,1},Adjust{1,-1}}).error == Error::rule_rejected); // Per-event policy.
assert(total_quantity(limit.snapshot()) == 10);
std::cout << "Engine checks passed\n";
}
#include "engine.h"
#include <sstream>
#include <utility>
static bool valid_name(const std::string& name) {
if (name.empty() || name.size() > 40 || name.front() == ' ' || name.back() == ' ') { return false; }
for (unsigned char ch : name) { if (ch < 32 || ch > 126 || ch == '|') { return false; } }
return true;
}
static bool valid_id(int id) { return id >= 1 && id <= 9999; }
struct ApplyVisitor {
Inventory& state;
Error operator()(const Create& event) const {
if (!valid_id(event.id) || !valid_name(event.name) || event.quantity < 0 || event.quantity > 1000) { return Error::invalid; }
if (state.find(event.id) != state.end()) { return Error::duplicate; }
if (state.size() >= 100) { return Error::full; }
state.emplace(event.id, Item{event.name, event.quantity});
return Error::none;
}
Error operator()(const Adjust& event) const {
if (!valid_id(event.id) || event.delta < -1000 || event.delta > 1000) { return Error::invalid; }
auto found = state.find(event.id);
if (found == state.end()) { return Error::missing; }
const int next = found->second.quantity + event.delta; // [-1000,2000], no int overflow.
if (next < 0 || next > 1000) { return Error::invalid; }
found->second.quantity = next;
return Error::none;
}
Error operator()(const Rename& event) const {
if (!valid_id(event.id) || !valid_name(event.name)) { return Error::invalid; }
auto found = state.find(event.id);
if (found == state.end()) { return Error::missing; }
found->second.name = event.name;
return Error::none;
}
};
long total_quantity(const Inventory& inventory) {
long total = 0;
for (const auto& entry : inventory) { total += entry.second.quantity; }
return total;
}
bool TotalLimit::accepts(const Inventory& proposed, const Event& event) const {
(void)event;
return total_quantity(proposed) <= maximum_;
}
bool Engine::add_rule(std::unique_ptr<Rule> rule) {
if (!rule) { return false; }
rules_.push_back(std::move(rule));
return true;
}
BatchResult Engine::apply(std::span<const Event> events) {
if (events.size() > 256) { return {Error::batch_too_large, std::nullopt}; }
Inventory staged = state_;
for (std::size_t index = 0; index < events.size(); ++index) {
Error error = std::visit(ApplyVisitor{staged}, events[index]);
if (error != Error::none) { return {error, index}; }
for (const auto& rule : rules_) {
if (!rule->accepts(staged, events[index])) { return {Error::rule_rejected, index}; }
}
}
state_.swap(staged);
return {Error::none, std::nullopt};
}
static std::optional<int> number(std::string_view text, bool signed_value) {
if (text.empty()) { return std::nullopt; }
std::size_t start = signed_value && text.front() == '-' ? 1 : 0;
if (start == text.size()) { return std::nullopt; }
for (std::size_t i = start; i < text.size(); ++i) { if (text[i] < '0' || text[i] > '9') { return std::nullopt; } }
std::istringstream input{std::string(text)};
int value = 0;
if (!(input >> value)) { return std::nullopt; }
return value;
}
ParseResult parse_event(std::string_view line) {
std::vector<std::string_view> fields;
std::size_t start = 0;
for (;;) {
const auto end = line.find('|', start);
fields.push_back(line.substr(start, end == std::string_view::npos ? end : end - start));
if (end == std::string_view::npos) { break; }
start = end + 1;
if (fields.size() >= 4) { return ParseError{"Too many fields"}; }
}
if (fields.size() < 3) { return ParseError{"Missing fields"}; }
auto id = number(fields[1], false);
if (!id || !valid_id(*id)) { return ParseError{"Invalid id"}; }
if (fields[0] == "create" && fields.size() == 4) {
auto quantity = number(fields[2], false);
std::string name(fields[3]);
if (!quantity || *quantity > 1000 || !valid_name(name)) { return ParseError{"Invalid create"}; }
return Event{Create{*id, std::move(name), *quantity}};
}
if (fields[0] == "adjust" && fields.size() == 3) {
auto delta = number(fields[2], true);
if (!delta || *delta < -1000 || *delta > 1000) { return ParseError{"Invalid adjustment"}; }
return Event{Adjust{*id, *delta}};
}
if (fields[0] == "rename" && fields.size() == 3) {
std::string name(fields[2]);
if (!valid_name(name)) { return ParseError{"Invalid name"}; }
return Event{Rename{*id, std::move(name)}};
}
return ParseError{"Unknown event or field count"};
}
struct ExportVisitor {
std::string operator()(const Create& e) const { return "create|" + std::to_string(e.id) + "|" + std::to_string(e.quantity) + "|" + e.name; }
std::string operator()(const Adjust& e) const { return "adjust|" + std::to_string(e.id) + "|" + std::to_string(e.delta); }
std::string operator()(const Rename& e) const { return "rename|" + std::to_string(e.id) + "|" + e.name; }
};
std::string export_event(const Event& event) { return std::visit(ExportVisitor{}, event); }
std::string export_inventory(const Inventory& inventory) {
std::ostringstream output;
for (const auto& entry : inventory) { output << entry.first << '|' << entry.second.quantity << '|' << entry.second.name << '\n'; }
return output.str();
}
#ifndef EVENT_ENGINE_H
#define EVENT_ENGINE_H
#include <concepts>
#include <cstddef>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <variant>
#include <vector>
struct Create { int id; std::string name; int quantity; };
struct Adjust { int id; int delta; };
struct Rename { int id; std::string name; };
using Event = std::variant<Create, Adjust, Rename>;
struct Item { std::string name; int quantity; };
using Inventory = std::map<int, Item>;
enum class Error { none, invalid, duplicate, missing, full, rule_rejected, batch_too_large };
struct BatchResult { Error error; std::optional<std::size_t> index; };
struct ParseError { std::string message; };
using ParseResult = std::variant<Event, ParseError>;
ParseResult parse_event(std::string_view line); // Borrows input during call; returns owned strings.
std::string export_event(const Event& event); // Canonical text for a valid event, no newline.
std::string export_inventory(const Inventory& inventory); // ID order, newline per item.
long total_quantity(const Inventory& inventory);
class Rule {
public:
virtual ~Rule() = default;
// Called on staged state AFTER each event. Must not retain references or produce
// external effects; only engine state participates in the transaction.
virtual bool accepts(const Inventory& proposed, const Event& event) const = 0;
};
class TotalLimit final : public Rule {
public:
explicit TotalLimit(long maximum) : maximum_(maximum) { } // Require maximum >= 0.
bool accepts(const Inventory& proposed, const Event& event) const override;
private:
long maximum_;
};
class Engine {
public:
Engine() = default;
Engine(const Engine&) = delete;
Engine& operator=(const Engine&) = delete;
Engine(Engine&&) = default;
Engine& operator=(Engine&&) = default;
bool add_rule(std::unique_ptr<Rule> rule); // Non-NULL owned rule; future batches only.
BatchResult apply(std::span<const Event> events);
Inventory snapshot() const { return state_; } // Owning copy, independent of later updates.
private:
Inventory state_;
std::vector<std::unique_ptr<Rule>> rules_;
};
// Definition stays in header for instantiation. Predicates inspect, never retain,
// their argument; exceptions/external effects are outside the engine contract.
template<class Predicate>
requires std::predicate<Predicate, const Event&>
std::size_t count_events(std::span<const Event> events, Predicate matches) {
std::size_t count = 0;
for (const Event& event : events) { if (std::invoke(matches, event)) { ++count; } }
return count;
}
#endif
Check your prediction
Text
Engine checks passed
Try two mutations in the editor, predicting the failing assertion each time before you run. First, in Engine::apply, change Inventory staged = state_; to Inventory& staged = state_;. Second, change return {error, index}; to return {error, 0};. An assertion failure stops the program and names the expression and line. Restore the code after each experiment. The compile-fail checks are in the download, because a browser run can show only one program's result at a time.
Practice
Exercise
Your turn
Write a small Store with void set(int id, int quantity) and std::map<int,int> snapshot() const that returns a copy. Then test the two halves of snapshot independence: changing a snapshot does not change the store, and a later change to the store does not change an old snapshot. Print:
Shell
edit copy: store still 5later set: old snapshot still 5, store now 9
Your workspaceC++
#include <iostream>
#include <map>
int main() {
// Write Store and both checks.
return 0;
}
Hint 1: the idea
Returning by value gives the caller its own map. A reference return would make both checks fail, because there would be only one map.
Hint 2: a first step
Take auto copy = store.snapshot(); copy[1] = 999;, then read the store through a fresh snapshot().at(1).
Show one solution
Run the solutionC++
#include <iostream>
#include <map>
class Store {
public:
void set(int id, int quantity) { state_[id] = quantity; }
std::map<int,int> snapshot() const { return state_; }
private:
std::map<int,int> state_;
};
int main() {
Store store;
store.set(1, 5);
auto copy = store.snapshot();
copy[1] = 999;
std::cout << "edit copy: store still " << store.snapshot().at(1) << "\n";
const auto old = store.snapshot();
store.set(1, 9);
std::cout << "later set: old snapshot still " << old.at(1) << ", store now " << store.snapshot().at(1) << "\n";
return 0;
}
Text
edit copy: store still 5later set: old snapshot still 5, store now 9
Change the return type to const std::map<int,int>& and bind const auto& old = store.snapshot();: the second line then prints 9 for the old snapshot, because it was never a snapshot, only a view of live state. at is used instead of operator[] on the const map, which has no operator[]. With exceptions disabled, at on a missing key would stop the program, so it is safe here only because the key is known to exist. Next you extend the engine and take it home.
Completion is saved in this browser only. It does not measure mastery.