Skip to content

Test the Planner’s Promises

The Course
•
30 min study

The planner prints the right report for the acceptance example. That is one input out of millions. A test suite earns its keep by answering a harder question: if someone made a small, plausible mistake in planner.cpp, would any check notice? A useful test detects a plausible mistake. A test that passes for both the correct code and the broken code is decoration.

test_planner.cpp checks the header's promises one by one: duration and title-length boundaries, parsing failure without changing the output, empty reports, independent copies, invalid completion indexes, repeated completion and the 100-task limit. This lesson explains what each group protects against and shows you how to prove the tests are sensitive.

Predict and run

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

struct Task { bool done = false; };

void complete(Task& task) {
    task.done = true;
}

int main() {
    Task task{false};
    complete(task);
    complete(task);
    assert(task.done);
    std::cout << "Completion checks passed\n";
    return 0;
}
Check your prediction
Text
Completion checks passed

Completion sets a state. Change the body to task.done = !task.done; and the second call flips the task back to not done, so the assertion fails. A test that completed the task only once would pass for both versions; calling it twice is what makes the test sharp.

Mutations: testing the tests

A mutation is a small deliberate bug, such as changing one operator. If the test suite still passes, the mutation "survived," and you have found a promise nobody checks. The course's own checks apply six mutations to planner.cpp and require the suite to fail every time. Each one is caught by a specific test:

  • Accept a zero duration (>= 1 becomes >= 0): caught by parsing "0 0 Zero" and expecting failure.
  • Reject the valid maximum (<= 180 becomes < 180): caught by expecting "180 1 ..." to succeed.
  • Toggle completion: caught by completing the same task twice and checking the totals.
  • Wrong remaining total: caught by checking the exact remaining minutes for a known mix.
  • Premature capacity (>= 100 becomes >= 99): caught by adding exactly 100 tasks and expecting all to succeed.
  • Change the output before validation: caught by the loop over bad lines that checks out still holds Keep me, 77 and done after every failure.

Notice the pattern: every boundary is tested from both sides. The suite accepts 1 and 180, rejects 0 and 181, accepts a 40-character title and rejects 41, accepts the 100th task and rejects the 101st. Moving any boundary by one in either direction breaks a check.

Tests that check what did not change

Several promises are about things staying the same, and those are easy to forget to test. After a rejected parse, the output must be unchanged. After add_task copies a task, changing the original must not change the stored copy, so the test edits original.title and asserts that tasks[0].title is still Read. After complete_task with an invalid index, no task may change, so the test asserts !tasks[0].done. These checks catch reference bugs, such as storing a reference where a copy was promised.

Assertion messages differ between local compilers and this browser. Check that the run fails, and which expression it names; do not depend on the exact wording. Keep assertions enabled by never defining NDEBUG when building tests.

Practice

Exercise

Your turn

Write bool complete_at(std::vector<Task>& tasks, std::size_t index) that marks the task at index as done and returns true, or returns false without changing anything when the index is out of range. Repeating it must be safe. With one task {"Read", 25, false}, assert:

  • index 1 (equal to the size) fails and the task is still not done
  • index 0 succeeds and the task is done
  • index 0 again succeeds, the task is still done, and its minutes are still 25
  • an empty vector rejects index 0

When all pass, print Completion checks passed.

Your workspace C++
#include <iostream>
#include <string>
#include <vector>
#include <cassert>

struct Task {
    std::string title;
    int minutes = 0;
    bool done = false;
};

int main() {
    // Write complete_at above main and your assertions here.
    return 0;
}
Hint 1: the idea

Check the index against tasks.size() before touching any element. An index equal to the size is the first invalid one, which makes it the most useful test.

Hint 2: a first step

Start with if (index >= tasks.size()) { return false; }, then assign tasks[index].done = true; and return true.

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

struct Task {
    std::string title;
    int minutes = 0;
    bool done = false;
};

bool complete_at(std::vector<Task>& tasks, std::size_t index) {
    if (index >= tasks.size()) {
        return false;
    }
    tasks[index].done = true;
    return true;
}

int main() {
    std::vector<Task> tasks{{"Read", 25, false}};
    assert(!complete_at(tasks, 1));
    assert(!tasks[0].done);
    assert(complete_at(tasks, 0));
    assert(tasks[0].done);
    assert(complete_at(tasks, 0));
    assert(tasks[0].done && tasks[0].minutes == 25);
    std::vector<Task> empty;
    assert(!complete_at(empty, 0));
    std::cout << "Completion checks passed\n";
    return 0;
}
Text
Completion checks passed

The size check runs before the index is used, so an out-of-range index never reaches tasks[index], which would be undefined behavior. Testing index 1 on a one-task vector catches a > written where >= was meant, and the repeat call catches a toggle. This is the planner's complete_task. Next you will extend the planner with a new report line and build it on your own computer.

Run and challenge the project tests

Planner contract checks C++
#include "planner.h" #include <cassert> #include <iostream> int main() { Task out{"Keep me", 77, true}; const std::vector<std::string> bad{ "", "0 0 Zero", "181 0 Long", "25 2 Flag", "25 0", "25 0 ", "no 0 Text", "25x 0 Text", "25 0Title", "25 1.5 Title", "25+0 Title", "25-0 Title", "99999999999999999999999999 0 Huge", "25 0 " + std::string(41, 'x'), "25 0 Title\nextra" }; for (const std::string& line : bad) { assert(!parse_task(line, out)); assert(out.title == "Keep me" && out.minutes == 77 && out.done); } assert(parse_task("1 0 Short", out) && out.minutes == 1 && !out.done); assert(parse_task("180 1 " + std::string(40, 'x'), out)); assert(out.minutes == 180 && out.done && out.title.size() == 40); std::vector<Task> tasks; Summary result = summarize(tasks); assert(result.planned == 0 && result.completed == 0 && result.remaining == 0); assert(!complete_task(tasks, 0)); Task original{"Read", 25, false}; assert(add_task(tasks, original)); original.title = "Changed"; assert(tasks[0].title == "Read"); assert(add_task(tasks, Task{"Review", 10, true})); assert(!add_task(tasks, Task{"Invalid", 0, false}) && tasks.size() == 2); assert(!add_task(tasks, Task{"", 25, false})); result = summarize(tasks); assert(result.planned == 35 && result.completed == 10 && result.remaining == 25); assert(!complete_task(tasks, tasks.size())); assert(!tasks[0].done); assert(complete_task(tasks, 0)); assert(complete_task(tasks, 0)); result = summarize(tasks); assert(result.planned == 35 && result.completed == 35 && result.remaining == 0); std::vector<Task> full; for (int i = 0; i < 100; ++i) { assert(add_task(full, Task{"Focus", 180, false})); } assert(!add_task(full, Task{"Extra", 1, false}) && full.size() == 100); assert(summarize(full).planned == 18000); std::cout << "Planner checks passed\n"; return 0; } #include "planner.h" #include <sstream> bool valid_task(const Task& task) { return task.minutes >= 1 && task.minutes <= 180 && !task.title.empty() && task.title.size() <= 40 && task.title.find_first_not_of(" \t") != std::string::npos && task.title.find_first_of("\r\n") == std::string::npos; } bool parse_task(const std::string& line, Task& out) { if (line.find_first_of("\r\n") != std::string::npos) { return false; } std::istringstream input(line); Task candidate; int done = 0; char separator = '\0'; if (!(input >> candidate.minutes) || !input.get(separator) || (separator != ' ' && separator != '\t')) { return false; } if (!(input >> done) || (done != 0 && done != 1)) { return false; } // Require whitespace between the done flag and the title. if (!input.get(separator) || (separator != ' ' && separator != '\t')) { return false; } std::getline(input >> std::ws, candidate.title); candidate.done = done == 1; if (!valid_task(candidate)) { return false; } out = candidate; return true; } bool add_task(std::vector<Task>& tasks, const Task& task) { if (tasks.size() >= 100 || !valid_task(task)) { return false; } tasks.push_back(task); return true; } Summary summarize(const std::vector<Task>& tasks) { Summary result; for (const Task& task : tasks) { result.planned += task.minutes; if (task.done) { result.completed += task.minutes; } else { result.remaining += task.minutes; } } return result; } bool complete_task(std::vector<Task>& tasks, std::size_t index) { if (index >= tasks.size()) { return false; } tasks[index].done = true; return true; } #ifndef STUDY_PLANNER_H #define STUDY_PLANNER_H #include <string> #include <vector> struct Task { std::string title; int minutes = 0; bool done = false; }; struct Summary { int planned = 0; int completed = 0; int remaining = 0; }; // One line: minutes, 0/1 done flag, then a title of 1..40 characters. // Durations are 1..180. Failure leaves out unchanged. bool parse_task(const std::string& line, Task& out); // At most 100 tasks. Rejection leaves the vector unchanged. bool add_task(std::vector<Task>& tasks, const Task& task); // Caller supplies tasks accepted by add_task. Summary summarize(const std::vector<Task>& tasks); // Invalid indexes fail without changing any task. Repeating completion is safe. bool complete_task(std::vector<Task>& tasks, std::size_t index); #endif
Check your prediction
Text
Planner checks passed

Apply mutations yourself in the planner.cpp tab. Change task.minutes >= 1 to task.minutes >= 0 and run: an assertion in the bad-lines loop should fail. Press Reset, then remove the final out = candidate; line in parse_task and predict which successful-parse check will catch it: the assertion that "1 0 Short" sets the minutes to 1. Reset again when you are done.

Was this article helpful?

Your response is saved on this device.