About: how pages are checked

tests/sims/traversal.test.ts

The automated tests for the /simulators/bfs-dfs-traversal 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. On 3,000 random graphs, BFS depths are shortest hop counts and every reachable node is visited once.
  2. The stack-based DFS visits nodes in the same order as plain recursive DFS, and builds a valid DFS tree.
// /simulators/bfs-dfs-traversal: breadth-first and depth-first search, against independent versions.
import { test } from 'node:test';
import { traverse, makeGraph, recursiveDfs, isDfsTree } from '../../src/lib/sims/traversal.ts';
import { checker, lcg } from './check.ts';

function graphs(count: number) {
	const r = lcg(9);
	return Array.from({ length: count }, () => {
		const n = 2 + Math.floor(r() * 18), p = r() * 0.4, edges: [number, number][] = [];
		for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) if (r() < p) edges.push([a, b]);
		const g = makeGraph(Array.from({ length: n }, (_, i) => String(i)), Array.from({ length: n }, () => [0, 0] as [number, number]), edges);
		return { g, n, s: Math.floor(r() * n) };
	});
}
const bfsDist = (g: { n: number; adj: number[][] }, s: number) => {
	const d = Array(g.n).fill(-1);
	d[s] = 0;
	const q = [s];
	for (let k = 0; k < q.length; k++) for (const v of g.adj[q[k]]) if (d[v] < 0) { d[v] = d[q[k]] + 1; q.push(v); }
	return d;
};

test('on 3,000 random graphs, BFS depths are shortest hop counts and every reachable node is visited once', () => {
	const { ok, done } = checker();
	for (const { g, s } of graphs(3000)) {
		const b = traverse(g, s, 'bfs'), ref = bfsDist(g, s);
		ok(b.depth.join() === ref.join(), `BFS depths from ${s}`);
		ok(new Set(b.order).size === b.order.length && b.order.length === ref.filter((x) => x >= 0).length, `BFS visit count from ${s}`);
	}
	done();
});

test('the stack-based DFS visits nodes in the same order as plain recursive DFS, and builds a valid DFS tree', () => {
	const { ok, done } = checker();
	for (const { g, n, s } of graphs(3000)) {
		const d = traverse(g, s, 'dfs');
		ok(d.order.join() === recursiveDfs(g, s).join(), `DFS order from ${s}`);
		ok(isDfsTree(g, d.parent, (v) => d.disc[v] >= 0), `DFS tree from ${s}`);
		for (let v = 0; v < n; v++) if (d.disc[v] >= 0 && d.parent[v] >= 0) {
			const u = d.parent[v];
			ok(d.disc[u] < d.disc[v] && d.fin[v] < d.fin[u], `discovery/finish times of ${u} do not enclose ${v}`);
		}
	}
	done();
});

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

Published