mvp-ai's picture
download
raw
7.28 kB
// Copyright (c) 2026 the Zuke contributors
// SPDX-License-Identifier: MIT
/**
* Shared harness for the in-process integration suite. Drives a real build
* through the CLI `main()` entry point — the same path the `zuke` command uses
* — capturing its console output and, when needed, giving it an isolated,
* temporary state directory. `main` returns an exit code rather than calling
* `Deno.exit`, so a whole build runs end-to-end inside one test.
*
* @module
*/
import { main, type MainOptions } from "../../packages/core/src/cli.ts";
import type { Build } from "../../packages/core/mod.ts";
import { defaultGraphHost } from "../../packages/core/src/graph_view.ts";
/** Swallow the browser open; see the note in `runCli`. */
function noOpen(): Promise<void> {
return Promise.resolve();
}
/** The captured result of one {@link runCli} invocation. */
export interface CliResult {
/** The exit code `main` resolved to (0 success, 1 failure). */
code: number;
/** Lines written to `console.log`, joined by newlines. */
out: string;
/** Lines written to `console.error`, joined by newlines. */
err: string;
}
/**
* Run `BuildClass` through the real CLI `main()` with `args`, capturing
* `console.log`/`console.error` instead of printing them. Does not manage the
* state directory: wrap the call in {@link withStateDir} for builds that use
* `waitsFor()`/`lock()` so their run records land in a temp dir, not the repo.
*/
export async function runCli(
BuildClass: new () => Build,
args: string[],
options: MainOptions = {},
): Promise<CliResult> {
// Never let a test reach the real browser opener. `zuke graph` defaults
// `--open` to true, so a test that forgets `--no-open` spawns the OS opener on
// whoever is running the suite — and then deletes the temp directory, so the
// tab shows nothing. Defaulting the injectable host here means a missing flag
// cannot do that, rather than every future test having to remember.
// A caller's own host is used as given — never spread into a literal, which
// would copy its own fields and drop every method on its prototype, quietly
// substituting the real implementations for a fake's.
const opts: MainOptions = options.graphHost !== undefined
? options
: { ...options, graphHost: { ...defaultGraphHost, open: noOpen } };
const out: string[] = [];
const err: string[] = [];
const origLog = console.log;
const origErr = console.error;
console.log = (...a: unknown[]) => void out.push(a.join(" "));
console.error = (...a: unknown[]) => void err.push(a.join(" "));
// Guard the async-safety fixes: a promise rejection that escapes the run
// (e.g. a scheduler path that dropped its `.catch`) must fail the test
// explicitly, not merely rely on the Deno runner's default handling — which
// this pins even if that default changes. We take ownership of the event
// (preventDefault) so the check below is authoritative; a rejection firing
// after this call (listener already removed) still falls back to the runner.
const rejections: unknown[] = [];
const onRejection = (event: PromiseRejectionEvent) => {
event.preventDefault();
rejections.push(event.reason);
};
addEventListener("unhandledrejection", onRejection);
try {
const code = await main(BuildClass, args, opts);
// A macrotask boundary so any queued unhandledrejection event has dispatched
// before we inspect — it fires at a microtask checkpoint, which setTimeout(0)
// is guaranteed to follow.
await new Promise<void>((resolve) => setTimeout(resolve, 0));
if (rejections.length > 0) {
const reasons = rejections
.map((r) => (r instanceof Error ? r.message : String(r)))
.join("; ");
throw new Error(`unhandled promise rejection during runCli: ${reasons}`);
}
return { code, out: out.join("\n"), err: err.join("\n") };
} finally {
removeEventListener("unhandledrejection", onRejection);
console.log = origLog;
console.error = origErr;
}
}
/**
* Run `fn` with a fresh temporary `ZUKE_STATE_DIR` so durable-state features
* (`waitsFor()`, `lock()`, run records) persist to a throwaway directory shared
* across every {@link runCli} call inside `fn` — the seam that lets one test
* suspend a run and a later call resume it. Restores the previous env var and
* removes the directory afterwards, even on failure.
*/
/**
* Run `fn` with **no** state store configured, whatever the ambient
* environment says.
*
* A test asserting store-less behaviour is otherwise at the mercy of a
* developer's or a runner's `ZUKE_STATE_DIR`: the run quietly gets a real
* store, the premise evaporates, and the test either fails for a reason that
* has nothing to do with it or passes while proving something else.
*/
export async function withoutStateDir(fn: () => Promise<void>): Promise<void> {
const prev = Deno.env.get("ZUKE_STATE_DIR");
const prevUrl = Deno.env.get("ZUKE_STATE_URL");
Deno.env.delete("ZUKE_STATE_DIR");
Deno.env.delete("ZUKE_STATE_URL");
try {
await fn();
} finally {
if (prev !== undefined) Deno.env.set("ZUKE_STATE_DIR", prev);
if (prevUrl !== undefined) Deno.env.set("ZUKE_STATE_URL", prevUrl);
}
}
export async function withStateDir(
fn: (dir: string) => Promise<void>,
): Promise<void> {
const dir = await Deno.makeTempDir({ prefix: "zuke-it-" });
const prev = Deno.env.get("ZUKE_STATE_DIR");
Deno.env.set("ZUKE_STATE_DIR", dir);
try {
await fn(dir);
} finally {
if (prev === undefined) Deno.env.delete("ZUKE_STATE_DIR");
else Deno.env.set("ZUKE_STATE_DIR", prev);
// Best-effort cleanup: a removal error (e.g. a Windows file lock) must never
// replace the test's own assertion failure, which is the error worth seeing.
try {
await Deno.remove(dir, { recursive: true });
} catch {
// ignore — the temp dir is throwaway; masking the real error is worse.
}
}
}
/**
* The host a request went to, for a test routing or filtering a fake `fetch`.
*
* Parsed and compared whole rather than matched with `url.includes(host)`: a
* substring test also matches a URL that merely mentions the host somewhere
* else, such as a query parameter, so it is the wrong test even where every
* input is one the test itself produced.
*
* Shared here rather than kept per file because it had already been written
* twice, and the second copy went back to the substring form — which is the
* way this particular mistake recurs.
*/
export function hostOf(url: string): string {
return new URL(url).hostname;
}
/**
* Strip the `::add-mask::` directives from captured output.
*
* Under GitHub Actions the executor deliberately emits `::add-mask::` followed by
* the *raw* secret through the un-redacted base reporter, so the runner censors
* the value in its own logs — a redacted directive would mask nothing. That line
* is the one sanctioned place the raw value appears, so it is removed here before
* asserting the secret shows up nowhere else. Everything else stays in scope.
*/
export function withoutMaskDirectives(output: string): string {
return output
.split("\n")
.filter((line) => !line.trimStart().startsWith("::add-mask::"))
.join("\n");
}

Xet Storage Details

Size:
7.28 kB
·
Xet hash:
a45a69142b2007d79a379563bb6117d85219649f8d781862b2e5110bcebd0eac

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.