Skip to content

Test the Callable Contract

The Course
•
35 min study

You wrote a helper that counts matching elements, called it with a predicate that matches everything, and got the right answer. Does the helper work? You cannot tell. A version that ignores the predicate and counts every element gives the same answer for that test. So does a version that has the condition backwards and an input where nothing fails. A test only proves something if a plausible wrong implementation would fail it.

For a helper that takes a predicate, the contract has several parts: it must call the predicate, respect its answer for each element, visit every element, and behave sensibly on an empty range. Each part needs a test case that would catch a violation of that part. This lesson shows the standard set of cases and checks them against deliberately broken implementations.

Predict and run

The lambda selects values of at least 25. What does count_if return?

Predict before running C++
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{10,25,40};
    auto matches = [](int n) { return n >= 25; };
    std::cout << std::count_if(values.begin(),values.end(),matches) << "\n";
    return 0;
}
Check your prediction
Text
2

Two of three values match. This case is useful because it is selective: some elements match and some do not. A predicate returning true for everything would give 3, and one returning false for everything would give 0, so this input distinguishes all three behaviors.

The cases a predicate helper needs

  • Selective: some match and some do not. This catches a helper that ignores the predicate.
  • All match and none match: the extremes, which catch inverted logic and early exits.
  • A match in the last position: catches a loop that stops one element early.
  • Empty input: defines the zero case. For a sum or count it is 0; for "all match" it is true.
  • A boundary value: an element exactly at the predicate's threshold, which catches > written for >= in the caller's lambda.

Keep inputs small enough that you can work out the expected answer by hand. If the expected value comes from running the same algorithm, a bug in the algorithm is copied into the expectation and the test passes anyway.

Weak tests versus strong tests

The program below runs three implementations through a single weak test (everything matches) and through the strong set above. Each implementation is a plain function, so they can be passed around and tested the same way.

To pass a function to another function, the parameter needs a type, and the type of "a pointer to a function" is written in an unusual way. Read using Predicate = bool (*)(int); from the inside out:

  • using Predicate = ...; gives a long type a short name, an alias. From here on, Predicate means the type on the right.
  • (*) says "pointer". The parentheses matter: without them, bool *(int) would be a function returning bool*.
  • bool ... (int) is the function it points to: it takes an int and returns bool.

So a Predicate can hold any function with the signature bool name(int), such as positive. Counter follows the same pattern for the counting functions: a pointer to a function taking const std::vector<int>& and a Predicate, returning std::size_t. To get such a pointer, write the function's name without calling it: weak(correct) passes the function itself, while weak(correct({1}, positive)) would try to pass the number it returns, which the compiler rejects because a number is not a Counter. Inside, count({1, 2, 3}, positive) and matches(value) call whatever function the pointer holds. A template parameter, as in the previous lesson, would accept these functions too; a named pointer type is used here because the test function takes three different implementations that must all have exactly the same signature, and the compiler checks that for each one.

main uses two small pieces of syntax you have not needed before. versions is a plain array of std::pairs, each holding a name and a function, written with braces like a vector. for (const auto& [name, count] : versions) is a structured binding: it unpacks each pair into two names, name for .first and count for .second.

Which tests catch which bug? C++
#include <iostream>
#include <vector>

using Predicate = bool (*)(int);
using Counter = std::size_t (*)(const std::vector<int>&, Predicate);

std::size_t correct(const std::vector<int>& values, Predicate matches) {
    std::size_t count = 0;
    for (int value : values) { if (matches(value)) { ++count; } }
    return count;
}

std::size_t ignores_predicate(const std::vector<int>& values, Predicate) {
    return values.size();
}

std::size_t skips_last(const std::vector<int>& values, Predicate matches) {
    std::size_t count = 0;
    for (std::size_t i = 0; i + 1 < values.size(); ++i) { if (matches(values[i])) { ++count; } }
    return count;
}

bool positive(int n) { return n > 0; }

bool weak(Counter count) { return count({1, 2, 3}, positive) == 3; }

bool strong(Counter count) {
    return count({1, 2, 3}, positive) == 3 && count({-1, 0, 5}, positive) == 1 &&
           count({-1, -2}, positive) == 0 && count({}, positive) == 0;
}

int main() {
    const std::pair<const char*, Counter> versions[] = {
        {"correct", correct}, {"ignores predicate", ignores_predicate}, {"skips last", skips_last}};
    for (const auto& [name, count] : versions) {
        std::cout << name << ": weak " << (weak(count) ? "pass" : "FAIL")
                  << ", strong " << (strong(count) ? "pass" : "FAIL") << "\n";
    }
    return 0;
}
Text
correct: weak pass, strong pass
ignores predicate: weak pass, strong FAIL
skips last: weak FAIL, strong FAIL

The weak test cannot see that the predicate is ignored. The selective case {-1, 0, 5} catches it, and also catches skips_last because its only match is the last element. This is the idea behind the project's mutation checks, which you will use in the checkpoint: break the code on purpose and confirm that some test notices.

Keep predicates pure

A pure predicate depends only on its argument and changes nothing. Tests of a pure predicate are repeatable, and the helper is free to call it however it likes. Standard algorithms do not promise how many times they call a predicate, so a lambda that counts its own calls or modifies a shared variable can behave differently across library versions. The tracker's report predicates only read a const Task&. If you ever need a side effect, test it separately and document it.

Practice

Exercise

Your turn

Write bool all_match(const std::vector<int>&, Predicate) (with using Predicate = bool (*)(int);) and a test function bool suite(AllMatch) that returns true only if an implementation behaves correctly on all-pass, one-failure, failure-in-last-position and empty inputs. Run it against your correct version and three broken ones and print:

Text
correct: passes
always true: caught
skips last: caught
empty is false: caught

The broken versions: always_true returns true without looking; skips_last never checks the final element; empty_is_false returns false for an empty vector but is otherwise correct.

Your workspace C++
#include <iostream>
#include <utility>
#include <vector>

using Predicate = bool (*)(int);
using AllMatch = bool (*)(const std::vector<int>&, Predicate);

bool positive(int n) { return n > 0; }

// Write all_match, the three broken versions and suite here.

int main() {
    return 0;
}
Hint 1: the idea

One counterexample is enough to return false, and an empty vector has no counterexample, so all_match of an empty vector is true. Each test case in the suite should exist because one particular broken version fails it.

Hint 2: a first step

Write all_match and only one broken version, always_true, then a suite with a single case: a vector containing a non-positive value must give false. Run both through it: always_true should be caught. Add the next broken version, find the input it gets wrong, and only then add that case to suite.

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

using Predicate = bool (*)(int);
using AllMatch = bool (*)(const std::vector<int>&, Predicate);

bool positive(int n) { return n > 0; }

bool all_match(const std::vector<int>& values, Predicate matches) {
    for (int value : values) { if (!matches(value)) { return false; } }
    return true;
}

bool always_true(const std::vector<int>&, Predicate) { return true; }

bool skips_last(const std::vector<int>& values, Predicate matches) {
    for (std::size_t i = 0; i + 1 < values.size(); ++i) { if (!matches(values[i])) { return false; } }
    return true;
}

bool empty_is_false(const std::vector<int>& values, Predicate matches) {
    return !values.empty() && all_match(values, matches);
}

bool suite(AllMatch check) {
    return check({1, 2}, positive) && !check({1, 0, 3}, positive) &&
           !check({1, 2, 0}, positive) && check({}, positive);
}

int main() {
    const std::pair<const char*, AllMatch> versions[] = {
        {"correct", all_match}, {"always true", always_true},
        {"skips last", skips_last}, {"empty is false", empty_is_false}};
    for (const auto& [name, check] : versions) {
        std::cout << name << ": " << (suite(check) ? "passes" : "caught") << "\n";
    }
    return 0;
}
Text
correct: passes
always true: caught
skips last: caught
empty is false: caught

always_true fails the one-failure case, skips_last fails only the case whose zero is last, and empty_is_false fails only the empty case, so every case in the suite earns its place. Remove any one of them and one broken version would print passes. The next lesson applies the same thinking to serialization, where a round trip alone can hide matching mistakes.

Was this article helpful?

Your response is saved on this device.