tests/sims/paging.test.ts
The automated tests for the /simulators/page-replacement simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.
- Silberschatz reference string with 3 frames: FIFO 15, LRU 12, OPT 9 faults.
- Bélády’s anomaly: FIFO on 1,2,3,4,1,2,5,1,2,3,4,5 has 9 faults with 3 frames and 10 with 4.
- OPT equals the brute-force minimum, no policy beats it, and LRU and OPT never show the anomaly.
// /simulators/page-replacement
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { run, curve, minimumFaults, rng, DEFAULTS, type Policy } from '../../src/lib/sims/paging.ts';
import { checker } from './check.ts';
const faults = (p: Policy, refs: number[], frames: number) => run(p, refs, { ...DEFAULTS, frames }).faults;
test('Silberschatz reference string with 3 frames: FIFO 15, LRU 12, OPT 9 faults', () => {
const S = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1];
assert.equal(faults('fifo', S, 3), 15);
assert.equal(faults('lru', S, 3), 12);
assert.equal(faults('opt', S, 3), 9);
});
test('Bélády’s anomaly: FIFO on 1,2,3,4,1,2,5,1,2,3,4,5 has 9 faults with 3 frames and 10 with 4', () => {
const B = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5];
assert.equal(faults('fifo', B, 3), 9);
assert.equal(faults('fifo', B, 4), 10);
});
test('OPT equals the brute-force minimum, no policy beats it, and LRU and OPT never show the anomaly', () => {
const { ok, done } = checker();
const r = rng(3);
for (let k = 0; k < 2000; k++) {
const len = 6 + Math.floor(r() * 10), pages = 3 + Math.floor(r() * 4);
const refs = Array.from({ length: len }, () => Math.floor(r() * pages));
for (let fr = 1; fr <= 4; fr++) {
const opt = faults('opt', refs, fr);
ok(opt === minimumFaults(refs, fr), `OPT ${opt} vs minimum ${minimumFaults(refs, fr)} on ${refs} with ${fr} frames`);
for (const p of ['fifo', 'lru', 'clock'] as const) ok(faults(p, refs, fr) >= opt, `${p} beat OPT`);
const rr = run('clock', refs, { ...DEFAULTS, frames: fr });
ok(rr.faults + rr.hits === len, 'faults + hits is not the string length');
}
for (const p of ['lru', 'opt'] as const) ok(curve(p, refs, 6).anomalies.length === 0, `${p} showed Bélády’s anomaly`);
}
done();
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.