Skip to content

Test the Analyzer Guarantees

The Course
•
35 min study

test_analyzer.c is a plain C program: it calls the library directly, checks results with assert, and prints Analyzer checks passed at the end. It needs no stdin, so every contract can be checked in isolation and in a fixed order. This lesson maps each guarantee in analyzer.h to the assertions that prove it, and then turns the question around: if someone broke the code, would these tests notice?

Predict and run

Read the program before pressing Run. Then predict what happens if the loop bound becomes i + 1 < 3.

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

int main(void) {
    int values[3] = {25, 40, 10};
    long total = 0;
    for (size_t i = 0; i < 3; ++i) { total += values[i]; }
    assert(total == 75);
    puts("Total checked");
    return 0;
}
Check your prediction
Text
Total checked

With the shortened bound the loop skips the 10, the total is 65, and the assertion fails before puts runs. The program stops with a message naming the file, line and condition, and exits with a failure status. A failing assertion that names its line is the cheapest debugging tool C offers.

Every guarantee has evidence

Read the test file with this map beside it:

  • Rejected input preserves the output. A list of eleven bad lines, from "" to a 24-letter topic, is parsed into a record holding {"keep", 77}, and after each one the test checks the topic and minutes are unchanged.
  • A failed first allocation leaves an empty collection. With fail_at = 1, the first append returns ANALYZER_NOMEM, and data, length and capacity are still NULL, 0 and 0.
  • Failed growth preserves existing storage. After four appends, the test saves analyzer.data and the capacity, fails the next call, and checks the pointer, length 4, capacity and total 100 are all unchanged, with one live block.
  • Appending a borrowed element is safe across growth. analyzer_append(&analyzer, &analyzer.data[0]) runs exactly when the array must grow.
  • A failed report leaves data unchanged. The report's copy is refused; the total is still 75 and the live count is still 1.
  • The report does not reorder storage. After a successful report, data[0] is still the first record inserted.
  • Destroy releases everything and can be repeated. Destroy is called twice, then probe.live == 0 and all fields are reset.
  • The limit is exact. 1024 appends succeed and the 1025th returns ANALYZER_FULL.

Notice the shape of every check that calls the library: status = analyzer_append(...); on one line, assert(status == ...); on the next. Prove Failure Guarantees warned why. A build that defines NDEBUG removes every assert, and a call written inside one would vanish with it, so the test would stop appending and its later checks would test something else. Pure queries such as analyzer_total can sit inside an assert, because skipping them changes nothing.

Notice the style. Each failure check inspects the state, not only the returned status. A status check alone cannot tell "refused cleanly" from "refused after damaging the data".

Mutations: testing the tests

A test suite can pass because the code is right, or because it checks too little. Mutation testing tells the difference. You make one small, plausible bug and run the tests: if they fail, the mutation is caught; if they pass, you have found a gap. The course's checks apply six mutations to analyzer.c automatically and require every one to be caught:

  • Accept zero minutes (minutes < 0 instead of minutes < 1): caught by the bad line reading 0.
  • Skip the final record when totaling: caught by every total assertion, such as 100 after four appends.
  • Omit the release in destroy: caught by probe.live == 0. Without the probe, this leak would be invisible.
  • Reverse the report order: no assertion fails, but the suite's printed report must match the expected text exactly, with coding before reading, and the course check compares it. Output is evidence too.
  • Write to the parse output before validating: caught by the keep 77 sentinel.
  • Drop one record when removing: caught by the totals after analyzer_remove.

Some bugs have no reliable output: a use-after-free might print the right number. Tests should avoid running undefined behavior at all and rely on sanitizers for that class of bug, which is why the local instructions include a sanitizer build.

Practice

Exercise

Your turn

The starter has a correct valid_minutes and a mutant that accepts 0. Write size_t run_cases(int (*check)(int)) with a table of inputs and expected answers, returning the number of cases where check disagrees. Choose cases so the real function has no failures and the mutant is caught. Use the boundaries. Expected output: real: 0 failures, mutant: 1 failures.

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

int valid_minutes(int value) { return value >= 1 && value <= 180; }
int valid_minutes_mutant(int value) { return value >= 0 && value <= 180; }

/* Write run_cases here. */

int main(void) {
    printf("real: %zu failures\n", run_cases(valid_minutes));
    printf("mutant: %zu failures\n", run_cases(valid_minutes_mutant));
    return 0;
}
Hint 1: the idea

The mutant differs from the real function on exactly one input. A suite that only tests 25 and 500 passes for both. Every comparison in a range check deserves a test on each side of it.

Hint 2: a first step

Start with a table of one case, {25, 1}, and a loop that counts disagreements. Run it: both lines say 0 failures, a suite that cannot tell the two functions apart. Now add cases, one at a time, until the mutant line changes and the real line does not. Each case you add should sit right next to one of the comparisons in valid_minutes.

Show one solution
Run the solution C
#include <stdio.h>
#include <stddef.h>

int valid_minutes(int value) { return value >= 1 && value <= 180; }
int valid_minutes_mutant(int value) { return value >= 0 && value <= 180; }

size_t run_cases(int (*check)(int)) {
    const struct { int input; int expected; } cases[] = {
        {-1, 0}, {0, 0}, {1, 1}, {25, 1}, {180, 1}, {181, 0},
    };
    size_t failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; ++i) {
        if ((check(cases[i].input) != 0) != cases[i].expected) { ++failures; }
    }
    return failures;
}

int main(void) {
    printf("real: %zu failures\n", run_cases(valid_minutes));
    printf("mutant: %zu failures\n", run_cases(valid_minutes_mutant));
    return 0;
}
Text
real: 0 failures
mutant: 1 failures

The case {0, 0} is the one that catches the mutant; remove it and both lines say 0 failures, a passing suite that misses a real bug. Comparing check(...) != 0 with the expected value lets the test accept any non-zero "true". Passing the function under test as a pointer reuses one table for both versions, the callback idea from Day 5. Next, run the project's full suite and apply a mutation yourself.

Run the real suite

Analyzer regression tests C
#include "analyzer.h" #include <assert.h> #include <stdlib.h> #include <string.h> typedef struct { size_t calls; size_t fail_at; size_t live; } Probe; static void *probe_resize(void *context, void *old, size_t bytes) { Probe *probe = context; ++probe->calls; if (probe->calls == probe->fail_at) { return NULL; } int new_block = old == NULL; void *result = realloc(old, bytes); if (result != NULL && new_block) { ++probe->live; } return result; } static void probe_release(void *context, void *storage) { Probe *probe = context; assert(storage != NULL && probe->live > 0); --probe->live; free(storage); } int main(void) { /* Calls that change state run in their own statement and assert checks the saved status, so building with NDEBUG removes only the checks, not the work. */ AnalyzerStatus status; Record out = {"keep", 77}; const char *bad[] = {"", "reading", "reading 0", "reading 181", "Read 25", "reading -1", "reading +25", "reading 25x", "reading 25 extra", "reading 99999999999999999999999999999", "abcdefghijklmnopqrstuvwx 25"}; for (size_t i = 0; i < sizeof bad / sizeof bad[0]; ++i) { status = record_parse(bad[i], &out); assert(status == ANALYZER_INVALID); assert(strcmp(out.topic, "keep") == 0 && out.minutes == 77); } status = record_parse(NULL, &out); assert(status == ANALYZER_INVALID); status = record_parse("reading 25", NULL); assert(status == ANALYZER_INVALID); status = record_parse(" reading 001\r\n", &out); assert(status == ANALYZER_OK && out.minutes == 1); status = record_parse("abcdefghijklmnopqrstuvw 180", &out); assert(status == ANALYZER_OK && out.minutes == 180); Probe probe = {0, 1, 0}; Allocator allocator = {probe_resize, probe_release, &probe}; Analyzer analyzer; analyzer_init(&analyzer, allocator); Record reading = {"reading", 25}; Record coding = {"coding", 40}; assert(analyzer_total(&analyzer) == 0); status = analyzer_append(&analyzer, &reading); assert(status == ANALYZER_NOMEM); assert(analyzer.data == NULL && analyzer.length == 0 && analyzer.capacity == 0); probe.fail_at = 0; for (size_t i = 0; i < 4; ++i) { status = analyzer_append(&analyzer, &reading); assert(status == ANALYZER_OK); } Record *old = analyzer.data; size_t capacity = analyzer.capacity; probe.fail_at = probe.calls + 1; status = analyzer_append(&analyzer, &coding); assert(status == ANALYZER_NOMEM); assert(analyzer.data == old && analyzer.length == 4 && analyzer.capacity == capacity); assert(analyzer_total(&analyzer) == 100 && probe.live == 1); probe.fail_at = 0; /* Passing a borrowed element back into append is safe across growth. */ status = analyzer_append(&analyzer, &analyzer.data[0]); assert(status == ANALYZER_OK); assert(analyzer.length == 5 && analyzer_total(&analyzer) == 125); Record invalid = {"bad", 0}; status = analyzer_append(&analyzer, &invalid); assert(status == ANALYZER_INVALID && analyzer.length == 5); status = analyzer_remove(&analyzer, analyzer.length); assert(status == ANALYZER_INVALID); status = analyzer_remove(&analyzer, 0); assert(status == ANALYZER_OK && analyzer.length == 4); assert(analyzer_total(&analyzer) == 100); analyzer_destroy(&analyzer); analyzer_destroy(&analyzer); assert(probe.live == 0 && analyzer.data == NULL && analyzer.capacity == 0 && analyzer.length == 0); analyzer_init(&analyzer, allocator); status = analyzer_append(&analyzer, &reading); assert(status == ANALYZER_OK); status = analyzer_append(&analyzer, &coding); assert(status == ANALYZER_OK); Record short_reading = {"reading", 10}; status = analyzer_append(&analyzer, &short_reading); assert(status == ANALYZER_OK); probe.fail_at = probe.calls + 1; status = analyzer_report(&analyzer, stdout); assert(status == ANALYZER_NOMEM); assert(analyzer_total(&analyzer) == 75 && probe.live == 1); probe.fail_at = 0; status = analyzer_report(&analyzer, stdout); assert(status == ANALYZER_OK); assert(strcmp(analyzer.data[0].topic, "reading") == 0 && analyzer.data[0].minutes == 25); assert(probe.live == 1); status = analyzer_remove(&analyzer, 0); assert(status == ANALYZER_OK); assert(strcmp(analyzer.data[0].topic, "coding") == 0 && analyzer_total(&analyzer) == 50); status = analyzer_remove(&analyzer, 1); assert(status == ANALYZER_OK); status = analyzer_remove(&analyzer, 0); assert(status == ANALYZER_OK && analyzer_total(&analyzer) == 0); for (size_t i = 0; i < ANALYZER_LIMIT; ++i) { status = analyzer_append(&analyzer, &coding); assert(status == ANALYZER_OK); } status = analyzer_append(&analyzer, &reading); assert(status == ANALYZER_FULL); assert(analyzer.length == ANALYZER_LIMIT && analyzer_total(&analyzer) == 40960); analyzer_destroy(&analyzer); assert(probe.live == 0); (void)status; /* these are only read by assert, which NDEBUG removes */ (void)old; (void)capacity; puts("Analyzer checks passed"); return 0; } #include "analyzer.h" #include <errno.h> #include <stdint.h> #include <stdlib.h> #include <string.h> static void *default_resize(void *context, void *old, size_t bytes) { (void)context; return realloc(old, bytes); } static void default_release(void *context, void *storage) { (void)context; free(storage); } Allocator analyzer_default_allocator(void) { Allocator allocator = {default_resize, default_release, NULL}; return allocator; } void analyzer_init(Analyzer *analyzer, Allocator allocator) { analyzer->data = NULL; analyzer->length = 0; analyzer->capacity = 0; analyzer->allocator = allocator; } void analyzer_destroy(Analyzer *analyzer) { if (analyzer->data != NULL) { analyzer->allocator.release(analyzer->allocator.context, analyzer->data); } analyzer->data = NULL; analyzer->length = 0; analyzer->capacity = 0; } static int whitespace(char ch) { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; } static int valid_record(const Record *record) { if (record == NULL || record->minutes < 1 || record->minutes > 180) { return 0; } size_t i = 0; while (i < TOPIC_CAPACITY && record->topic[i] >= 'a' && record->topic[i] <= 'z') { ++i; } return i > 0 && i < TOPIC_CAPACITY && record->topic[i] == '\0'; } AnalyzerStatus record_parse(const char *line, Record *out) { if (line == NULL || out == NULL) { return ANALYZER_INVALID; } while (whitespace(*line)) { ++line; } Record candidate = {{0}, 0}; size_t length = 0; while (*line >= 'a' && *line <= 'z') { if (length >= TOPIC_CAPACITY - 1) { return ANALYZER_INVALID; } candidate.topic[length++] = *line++; } if (length == 0 || !whitespace(*line)) { return ANALYZER_INVALID; } while (whitespace(*line)) { ++line; } /* Require a decimal digit first: signed notation is outside this format. */ if (*line < '0' || *line > '9') { return ANALYZER_INVALID; } errno = 0; char *end = NULL; long minutes = strtol(line, &end, 10); if (errno == ERANGE || end == line || minutes < 1 || minutes > 180) { return ANALYZER_INVALID; } while (whitespace(*end)) { ++end; } if (*end != '\0') { return ANALYZER_INVALID; } candidate.minutes = (int)minutes; *out = candidate; return ANALYZER_OK; } AnalyzerStatus analyzer_append(Analyzer *analyzer, const Record *record) { if (!valid_record(record)) { return ANALYZER_INVALID; } if (analyzer->length >= ANALYZER_LIMIT) { return ANALYZER_FULL; } /* A caller may pass &data[i]. Copy it before realloc can invalidate it. */ Record candidate = *record; if (analyzer->length == analyzer->capacity) { size_t capacity = analyzer->capacity == 0 ? 4 : analyzer->capacity * 2; if (capacity > ANALYZER_LIMIT) { capacity = ANALYZER_LIMIT; } if (capacity > SIZE_MAX / sizeof *analyzer->data) { return ANALYZER_NOMEM; } void *grown = analyzer->allocator.resize(analyzer->allocator.context, analyzer->data, capacity * sizeof *analyzer->data); if (grown == NULL) { return ANALYZER_NOMEM; } analyzer->data = grown; analyzer->capacity = capacity; } analyzer->data[analyzer->length] = candidate; ++analyzer->length; return ANALYZER_OK; } AnalyzerStatus analyzer_remove(Analyzer *analyzer, size_t index) { if (index >= analyzer->length) { return ANALYZER_INVALID; } size_t following = analyzer->length - index - 1; if (following > 0) { memmove(&analyzer->data[index], &analyzer->data[index + 1], following * sizeof *analyzer->data); } --analyzer->length; return ANALYZER_OK; } long analyzer_total(const Analyzer *analyzer) { long total = 0; for (size_t i = 0; i < analyzer->length; ++i) { total += analyzer->data[i].minutes; } return total; } static int compare_records(const void *left, const void *right) { const Record *a = left; const Record *b = right; int topic = strcmp(a->topic, b->topic); if (topic != 0) { return topic; } return (a->minutes > b->minutes) - (a->minutes < b->minutes); } AnalyzerStatus analyzer_report(const Analyzer *analyzer, FILE *output) { if (analyzer->length == 0) { fprintf(output, "No records\n"); return ANALYZER_OK; } Record *sorted = analyzer->allocator.resize(analyzer->allocator.context, NULL, analyzer->length * sizeof *sorted); if (sorted == NULL) { return ANALYZER_NOMEM; } memcpy(sorted, analyzer->data, analyzer->length * sizeof *sorted); qsort(sorted, analyzer->length, sizeof *sorted, compare_records); size_t i = 0; while (i < analyzer->length) { size_t start = i; long minutes = 0; while (i < analyzer->length && strcmp(sorted[start].topic, sorted[i].topic) == 0) { minutes += sorted[i].minutes; ++i; } fprintf(output, "%s: %zu sessions, %ld minutes\n", sorted[start].topic, i - start, minutes); } analyzer->allocator.release(analyzer->allocator.context, sorted); return ANALYZER_OK; } #ifndef ANALYZER_H #define ANALYZER_H #include <stddef.h> #include <stdio.h> #define TOPIC_CAPACITY 24 #define ANALYZER_LIMIT 1024 typedef enum { ANALYZER_OK, ANALYZER_INVALID, ANALYZER_FULL, ANALYZER_NOMEM } AnalyzerStatus; typedef struct { char topic[TOPIC_CAPACITY]; int minutes; } Record; /* resize has realloc semantics: failure preserves old storage. release frees it. Both callbacks use the same allocator/context, which must outlive the analyzer. */ typedef void *(*ResizeFn)(void *context, void *old, size_t bytes); typedef void (*ReleaseFn)(void *context, void *storage); typedef struct { ResizeFn resize; ReleaseFn release; void *context; } Allocator; /* Owns data. Do not shallow-copy this struct or free data yourself. Invariant: length <= capacity <= ANALYZER_LIMIT; only [0,length) is initialized. Borrowed element pointers expire after successful growth, removal or destroy. */ typedef struct { Record *data; size_t length; size_t capacity; Allocator allocator; } Analyzer; Allocator analyzer_default_allocator(void); /* Initialize once, using a valid allocator. Destroy before reinitializing. */ void analyzer_init(Analyzer *analyzer, Allocator allocator); void analyzer_destroy(Analyzer *analyzer); /* Lowercase ASCII topic (1..23 letters), whitespace, decimal duration 1..180. Leading/trailing whitespace is allowed. No extra fields. Failure preserves out. */ AnalyzerStatus record_parse(const char *line, Record *out); /* Failure leaves contents, length and capacity unchanged. Copies record by value. */ AnalyzerStatus analyzer_append(Analyzer *analyzer, const Record *record); AnalyzerStatus analyzer_remove(Analyzer *analyzer, size_t index); /* Empty total is zero. Caller supplies an initialized analyzer. */ long analyzer_total(const Analyzer *analyzer); /* Sort a temporary copy by topic/minutes. Does not reorder stored records. Allocation failure prints nothing. Caller checks ferror(output) for I/O errors. */ AnalyzerStatus analyzer_report(const Analyzer *analyzer, FILE *output); #endif
Check your prediction
Text
coding: 1 sessions, 40 minutes
reading: 2 sessions, 35 minutes
Analyzer checks passed

The two report lines come from the test's successful analyzer_report call. Now open analyzer.c in the editor, change minutes < 1 || minutes > 180 in record_parse to minutes < 0 || minutes > 180, and run again: an assertion names the line that caught it. Restore the code, then try removing the release call in analyzer_destroy. A live-block count is useful evidence, not a complete memory checker; the optional sanitizer build in the next lesson also detects invalid reads, writes and frees.

Was this article helpful?

Your response is saved on this device.