A cache can pass isolated set and get tests while evicting the wrong entry after a read. Test sequences against a small independent model and compare observable state after every operation. A deliberately broken read-refresh behavior can show whether the harness exercises the policy it claims to protect.
This Node.js 24 exercise explores a bounded operation space for a two-entry least-recently-used cache. It is a dependency-free teaching fixture, not a general cache library or a concurrency proof. Values are fixed non-undefined integers so a missing lookup has an unambiguous result.
Define the state that readers can observe
The contract orders keys from least to most recently used. Setting a key makes it most recent. Reading an existing key also makes it most recent. Inserting a third distinct key evicts the least recent one. Reading a missing key returns undefined without changing order.
Expose the ordered keys only as a testing observation here. A real implementation may instead expose policy-relevant behavior through a sequence of reads and evictions. Avoid inspecting private nodes merely because doing so makes assertions convenient; the reference model should check the promised behavior.
The fast-check project's model-based testing guide explains comparison between modeled commands and a real system. Its generators and shrinking machinery can extend this idea to larger spaces. The example below uses exhaustive short sequences so it needs neither that dependency nor a claim about randomized coverage.
Use a different representation for the model
Save this JavaScript in cache-model.mjs. The fixture implementation uses a Map. Its optional switch creates a deliberate mutant for the test demonstration; it is not a proposed product configuration:
import assert from "node:assert/strict";
function makeCache(refreshReads = true) {
const values = new Map();
return {
get(key) {
if (!values.has(key)) return undefined;
const value = values.get(key);
if (refreshReads) {
values.delete(key);
values.set(key, value);
}
return value;
},
set(key, value) {
values.delete(key);
values.set(key, value);
if (values.size > 2) values.delete(values.keys().next().value);
},
keys() {
return [...values.keys()];
}
};
}
function check(sequence, refreshReads = true) {
const cache = makeCache(refreshReads);
const model = [];
for (const [operation, key, value] of sequence) {
const index = model.findIndex(entry => entry[0] === key);
if (operation === "set") {
if (index !== -1) model.splice(index, 1);
model.push([key, value]);
if (model.length > 2) model.shift();
cache.set(key, value);
} else {
const entry = index === -1 ? undefined : model[index];
if (entry !== undefined) {
model.splice(index, 1);
model.push(entry);
}
assert.equal(cache.get(key), entry?.[1]);
}
assert.deepEqual(cache.keys(), model.map(entry => entry[0]));
}
}
The model keeps an explicit ordered array of pairs. It shares the contract with the implementation but does not call the implementation's ordering helpers. Copying the same helper into both sides would let a shared defect agree with itself.
Comparing order after each operation localizes failure earlier than waiting for a later eviction. Also compare returned values: a cache with correct-looking key order can still return the wrong payload. The test's observation set must cover both membership policy and lookup results.
Explore a declared finite operation space
Append the exploration and mutant check:
const actions = [["set", "a", 1], ["set", "b", 2], ["set", "c", 3], ["get", "a"]];
let tested = 0;
function explore(sequence = []) {
check(sequence);
tested += 1;
if (sequence.length === 4) return;
for (const action of actions) explore([...sequence, action]);
}
explore();
assert.equal(tested, 341);
assert.throws(() => check([
["set", "a", 1],
["set", "b", 2],
["get", "a"],
["set", "c", 3]
], false), assert.AssertionError);
Run node cache-model.mjs. The working implementation should pass every sequence. The mutant must raise an assertion that the outer negative check catches. Without read refresh, reading a leaves its order stale. The immediate order assertion detects that divergence before the final insertion could evict the wrong key.
The count is derived from the chosen search: one empty sequence plus 4, 16, 64, and 256 sequences of lengths one through four. It is not an estimate of real application reliability. The fixture checks exactly this finite alphabet, depth, capacity, and value set.
Retain the failure as a focused regression
Keep a short failing sequence as a named regression case after fixing a real defect. A small example explains the contract to future maintainers and survives changes to generator settings. If a randomized system finds the sequence, retain the seed, path, and replay information required by that runner.
When reducing a failure, preserve the preconditions that make the operation meaningful. Removing an earlier insertion can turn an existing-key read into a missing-key read and erase the policy under investigation. Verify the reduced sequence against both the repaired implementation and the known defect so it remains a discriminating regression case.
Expand the model at its declared limits
Expand the model for contracts not covered here: overwriting with a different value, deleting keys, zero capacity, expiration, or concurrent access. Each added operation needs defined semantics and an observation that can distinguish a correct transition from an incorrect one. Adding random calls without a corresponding oracle increases activity without establishing coverage.
Test cleanup and asynchronous scheduling separately if the real cache owns timers or background work. This synchronous model does not validate those lifetimes, even when its sequence count is large. The controlled-clock guide supplies the separate timer-testing boundary.
The useful completion evidence is the combination of a declared operation space, an independently represented model, stepwise observations, and a defect the harness demonstrably rejects. If the mutant still passes, repair the test's observation or command space before trusting a green run from the intended implementation.
Was this guide useful?
Your rating helps us prioritize clearer, more practical technical content.
Review diffs, run checks, and prepare the release in Arezgit.
Keep Git review, security scanning, API checks, database inspection, and release preparation together in one local desktop application.
Explore Arezgit