1
0
forked from rosa/hakurei
Files
hakurei/cmd/pkgserver/ui/static/test.ts

282 lines
8.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// =============================================================================
// DSL
type TestTree = TestGroup | Test;
type TestGroup = { name: string, children: TestTree[] };
type Test = { name: string, test: (TestController) => void };
let TESTS: TestGroup[] = [];
export function suite(name: string, children: TestTree[]) {
checkDuplicates(name, children);
TESTS.push({ name, children });
}
export function context(name: string, children: TestTree[]): TestTree {
checkDuplicates(name, children);
return { name, children };
}
export const group = context;
export function test(name: string, test: (TestController) => void): TestTree {
return { name, test };
}
function checkDuplicates(parent: string, names: { name: string }[]) {
let seen = new Set<string>();
for (const { name } of names) {
if (seen.has(name)) {
throw new RangeError(`duplicate name '${name}' in '${parent}'`);
}
seen.add(name);
}
}
class FailNowSentinel {}
export class TestController {
logs: string[];
#failed: boolean;
constructor() {
this.logs = [];
this.#failed = false;
}
fail() {
this.#failed = true;
}
failed(): boolean {
return this.#failed;
}
failNow(): never {
this.fail();
throw new FailNowSentinel();
}
log(message: string) {
this.logs.push(message);
}
error(message: string) {
this.log(message);
this.fail();
}
fatal(message: string): never {
this.log(message);
this.failNow();
}
}
// =============================================================================
// Execution
export interface TestResult {
success: boolean;
logs: string[];
}
export function run(reporter: Reporter) {
reporter.register(TESTS);
for (const suite of TESTS) {
for (const c of suite.children) runTests(reporter, [suite.name], c);
}
reporter.finalize();
}
function runTests(reporter: Reporter, parents: string[], node: TestTree) {
const path = [...parents, node.name];
if ("children" in node) {
for (const c of node.children) runTests(reporter, path, c);
return;
}
let controller = new TestController();
try {
node.test(controller);
} catch (e) {
if (!(e instanceof FailNowSentinel)) {
controller.error(extractExceptionString(e));
}
}
reporter.update(path, { success: !controller.failed(), logs: controller.logs });
}
function extractExceptionString(e: any): string {
// String() instead of .toString() as null and undefined don't have
// properties.
const s = String(e);
if (!(e instanceof Error && "stack" in e)) return s;
// v8 (Chromium, NodeJS) include the error message, while Firefox and WebKit
// do not.
if (e.stack.startsWith(s)) return e.stack;
return `${s}\n${e.stack}`;
}
// =============================================================================
// Reporting
export interface Reporter {
register(suites: TestGroup[]): void
update(path: string[], result: TestResult): void;
finalize(): void;
}
export interface Stream {
writeln(s: string): void;
}
const SEP = " ";
export class StreamReporter implements Reporter {
stream: Stream;
verbose: boolean;
#failures: ({ path: string[] } & TestResult)[];
counts: { successes: number, failures: number };
constructor(stream: Stream, verbose: boolean = false) {
this.stream = stream;
this.verbose = verbose;
this.#failures = [];
this.counts = { successes: 0, failures: 0 };
}
register(suites: TestGroup[]) {}
update(path: string[], result: TestResult) {
if (path.length === 0) throw new RangeError("path is empty");
const pathStr = path.join(SEP);
if (result.success) {
this.counts.successes++;
if (this.verbose) this.stream.writeln(`✅️ ${pathStr}`);
} else {
this.counts.failures++;
this.stream.writeln(`⚠️ ${pathStr}`);
this.#failures.push({ path, ...result });
}
}
finalize() {
// Transform [{ path: ["a", "b", "c"] }, { path: ["a", "b", "d"] }]
// into { "a b": ["c", "d"] }.
let pathMap = new Map<string, ({ name: string } & TestResult)[]>();
for (const f of this.#failures) {
const key = f.path.slice(0, -1).join(SEP);
if (!pathMap.has(key)) pathMap.set(key, []);
pathMap.get(key).push({ name: f.path.at(-1), ...f });
}
this.stream.writeln("");
this.stream.writeln("FAILURES");
this.stream.writeln("========");
for (const [path, tests] of pathMap) {
if (tests.length === 1) {
this.#writeOutput(tests[0], path ? `${path}${SEP}` : "", false);
} else {
this.stream.writeln(path);
for (const t of tests) this.#writeOutput(t, " - ", true);
}
}
this.stream.writeln("");
const { successes, failures } = this.counts;
this.stream.writeln(`${successes} succeeded, ${failures} failed`);
}
#writeOutput(test: { name: string } & TestResult, prefix: string, nested: boolean) {
let output = "";
if (test.logs.length) {
// Individual logs might span multiple lines, so join them together
// then split it again.
const logStr = test.logs.join("\n");
const lines = logStr.split("\n");
if (lines.length <= 1) {
output = `: ${logStr}`;
} else {
const padding = nested ? " " : " ";
output = ":\n" + lines.map((line) => padding + line).join("\n");
}
}
this.stream.writeln(`${prefix}${test.name}${output}`);
}
}
export class DOMReporter implements Reporter {
register(suites: TestGroup[]) {}
update(path: string[], result: TestResult) {
if (path.length === 0) throw new RangeError("path is empty");
const counter = document.getElementById(result.success ? "successes" : "failures");
counter.innerText = (Number(counter.innerText) + 1).toString();
let parent = document.getElementById("root");
for (const node of path) {
let child = null;
outer: for (const d of parent.children) {
for (const s of d.children) {
if (!(s instanceof HTMLElement)) continue;
if (s.tagName !== "SUMMARY" || s.innerText !== node) continue;
child = d;
break outer;
}
}
if (child === null) {
child = document.createElement("details");
child.className = "test-node";
const summary = document.createElement("summary");
summary.appendChild(document.createTextNode(node));
child.appendChild(summary);
parent.appendChild(child);
}
if (!result.success) {
child.open = true;
child.classList.add("failure");
}
parent = child;
}
const p = document.createElement("p");
p.classList.add("test-desc");
if (result.logs.length) {
const pre = document.createElement("pre");
pre.appendChild(document.createTextNode(result.logs.join("\n")));
p.appendChild(pre);
} else {
p.classList.add("italic");
p.appendChild(document.createTextNode("No output."));
}
parent.appendChild(p);
}
finalize() {}
}
interface GoNode {
name: string;
subtests?: GoNode[];
}
// Used to display results via `go test`, via some glue code from the Go side.
export class GoTestReporter implements Reporter {
// Convert a test tree into the one expected by the Go code.
static serialize(node: TestTree): GoNode {
return {
name: node.name,
subtests: "children" in node ? node.children.map(GoTestReporter.serialize) : null,
};
}
register(suites: TestGroup[]) {
console.log(JSON.stringify(suites.map(GoTestReporter.serialize)));
}
update(path: string[], result: TestResult) {
console.log(JSON.stringify({ path: path, ...result }));
}
finalize() {
console.log("null");
}
}