About: how pages are checked

tests/sims/heap.test.ts

The automated tests for the /simulators/heap 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. After every insert the array is the one Python's heapq builds, and pops come out in sorted order.
  2. Bottom-up heapify makes a valid heap in under 2n comparisons, and heapsort sorts.
// /simulators/heap: binary heap insert, extract, heapify and heapsort.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { Heap } from '../../src/lib/sims/heap.ts';
import { lcg } from './check.ts';

let python = true;
try { execFileSync('python3', ['--version']); } catch { python = false; }

function cases() {
	const r = lcg(9);
	return Array.from({ length: 200 }, () => Array.from({ length: 1 + Math.floor(r() * 40) }, () => Math.floor(r() * 100)));
}

test('after every insert the array is the one Python\'s heapq builds, and pops come out in sorted order', { skip: !python && 'python3 is not installed' }, () => {
	const cs = cases();
	const py = JSON.parse(execFileSync('python3', ['-c', `
import heapq, json, sys
out = []
for c in json.loads(sys.stdin.read()):
    h = []; states = []
    for v in c: heapq.heappush(h, v); states.append(list(h))
    hm = []; mstates = []
    for v in c: heapq.heappush(hm, -v); mstates.append([-x for x in hm])
    pops = [heapq.heappop(h) for _ in range(len(h))]
    out.append({'states': states, 'mstates': mstates, 'pops': pops})
print(json.dumps(out))
`], { input: JSON.stringify(cs) }).toString());
	cs.forEach((c, k) => {
		for (const kind of ['min', 'max'] as const) {
			const h = new Heap(kind);
			c.forEach((v, i) => {
				h.insert(v);
				assert.deepEqual(h.a, kind === 'min' ? py[k].states[i] : py[k].mstates[i], `${kind} heap after inserting ${c.slice(0, i + 1)}`);
				assert.ok(h.valid());
			});
			const pops: number[] = [];
			for (;;) { const op = h.extract(); if (!op) break; pops.push(op.result!); assert.ok(h.valid()); }
			assert.deepEqual(pops, kind === 'min' ? py[k].pops : [...py[k].pops].reverse());
		}
	});
});

test('bottom-up heapify makes a valid heap in under 2n comparisons, and heapsort sorts', () => {
	for (const c of cases()) for (const kind of ['min', 'max'] as const) {
		const { heap, op } = Heap.build(kind, c);
		assert.ok(heap.valid(), `${kind} heapify of ${c}`);
		assert.ok(op.comparisons <= 2 * c.length, `${op.comparisons} comparisons for ${c.length} keys`);
		heap.sort();
		const sorted = [...c].sort((x, y) => x - y);
		assert.deepEqual(heap.a, kind === 'max' ? sorted : [...sorted].reverse());
	}
});

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

Published