Skip to content

Test the Boundaries

The Course
•
30 min study

The report printed the right answer for the sample input. That proves less than it seems: many wrong programs also print Sessions: 3 for that input. A test suite earns its place when it fails for the mistakes you are most likely to make. This lesson reads the project's tests as a design, asks what each assertion protects, and then checks the tests themselves by planting bugs on purpose. A small deliberate bug used this way is called a mutation, and a test suite that catches it has shown that it can fail.

Predict and run

Predict before running C
#include <stdio.h>
#include <assert.h>

int sum(const int values[], int count) {
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += values[i];
    }
    return total;
}

int main(void) {
    int values[3] = {25, 10, 40};
    assert(sum(values, 0) == 0);
    assert(sum(values, 1) == 25);
    assert(sum(values, 3) == 75);
    printf("Sum checks passed\n");
    return 0;
}
Check your prediction
Text
Sum checks passed

Now change the loop condition so it stops one element early, at count - 1. The first assertion still passes, because with count 0 the mutated loop also runs no times. The second fails: a count of 1 now adds nothing and returns 0, not 25. The case that catches the bug is the one where the last element matters. Restore the loop.

How the project tests are organized

Open test_report.c in the editor at the end of this lesson. It checks four promises, each with cases chosen at the edges.

  • The parser rejects bad text and leaves the output alone. One loop feeds nine bad strings, from "" and "0" to a very long number and "25\nextra", and after each one asserts that out is still 77. A single loop tests the unchanged-output promise for every rejected shape.
  • The parser accepts the edges. "1", "180\n" and "025" must succeed with the right value, so a range that is one too narrow, or a parser that refuses leading zeros, fails here.
  • Bad pointers are refused. NULL text, a NULL output, a NULL array and a NULL count each return 0 instead of being dereferenced.
  • Capacity is exact. The test fills all eight slots, asserting each add_session succeeds, then asserts that a ninth fails and the count stays 8, and that the total of eight 25s is 200.

The expected numbers were worked out from the brief, not copied from the program's output. Otherwise the tests would only prove that the code agrees with itself.

Mutations the suite catches

The course's own check script applies four mutations to report.c and requires the tests to fail for each:

  • Accept zero. Changing the parser's value < 1 to value < 0 lets "0" through, and the bad-input loop fails on its second string.
  • Skip the last session. Stopping the total loop at count - 1 makes eight 25s total 175, and the 200 assertion fails.
  • Fill up early. Comparing the count with SESSION_CAPACITY - 1 refuses the eighth session, and the fill loop fails on its last call.
  • Damage the output on failure. Writing *out = 0; at the start of the parser breaks the "still 77" check for the very first bad string.

Some changes are not bugs at all. Writing the capacity check as *count > SESSION_CAPACITY - 1 means exactly the same as *count >= SESSION_CAPACITY for integers, and no test can or should catch it. When a mutation survives, first ask whether it changed behavior; if it did, you have found a missing test.

Assertion failure messages are not part of the test, because their wording and file paths vary between compilers. What matters is that a broken promise makes the run fail. The integration side, feeding real input to main, is covered by the nine acceptance cases from the brief.

Practice

Exercise

Your turn

Write int valid_duration(int minutes) and int count_valid(const int values[], int count). Then write assertions strong enough to catch each of these three mutations: >= 1 becoming > 1, <= 180 becoming < 180, and the count loop stopping at count - 1. Use the array {1, 180, 0, 181}. When everything passes, print:

Text
Boundary checks passed

Then apply each mutation in turn and confirm that some assertion fails.

Your workspace C
#include <stdio.h>
#include <assert.h>

int main(void) {
    int values[4] = {1, 180, 0, 181};
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Each accepted endpoint needs a rejected neighbor. For the loop mutation, you need a count at which the last counted element is valid, so skipping it changes the answer.

Hint 2: a first step

Write four assertions on valid_duration for 0, 1, 180 and 181 before writing its body. For count_valid, assert the results at counts 2 and 4: both should be 2.

Show one solution
C
#include <stdio.h>
#include <assert.h>

int valid_duration(int minutes) {
    return minutes >= 1 && minutes <= 180;
}

int count_valid(const int values[], int count) {
    int found = 0;
    for (int i = 0; i < count; i++) {
        if (valid_duration(values[i])) {
            found++;
        }
    }
    return found;
}

int main(void) {
    int values[4] = {1, 180, 0, 181};
    assert(!valid_duration(0));
    assert(valid_duration(1));
    assert(valid_duration(180));
    assert(!valid_duration(181));
    assert(count_valid(values, 0) == 0);
    assert(count_valid(values, 2) == 2);
    assert(count_valid(values, 4) == 2);
    printf("Boundary checks passed\n");
    return 0;
}
Text
Boundary checks passed

valid_duration(1) catches the first mutation and valid_duration(180) the second. count_valid(values, 2) catches the loop mutation, because the second element, 180, is valid and would be skipped. At count 4 the skipped element, 181, is invalid, so that assertion alone would let the bug survive. Next you will extend the report with an average, guarding the empty case.

The project tests

Try a mutation in report.c C
#include "report.h" #include <assert.h> #include <stddef.h> #include <stdio.h> int main(void) { // Calls that change state run in their own statement; assert checks the // saved result, so the work still happens in a build that defines NDEBUG. int ok = 0; int out = 77; const char *bad[] = {"", "0", "181", "-1", " 25", "25x", "\n", "99999999999999999999999999", "25\nextra"}; for (int i = 0; i < 9; i++) { ok = parse_minutes(bad[i], &out); assert(!ok && out == 77); } ok = parse_minutes(NULL, &out); assert(!ok && out == 77); ok = parse_minutes("25", NULL); assert(!ok); ok = parse_minutes("1", &out); assert(ok && out == 1); ok = parse_minutes("180\n", &out); assert(ok && out == 180); ok = parse_minutes("025", &out); assert(ok && out == 25); struct Session sessions[SESSION_CAPACITY] = {0}; int count = 0; assert(total_minutes(sessions, count) == 0); ok = add_session(sessions, &count, 0); assert(!ok && count == 0); ok = add_session(sessions, &count, 181); assert(!ok && count == 0); ok = add_session(NULL, &count, 1); assert(!ok && count == 0); ok = add_session(sessions, NULL, 1); assert(!ok); for (int i = 0; i < SESSION_CAPACITY; i++) { ok = add_session(sessions, &count, 25); assert(ok); } assert(count == SESSION_CAPACITY); ok = add_session(sessions, &count, 30); assert(!ok && count == SESSION_CAPACITY); assert(total_minutes(sessions, count) == 200); (void)ok; // with NDEBUG the asserts vanish; this keeps ok "used" printf("Report checks passed\n"); return 0; } #include "report.h" #include <stddef.h> int parse_minutes(const char *text, int *out) { if (text == NULL || out == NULL || *text == '\0') { return 0; } int value = 0; int i = 0; while (text[i] >= '0' && text[i] <= '9') { int digit = text[i] - '0'; /* Reject before multiplication: even a very long number cannot overflow. */ if (value > (MAX_MINUTES - digit) / 10) { return 0; } value = value * 10 + digit; i++; } if (i == 0 || value < 1) { return 0; } if (text[i] == '\n') { i++; } if (text[i] != '\0') { return 0; } *out = value; return 1; } int add_session(struct Session sessions[], int *count, int minutes) { if (sessions == NULL || count == NULL || *count < 0 || *count >= SESSION_CAPACITY || minutes < 1 || minutes > MAX_MINUTES) { return 0; } sessions[*count].minutes = minutes; (*count)++; return 1; } int total_minutes(const struct Session sessions[], int count) { int total = 0; for (int i = 0; i < count; i++) { total += sessions[i].minutes; } return total; } #ifndef REPORT_H #define REPORT_H #define SESSION_CAPACITY 8 #define MAX_MINUTES 180 struct Session { int minutes; }; /* On failure, leave *out unchanged. */ int parse_minutes(const char *text, int *out); /* Caller supplies count initialized records, 0 <= count <= SESSION_CAPACITY. */ int total_minutes(const struct Session sessions[], int count); /* Returns 0 without changing storage when invalid or full. */ int add_session(struct Session sessions[], int *count, int minutes); #endif
Check your prediction
Text
Report checks passed

Apply one of the four mutations above to report.c, run, and note which assertion fails. Restore it before trying the next.

Was this article helpful?

Your response is saved on this device.