Skip to content

Checkpoint: Tests That Catch Broken Contracts

The Course
•
45 min study

A green test suite proves less than it seems. It shows the current code passes the current tests. It does not show the tests would notice if the code broke. A suite that never actually checks the consumed count will stay green when the consumed count is wrong. The way to measure that is mutation testing: make a small, deliberate bug, called a mutant, run the suite, and expect it to fail. A failing suite has killed the mutant. A mutant that survives points at a contract nobody is checking.

The project keeps its mutants in manifest.json, each as an exact before and after string in telemetry.c. The checker applies them one at a time and requires every one to be killed:

  • ignore checksum: the checksum comparison becomes if (0).
  • accept unsupported version and accept unsupported type: one header condition is replaced by 0.
  • reverse field byte order: read_u16 combines its octets little-endian.
  • wrong progress count: FRAME_READY reports consumed - 1.
  • omit owned release: destroy no longer calls the deallocator.
  • reset leaves partial count: reset sets used to 1.
  • accept truncated end: finish ignores buffered bytes.

Each one maps to a clause of the header contract, and each is killed by a specific assertion. Mutants are kept in a file, rather than tried once by hand, so the evidence can be rerun after every future change.

Predict and run

Read the program before pressing Run. Predict the output, then explain why consumed <= supplied alone would not catch a decoder that always returns zero.

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

int main(void) {
    size_t supplied = 10, consumed = 10;
    assert(consumed <= supplied);
    puts("Progress invariant holds");
    return 0;
}
Check your prediction
Text
Progress invariant holds

The upper bound is satisfied by 10, and also by 0. A decoder that never makes progress passes it and leaves its caller looping forever. Killing that mutant needs a second assertion: when a healthy decoder is given at least one byte, it consumes at least one. The project's chunk loop asserts result.consumed > 0, and its partition test asserts the exact count, which kills both "too few" and "too many".

What you will use

  • A function under test and several mutants of it. Each mutant differs from the original in one small change.
  • Function pointers. One suite function takes the implementation as a parameter, so the same tests run against every version.
  • Targeted cases. At least one case per rule, chosen so the rule's mutant gives a different answer from the original.
  • A survivor report. Print which mutants survived, because each one names a missing test.

Plan before you type

  1. Read the original valid_header and each mutant, and write down which input would tell them apart.
  2. Write int suite(int (*valid)(const unsigned char *)) that returns 1 only if every case gives the expected answer.
  3. Start with a single case, the valid fixture header, and run it against all versions. Note which mutants survive.
  4. Add one rejection case per rule until every mutant is killed.
  5. Confirm the original still passes after every addition.
Prove it can fail

Before you add the rejection cases, run the suite with only the valid header. You should see original: passes and only the byte-swap mutant killed, because it is the only mutant that rejects a valid header. Every other mutant accepts more than it should, and a test that only feeds good input cannot see that. Then add your cases one at a time and watch each mutant flip from SURVIVED to killed.

Mistakes worth checking for

  • The original fails your suite. One expected answer is wrong, often a typo in a test header. Fix the test before judging any mutant.
  • A mutant survives every test you add. It may be equivalent to the original, such as length <= 16 && length == 4 with the first clause removed, which accepts exactly the same headers. Equivalent mutants cannot be killed and should be dropped from the manifest, with a note saying why.
  • A rejection test kills the wrong mutant. The test header differs from the valid one in two places, so it is rejected for a different reason. Change exactly one byte per case.
  • A mutant crashes instead of failing. It caused undefined behavior, such as an out-of-bounds write. A crash counts as killed, but it is not reliable evidence; run such mutants under AddressSanitizer so the failure is deterministic.
  • The suite passes only in a debug build. It relied on assert, and the release build defined NDEBUG. Keep test assertions enabled.

Practice

Exercise

Your turn

The starter has an original valid_header and four mutants. Write suite so that it passes the original and kills all four. Print:

Text
original: passes
ignore magic: killed
ignore version: killed
accept short length: killed
swap length bytes: killed
Your workspace C
#include <stdio.h>

static unsigned long length_of(const unsigned char *h) { return ((unsigned long)h[3] << 8) | h[4]; }
static int original(const unsigned char *h) {
    return h[0] == 0x54 && h[1] == 1 && h[2] == 1 && length_of(h) == 4;
}
static int ignore_magic(const unsigned char *h) { return h[1] == 1 && h[2] == 1 && length_of(h) == 4; }
static int ignore_version(const unsigned char *h) { return h[0] == 0x54 && h[2] == 1 && length_of(h) == 4; }
static int short_length(const unsigned char *h) {
    return h[0] == 0x54 && h[1] == 1 && h[2] == 1 && length_of(h) <= 4;
}
static int swap_length(const unsigned char *h) {
    return h[0] == 0x54 && h[1] == 1 && h[2] == 1 && (((unsigned long)h[4] << 8) | h[3]) == 4;
}

int main(void) {
    /* Write suite above, then run it against all five versions here. */
    return 0;
}
Hint 1: the idea

Each mutant is killed by an input where it answers differently from the original. Three of the mutants are too permissive, so they need inputs the original rejects; one is too strict, so the valid header already catches it.

Hint 2: a first step

Store cases as {header bytes, expected} pairs in an array. Start with {0x54, 1, 1, 0, 4} expected 1, then add {0x55, 1, 1, 0, 4} expected 0 for the magic rule.

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

static unsigned long length_of(const unsigned char *h) { return ((unsigned long)h[3] << 8) | h[4]; }
static int original(const unsigned char *h) {
    return h[0] == 0x54 && h[1] == 1 && h[2] == 1 && length_of(h) == 4;
}
static int ignore_magic(const unsigned char *h) { return h[1] == 1 && h[2] == 1 && length_of(h) == 4; }
static int ignore_version(const unsigned char *h) { return h[0] == 0x54 && h[2] == 1 && length_of(h) == 4; }
static int short_length(const unsigned char *h) {
    return h[0] == 0x54 && h[1] == 1 && h[2] == 1 && length_of(h) <= 4;
}
static int swap_length(const unsigned char *h) {
    return h[0] == 0x54 && h[1] == 1 && h[2] == 1 && (((unsigned long)h[4] << 8) | h[3]) == 4;
}

typedef struct { unsigned char header[5]; int expected; } Case;

int suite(int (*valid)(const unsigned char *)) {
    static const Case cases[] = {
        {{0x54, 1, 1, 0, 4}, 1},   /* the fixture header */
        {{0x55, 1, 1, 0, 4}, 0},   /* magic */
        {{0x54, 2, 1, 0, 4}, 0},   /* version */
        {{0x54, 1, 2, 0, 4}, 0},   /* type */
        {{0x54, 1, 1, 0, 3}, 0},   /* length too short */
        {{0x54, 1, 1, 0, 5}, 0},   /* length too long */
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; ++i) {
        if (valid(cases[i].header) != cases[i].expected) { return 0; }
    }
    return 1;
}

int main(void) {
    printf("original: %s\n", suite(original) ? "passes" : "FAILS");
    struct { const char *name; int (*fn)(const unsigned char *); } mutants[] = {
        {"ignore magic", ignore_magic}, {"ignore version", ignore_version},
        {"accept short length", short_length}, {"swap length bytes", swap_length},
    };
    for (size_t i = 0; i < 4; ++i) {
        printf("%s: %s\n", mutants[i].name, suite(mutants[i].fn) ? "SURVIVED" : "killed");
    }
    return 0;
}
Text
original: passes
ignore magic: killed
ignore version: killed
accept short length: killed
swap length bytes: killed

Every case changes one byte of the valid header, so each rejection can only be caused by the rule it names. The type and "too long" cases kill no mutant here, and that is fine: they protect against mutants you have not written yet. Below, the real suite runs against the real decoder. Try one of the manifest's mutations by hand in telemetry.c, predict which assertion will fire, run, and restore the original before the next one. Day 7 assembles the whole project.

Run the regression suite

Telemetry regression tests C
#include "telemetry.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdio.h> typedef struct { size_t calls; size_t live; int fail; } Probe; static void *allocate(void *context, size_t bytes) { Probe *probe = context; ++probe->calls; if (probe->fail) { return NULL; } void *storage = malloc(bytes); if (storage != NULL) { ++probe->live; } return storage; } static void release(void *context, void *storage) { Probe *probe = context; assert(probe->live == 1 && storage != NULL); --probe->live; free(storage); } static const unsigned char fixture[10] = {0x54,1,1,0,4,0,1,0,25,0x74}; static void decode_chunks(Decoder *decoder, const unsigned char *data, size_t size, size_t chunk) { decoder_reset(decoder); size_t offset = 0, frames = 0; while (offset < size) { size_t end = offset + chunk; if (end > size) { end = size; } while (offset < end) { Reading out = {77,88}; FeedResult result = decoder_feed(decoder, data + offset, end - offset, &out); assert(result.consumed > 0 && result.consumed <= end - offset); assert(result.status != DECODE_ERROR); offset += result.consumed; if (result.status == FRAME_READY) { assert(out.sensor == 1 && out.value == 25); ++frames; } else { assert(result.status == NEED_MORE && offset == end); assert(out.sensor == 77 && out.value == 88); } } } assert(frames == size / 10 && decoder_finish(decoder) == STREAM_END); } int main(void) { Probe probe = {0,0,1}; TelemetryAllocator allocator = {allocate, release, &probe}; assert(decoder_create(allocator) == NULL && probe.live == 0); probe.fail = 0; Decoder *decoder = decoder_create(allocator); assert(decoder != NULL && probe.live == 1 && probe.calls == 2); size_t allocations = probe.calls; unsigned char encoded[10]; memset(encoded, 0xaa, sizeof encoded); size_t written = 77; assert(!telemetry_encode((Reading){0,25}, encoded, sizeof encoded, &written)); assert(written == 77); for (size_t i = 0; i < sizeof encoded; ++i) { assert(encoded[i] == 0xaa); } assert(!telemetry_encode((Reading){1,25}, encoded, 9, &written) && written == 77); assert(!telemetry_encode((Reading){4096,25}, encoded, 10, &written)); assert(!telemetry_encode((Reading){1,10001}, encoded, 10, &written)); assert(telemetry_encode((Reading){1,25}, encoded, sizeof encoded, &written)); assert(written == 10 && memcmp(encoded, fixture, 10) == 0); Reading sentinel = {77,88}; FeedResult empty = decoder_feed(decoder, NULL, 0, &sentinel); assert(empty.status == NEED_MORE && empty.consumed == 0); assert(sentinel.sensor == 77 && sentinel.value == 88); assert(decoder_finish(decoder) == STREAM_END); unsigned char stream[20]; memcpy(stream, fixture, 10); memcpy(stream + 10, fixture, 10); for (size_t chunk = 1; chunk <= 20; ++chunk) { decode_chunks(decoder, stream, 20, chunk); } /* Every possible partition of a single 10-byte frame (2^9 cases). */ for (unsigned mask = 0; mask < 512; ++mask) { decoder_reset(decoder); size_t start = 0; for (size_t end = 1; end <= 10; ++end) { if (end == 10 || (mask & (1u << (end - 1))) != 0) { Reading out = {77,88}; FeedResult result = decoder_feed(decoder, fixture + start, end - start, &out); assert(result.consumed == end - start); if (end == 10) { assert(result.status == FRAME_READY && out.sensor == 1 && out.value == 25); } else { assert(result.status == NEED_MORE && out.sensor == 77 && out.value == 88); } start = end; } } assert(decoder_finish(decoder) == STREAM_END); } for (size_t length = 1; length < 10; ++length) { decoder_reset(decoder); Reading out = {77,88}; FeedResult result = decoder_feed(decoder, fixture, length, &out); assert(result.status == NEED_MORE && result.consumed == length); assert(decoder_finish(decoder) == DECODE_ERROR); result = decoder_feed(decoder, fixture, 10, &out); assert(result.status == DECODE_ERROR && result.consumed == 0); assert(out.sensor == 77 && out.value == 88); } for (size_t byte = 0; byte < 10; ++byte) { unsigned char corrupt[10]; memcpy(corrupt, fixture, 10); corrupt[byte] ^= 1; decoder_reset(decoder); Reading out = {77,88}; FeedResult result = decoder_feed(decoder, corrupt, 10, &out); assert(result.status == DECODE_ERROR && result.consumed > 0 && result.consumed <= 10); assert(out.sensor == 77 && out.value == 88); assert(decoder_finish(decoder) == DECODE_ERROR); result = decoder_feed(decoder, fixture, 10, &out); assert(result.status == DECODE_ERROR && result.consumed == 0); } /* Repair checksums after metadata changes to test semantic rejection independently. */ const size_t metadata[] = {0,1,2,4}; for (size_t i = 0; i < sizeof metadata / sizeof metadata[0]; ++i) { unsigned char changed[10]; memcpy(changed, fixture, 10); changed[metadata[i]] ^= 1; changed[9] = 0; for (size_t j = 0; j < 9; ++j) { changed[9] = (unsigned char)(changed[9] + changed[j]); } decoder_reset(decoder); Reading out = {77,88}; assert(decoder_feed(decoder, changed, 10, &out).status == DECODE_ERROR); assert(out.sensor == 77 && out.value == 88); } /* Domain-invalid payload with a correct checksum, rather than checksum-only failure. */ unsigned char invalid[10]; memcpy(invalid, fixture, 10); invalid[6] = 0; invalid[9]--; decoder_reset(decoder); Reading out = {77,88}; assert(decoder_feed(decoder, invalid, 10, &out).status == DECODE_ERROR); assert(out.sensor == 77 && out.value == 88); for (unsigned sensor = 1; sensor <= 4095; sensor += 683) { for (unsigned value = 0; value <= 10000; value += 2500) { decoder_reset(decoder); Reading input = {(uint_least16_t)sensor,(uint_least16_t)value}; assert(telemetry_encode(input, encoded, sizeof encoded, &written)); FeedResult result = decoder_feed(decoder, encoded, written, &out); assert(result.status == FRAME_READY && result.consumed == written); assert(out.sensor == input.sensor && out.value == input.value); } } decoder_reset(decoder); assert(telemetry_encode((Reading){4095,10000}, encoded,10,&written)); assert(decoder_feed(decoder,encoded,10,&out).status == FRAME_READY); assert(out.sensor == 4095 && out.value == 10000); assert(probe.calls == allocations && probe.live == 1); /* feed/reset/finish do not allocate. */ decoder_destroy(decoder); decoder_destroy(NULL); assert(probe.live == 0); puts("Telemetry checks passed"); return 0; } #include "telemetry.h" #include <stdlib.h> #include <string.h> struct Decoder { unsigned char frame[5 + TELEMETRY_PAYLOAD_LIMIT + 1]; size_t used; int failed; TelemetryAllocator allocator; }; static void *default_allocate(void *context, size_t bytes) { (void)context; return malloc(bytes); } static void default_deallocate(void *context, void *storage) { (void)context; free(storage); } TelemetryAllocator telemetry_default_allocator(void) { TelemetryAllocator allocator = {default_allocate, default_deallocate, NULL}; return allocator; } Decoder *decoder_create(TelemetryAllocator allocator) { if (allocator.allocate == NULL || allocator.deallocate == NULL) { return NULL; } Decoder *decoder = allocator.allocate(allocator.context, sizeof *decoder); if (decoder == NULL) { return NULL; } decoder->allocator = allocator; decoder_reset(decoder); return decoder; } void decoder_destroy(Decoder *decoder) { if (decoder != NULL) { decoder->allocator.deallocate(decoder->allocator.context, decoder); } } void decoder_reset(Decoder *decoder) { decoder->used = 0; decoder->failed = 0; } static unsigned long read_u16(const unsigned char *bytes) { return ((unsigned long)bytes[0] << 8) | (unsigned long)bytes[1]; } static void write_u16(unsigned char *bytes, unsigned long value) { bytes[0] = (unsigned char)(value >> 8); bytes[1] = (unsigned char)(value & 255UL); } static unsigned char checksum(const unsigned char *bytes, size_t size) { unsigned char sum = 0; for (size_t i = 0; i < size; ++i) { sum = (unsigned char)(sum + bytes[i]); } return sum; } int telemetry_encode(Reading record, unsigned char *out, size_t capacity, size_t *written) { if (out == NULL || written == NULL || capacity < TELEMETRY_FRAME_SIZE || record.sensor < 1 || record.sensor > 4095 || record.value > 10000) { return 0; } unsigned char frame[TELEMETRY_FRAME_SIZE] = {0x54, 1, 1, 0, 4, 0, 0, 0, 0, 0}; write_u16(frame + 5, record.sensor); write_u16(frame + 7, record.value); frame[9] = checksum(frame, 9); memcpy(out, frame, sizeof frame); *written = sizeof frame; return 1; } static FeedResult fail(Decoder *decoder, size_t consumed) { decoder->failed = 1; FeedResult result = {DECODE_ERROR, consumed}; return result; } FeedResult decoder_feed(Decoder *decoder, const unsigned char *bytes, size_t size, Reading *out) { if (decoder->failed) { FeedResult result = {DECODE_ERROR, 0}; return result; } if (out == NULL || (bytes == NULL && size != 0)) { return fail(decoder, 0); } size_t consumed = 0; while (consumed < size) { /* used is bounded by header validation before payload accumulation. */ decoder->frame[decoder->used++] = bytes[consumed++]; if (decoder->used == 1 && decoder->frame[0] != 0x54) { return fail(decoder, consumed); } if (decoder->used == 5) { unsigned long length = read_u16(decoder->frame + 3); if (decoder->frame[1] != 1 || decoder->frame[2] != 1 || length > TELEMETRY_PAYLOAD_LIMIT || length != 4) { return fail(decoder, consumed); } } if (decoder->used == TELEMETRY_FRAME_SIZE) { if (checksum(decoder->frame, 9) != decoder->frame[9]) { return fail(decoder, consumed); } Reading candidate = {(uint_least16_t)read_u16(decoder->frame + 5), (uint_least16_t)read_u16(decoder->frame + 7)}; if (candidate.sensor < 1 || candidate.sensor > 4095 || candidate.value > 10000) { return fail(decoder, consumed); } *out = candidate; decoder->used = 0; FeedResult result = {FRAME_READY, consumed}; return result; } } FeedResult result = {NEED_MORE, consumed}; return result; } DecodeStatus decoder_finish(Decoder *decoder) { if (decoder->failed || decoder->used != 0) { decoder->failed = 1; return DECODE_ERROR; } return STREAM_END; } #ifndef TELEMETRY_H #define TELEMETRY_H #include <limits.h> #include <stddef.h> #include <stdint.h> /* Wire octets require an 8-bit unsigned char. No native struct layout is serialized. */ _Static_assert(CHAR_BIT == 8, "Telemetry format requires 8-bit bytes"); #define TELEMETRY_PAYLOAD_LIMIT 16 #define TELEMETRY_FRAME_SIZE 10 typedef struct { uint_least16_t sensor; uint_least16_t value; } Reading; typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR, STREAM_END } DecodeStatus; typedef struct { DecodeStatus status; size_t consumed; } FeedResult; typedef void *(*AllocateFn)(void *context, size_t bytes); typedef void (*DeallocateFn)(void *context, void *storage); typedef struct { AllocateFn allocate; DeallocateFn deallocate; void *context; } TelemetryAllocator; typedef struct Decoder Decoder; TelemetryAllocator telemetry_default_allocator(void); /* allocator callbacks/context must remain valid until destroy. NULL on failure. One bounded allocation at creation; feed/reset/finish never allocate. */ Decoder *decoder_create(TelemetryAllocator allocator); void decoder_destroy(Decoder *decoder); /* NULL is allowed; other handles exactly once. */ void decoder_reset(Decoder *decoder); /* Requires non-NULL decoder/out; bytes may be NULL only for size zero. Processes at most one frame; caller advances by consumed, then feeds remaining bytes. NEED_MORE consumes all supplied bytes, FRAME_READY consumes through one checksum. Error is sticky until reset. Output changes only on FRAME_READY. Input is borrowed only during this call. Output is a caller-owned value. Decoder, input and output storage must not overlap. */ FeedResult decoder_feed(Decoder *decoder, const unsigned char *bytes, size_t size, Reading *out); /* Check end-of-input: STREAM_END on a clean boundary; partial frame becomes sticky error. A clean finish is a check, not a close: later feed is permitted. */ DecodeStatus decoder_finish(Decoder *decoder); /* Record: sensor 1..4095, value 0..10000. Encoder validates before writing. Requires non-NULL out/written and nonoverlapping record/out/written storage. Failure leaves output bytes and written unchanged. Capacity must be >=10. */ int telemetry_encode(Reading record, unsigned char *out, size_t capacity, size_t *written); #endif
Check your prediction
Text
Telemetry checks passed

Find the assertions for consumed counts and output sentinels in test_telemetry.c. Then replace the checksum comparison in telemetry.c with if (0), predict which loop fails first, and run. Header flips are still rejected by the header checks, but the single-byte corruption loop's first payload flip, byte 5, turns sensor 1 into sensor 257. That is a valid sensor, so with the checksum gone the frame decodes and the assertion on DECODE_ERROR fires. Restore the line before trying the next mutation. Do not rely on the exact wording of assertion messages, which varies between C libraries.

Was this article helpful?

Your response is saved on this device.