Skip to content

Checkpoint: Detect Broken Guarantees

The Course
•
40 min study

A test suite that passes tells you the code meets the tests. It does not tell you the tests would notice if the code were wrong. Mutation testing checks that directly: make one small, deliberate mistake in the implementation, a mutant, and run the suite. If some test fails, the mutant is killed and the suite has proved it guards that line. If everything still passes, the mutant survived, and you have found a guarantee nobody is checking.

The project's manifest.json lists seven mutants, each a one-line edit with a before and after string: edit live state instead of a staged copy, skip the policy check, report index 0 for every failure, never commit, exclude the policy's equality case, export the wrong quantity, and ignore the report predicate. The course checker applies each one to a fresh copy of the sources, rebuilds the tests and requires them to fail. In this checkpoint you run the same experiment on a small batch function, with mutants passed as function pointers so everything fits in one program.

Predict and run

Predict before running C++
#include <iostream>
#include <cassert>

int main() {
    int live = 10, candidate = 15;
    bool rejected = true;
    if (!rejected) { live = candidate; }
    assert(live == 10);
    std::cout << "Rollback evidence\n";
    return 0;
}
Check your prediction
Text
Rollback evidence

The assertion is the evidence: after a rejection, the state is still 10. Now imagine the mutant that assigns live = candidate; before deciding. The rejection would still be reported, so a test that checked only rejected would pass, and assert(live == 10) is the line that would fail. A mutant is killed only by a test that observes the specific behavior the mutant changes.

What you will use

  • Function pointers as implementations. using Apply = bool (*)(int& quantity, const std::vector<int>& deltas); lets one suite run against the original and each mutant.
  • Named test cases. Each case returns whether it passed, so the suite can report which test killed a mutant.
  • State checks after rejection. Rollback is only proven by comparing state, never by the return value alone.
  • Boundary cases. A total of exactly 1000 must be accepted; only a test at the boundary kills an off-by-one.
  • A dip-and-recover batch. Only a batch that goes invalid in the middle and ends valid kills a final-only check.

Plan before you type

  1. Write the original staged_apply, which validates each step on a candidate and assigns once at the end.
  2. Write four mutants, each differing from the original in one decision.
  3. Write const char* first_failure(Apply apply), which runs four named cases and returns the name of the first failing one, or nullptr.
  4. Run the suite on the original; it must pass. A suite that fails on correct code proves nothing about mutants.
  5. Run it on each mutant and print which test killed it.
Prove it can fail

Delete the boundary case from the suite and run again. The exclude boundary mutant now prints survived. Every remaining test passes against an engine that refuses to fill an item to its documented maximum. That is what a surviving mutant looks like in practice: a correct-looking suite with a missing case. Restore the case, then try writing a fifth mutant of your own that survives, and add the test that kills it.

Mistakes worth checking for

  • The original fails its own suite. A test's expectation is wrong. Fix the test against the specification before judging any mutant.
  • The rollback test passes on the live-state mutant. It checked only the returned false. Compare the quantity with its value before the batch.
  • The dip test passes on the final-only mutant. The batch never goes invalid in the middle, or it ends invalid too. It must dip below 0 and recover.
  • One test kills every mutant. It is probably too broad, such as comparing a long sequence of results. That works, but when it fails it does not say which guarantee broke. Prefer one focused case per guarantee.
  • A mutant survives that cannot change behavior. Some edits produce equivalent mutants, such as reordering two independent checks. No test can kill those, so remove them from the list rather than writing a contrived test.

Practice

Exercise

Your turn

Write the original and the four mutants named below, and a suite of four cases: rollback (from 10, {5, -99} is rejected and leaves 10), commit (from 10, {-3, 2} is accepted and gives 9), boundary (from 10, {990} is accepted and gives 1000) and dip (from 10, {-20, 15} is rejected). Print:

Shell
original: passes
mutate live state: killed by rollback
omit commit: killed by commit
exclude boundary: killed by boundary
final-only check: killed by dip
Your workspace C++
#include <iostream>
#include <vector>

using Apply = bool (*)(int& quantity, const std::vector<int>& deltas);

int main() {
    // Write the original, four mutants and first_failure, then report each.
    return 0;
}
Hint 1: the idea

Each test pins exactly one guarantee. Each mutant breaks exactly one guarantee. The report is the matching between them.

Hint 2: a first step

A case can be a small lambda: auto rollback = [&] { int q = 10; return !apply(q, {5, -99}) && q == 10; };, and first_failure returns "rollback" when it is false.

Show one solution
Run the solution C++
#include <iostream>
#include <vector>

using Apply = bool (*)(int& quantity, const std::vector<int>& deltas);

bool staged_apply(int& quantity, const std::vector<int>& deltas) {
    int candidate = quantity;
    for (int delta : deltas) {
        candidate += delta;
        if (candidate < 0 || candidate > 1000) { return false; }
    }
    quantity = candidate;
    return true;
}

bool mutate_live(int& quantity, const std::vector<int>& deltas) {
    for (int delta : deltas) {
        quantity += delta; // Mutant: no staged copy.
        if (quantity < 0 || quantity > 1000) { return false; }
    }
    return true;
}

bool omit_commit(int& quantity, const std::vector<int>& deltas) {
    int candidate = quantity;
    for (int delta : deltas) {
        candidate += delta;
        if (candidate < 0 || candidate > 1000) { return false; }
    }
    return true; // Mutant: success never published.
}

bool exclude_boundary(int& quantity, const std::vector<int>& deltas) {
    int candidate = quantity;
    for (int delta : deltas) {
        candidate += delta;
        if (candidate < 0 || candidate >= 1000) { return false; } // Mutant: 1000 rejected.
    }
    quantity = candidate;
    return true;
}

bool final_only(int& quantity, const std::vector<int>& deltas) {
    int candidate = quantity;
    for (int delta : deltas) { candidate += delta; }
    if (candidate < 0 || candidate > 1000) { return false; } // Mutant: checked once.
    quantity = candidate;
    return true;
}

const char* first_failure(Apply apply) {
    int q = 10;
    if (apply(q, {5, -99}) || q != 10) { return "rollback"; }
    q = 10;
    if (!apply(q, {-3, 2}) || q != 9) { return "commit"; }
    q = 10;
    if (!apply(q, {990}) || q != 1000) { return "boundary"; }
    q = 10;
    if (apply(q, {-20, 15}) || q != 10) { return "dip"; }
    return nullptr;
}

int main() {
    const char* original = first_failure(staged_apply);
    std::cout << "original: " << (original ? original : "passes") << "\n";
    const struct { const char* name; Apply apply; } mutants[] = {
        {"mutate live state", mutate_live},
        {"omit commit", omit_commit},
        {"exclude boundary", exclude_boundary},
        {"final-only check", final_only}};
    for (const auto& mutant : mutants) {
        const char* killer = first_failure(mutant.apply);
        std::cout << mutant.name << ": " << (killer ? "killed by " : "survived") << (killer ? killer : "") << "\n";
    }
    return 0;
}
Text
original: passes
mutate live state: killed by rollback
omit commit: killed by commit
exclude boundary: killed by boundary
final-only check: killed by dip

Each mutant was killed by the case aimed at it, and the original passed every case, so the suite is both correct and sensitive. The live-state mutant reported false correctly; only the q != 10 comparison caught it. The project's checker does the same at file level: it rewrites engine.cpp or engine.h with each manifest entry, rebuilds test_engine.cpp, and prints Mutation caught: for each mutant that makes the tests fail. Day 7 assembles the full engine and walks through those tests.

Run the complete engine checks

Complete engine checks C++
#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

Locate the late-failure rollback test (Create{1,"Nuts",5}, Adjust{2,-99}) and the per-event TotalLimit test (Adjust{1,1}, Adjust{1,-1} against a limit of 10). For each mutant in the manifest, name the assertion you expect to kill it. Then try one: change <= maximum_ to < maximum_ in engine.cpp in the editor and run. The assertion that stops it is not the compensating batch but the one just before it: creating exactly 10 items under a limit of 10 must succeed. Restore the line, then explain why the batch that exceeds the policy and then compensates must still fail.

Was this article helpful?

Your response is saved on this device.