About: how pages are checked

tests/sims/bankers.test.ts

The automated tests for the /simulators/bankers-algorithm 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.

  1. Safety verdicts and safe-sequence counts match trying every order.
  2. The Silberschatz example: safe, and P1 asking for (1,0,2) is granted.
// /simulators/bankers-algorithm
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { safety, request, checkSequence, countSafe, need, rng, type State } from '../../src/lib/sims/bankers.ts';
import { checker } from './check.ts';

function perms(n: number): number[][] {
	if (n === 0) return [[]];
	const out: number[][] = [];
	for (const p of perms(n - 1)) for (let i = 0; i <= p.length; i++) out.push([...p.slice(0, i), n - 1, ...p.slice(i)]);
	return out;
}

test('safety verdicts and safe-sequence counts match trying every order', () => {
	const { ok, done } = checker();
	const r = rng(4);
	for (let k = 0; k < 3000; k++) {
		const n = 2 + Math.floor(r() * 5), m = 1 + Math.floor(r() * 3);
		const max = Array.from({ length: n }, () => Array.from({ length: m }, () => Math.floor(r() * 7)));
		const alloc = max.map((row) => row.map((v) => Math.floor(r() * (v + 1))));
		const avail = Array.from({ length: m }, () => Math.floor(r() * 5));
		const s: State = { alloc, max, avail };
		const valid = perms(n).filter((p) => checkSequence(s, p).valid);
		for (const scan of ['restart', 'continue'] as const) {
			const sf = safety(s, scan);
			ok(sf.safe === valid.length > 0, `verdict, case ${k}`);
			if (sf.safe) ok(checkSequence(s, sf.sequence).valid, `sequence, case ${k}`);
		}
		ok(countSafe(s) === valid.length, `count ${countSafe(s)} vs ${valid.length}`);
		const p = Math.floor(r() * n);
		const rq = request(s, p, need(s)[p].map((v) => Math.floor(r() * (v + 1))));
		if (rq.outcome === 'granted') ok(safety(rq.state).safe, `granted request left an unsafe state, case ${k}`);
	}
	done();
});

test('the Silberschatz example: safe, and P1 asking for (1,0,2) is granted', () => {
	const T: State = { alloc: [[0, 1, 0], [2, 0, 0], [3, 0, 2], [2, 1, 1], [0, 0, 2]], max: [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]], avail: [3, 3, 2] };
	assert.equal(safety(T).safe, true);
	assert.equal(checkSequence(T, [1, 3, 4, 2, 0]).valid, true);
	const g = request(T, 1, [1, 0, 2]);
	assert.equal(g.outcome, 'granted');
	// after that grant, P4 asking for (3,3,0) has to wait and P0 asking for (0,2,0) would be unsafe
	assert.notEqual(request(g.state, 4, [3, 3, 0]).outcome, 'granted');
	assert.notEqual(request(g.state, 0, [0, 2, 0]).outcome, 'granted');
});

Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.

Published