Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

test(sdk): share temporary directory and subprocess fixtures (#1388)

mldangelo-oai5c46a3911bfe
diff --git a/sdk/typescript/scripts/release-automation.mjs b/sdk/typescript/scripts/release-automation.mjs
index 5fedf5139..bf8cbd517 100644
--- a/sdk/typescript/scripts/release-automation.mjs
+++ b/sdk/typescript/scripts/release-automation.mjs
@@ -43,6 +43,10 @@ function hasReviewedText(value) {
return !value.includes("\0") && /\S/u.test(value);
}
+/**
+ * @param {string} version
+ * @param {string} notes
+ */
export function parseReviewedReleaseNotes(version, notes) {
const expectedHeader = `<!-- release-version: ${version} -->`;
const normalized =
@@ -105,6 +109,10 @@ export function resolveReleaseSummary(version, taggedNotes, existingNotes) {
return extractHistoricalReleaseSummary(existingNotes);
}
+/**
+ * @param {string} generatedNotes
+ * @param {string | null} releaseSummary
+ */
export function composeReleaseNotes(generatedNotes, releaseSummary) {
if (releaseSummary === null || releaseSummary === "") {
return generatedNotes;
diff --git a/sdk/typescript/tests-ts/azure-pipelines-example.test.ts b/sdk/typescript/tests-ts/azure-pipelines-example.test.ts
index afd0eb70c..adc42cb28 100644
--- a/sdk/typescript/tests-ts/azure-pipelines-example.test.ts
+++ b/sdk/typescript/tests-ts/azure-pipelines-example.test.ts
@@ -1,13 +1,11 @@
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import {
existsSync,
mkdirSync,
- mkdtempSync,
readFileSync,
readdirSync,
- rmSync,
writeFileSync,
} from "node:fs";
-import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, test } from "bun:test";
import { parse } from "yaml";
@@ -46,21 +44,16 @@ const steps = job.steps.flatMap((step) =>
) as Step[];
const scan = steps.find((step) => step.name === "runScan")!;
const sarif = steps.find((step) => step.name === "exportSarif")!;
-const temporaryDirectories: string[] = [];
+const temporaryDirectories = createTemporaryDirectoriesSync();
-afterEach(() => {
- for (const directory of temporaryDirectories.splice(0)) {
- rmSync(directory, { recursive: true, force: true });
- }
-});
+afterEach(temporaryDirectories.cleanup);
function runStep(
step: Step,
overrides: Record<string, string> = {},
scanFiles: string[] = [],
) {
- const directory = mkdtempSync(join(tmpdir(), "codex azure example "));
- temporaryDirectories.push(directory);
+ const directory = temporaryDirectories.create("codex azure example ");
for (const child of ["repository with spaces", "scan", "reports"]) {
mkdirSync(join(directory, child));
}
diff --git a/sdk/typescript/tests-ts/candidate-normalizer.test.ts b/sdk/typescript/tests-ts/candidate-normalizer.test.ts
index 7c4d3a05b..b8a9038e0 100644
--- a/sdk/typescript/tests-ts/candidate-normalizer.test.ts
+++ b/sdk/typescript/tests-ts/candidate-normalizer.test.ts
@@ -1,17 +1,14 @@
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { spawnSync } from "node:child_process";
import {
existsSync,
mkdirSync,
- mkdtempSync,
readFileSync,
readdirSync,
- realpathSync,
- rmSync,
statSync,
symlinkSync,
writeFileSync,
} from "node:fs";
-import { tmpdir } from "node:os";
import { basename, dirname, join, toNamespacedPath } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
@@ -19,7 +16,7 @@ import { parseJsonLines } from "./support/json.js";
const node = Bun.which("node")!;
const helper = join(PLUGIN_ROOT, "mcp", "helpers.mjs");
-const roots: string[] = [];
+const roots = createTemporaryDirectoriesSync(true);
type Row = Record<string, unknown>;
interface Fixture {
root: string;
@@ -44,10 +41,7 @@ function write(path: string, data: string | Buffer): void {
writeFileSync(path, data);
}
function fixture(): Fixture {
- const root = realpathSync(
- mkdtempSync(join(tmpdir(), "candidate-normalizer-")),
- );
- roots.push(root);
+ const root = roots.create("candidate-normalizer-");
const repo = join(root, "İrepository");
for (const path of [
"app/routes.py",
@@ -105,10 +99,7 @@ function invoke(
function ledger(f: Fixture): Row[] {
return parseJsonLines<Row>(readFileSync(f.output, "utf8"));
}
-afterEach(() => {
- for (const root of roots.splice(0))
- rmSync(root, { recursive: true, force: true });
-});
+afterEach(roots.cleanup);
describe("built candidate normalizer", () => {
test.skipIf(process.platform !== "linux")(
diff --git a/sdk/typescript/tests-ts/classify-scan-severity.test.ts b/sdk/typescript/tests-ts/classify-scan-severity.test.ts
index 7f7e42d95..e4014561b 100644
--- a/sdk/typescript/tests-ts/classify-scan-severity.test.ts
+++ b/sdk/typescript/tests-ts/classify-scan-severity.test.ts
@@ -1,4 +1,5 @@
-import { findingFingerprint, sha256 } from "./support/finding-identity.js";
+import { codexWithRun, jsonCodex } from "./support/codex.js";
+import { setFindingIdentity, sha256 } from "./support/finding-identity.js";
import { spawnSync } from "node:child_process";
import { chmod, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -41,10 +42,7 @@ async function fixture() {
) as FindingsDocument;
const other = structuredClone(document.findings[0]!);
other.identity.instance = "second-instance";
- const fingerprint = findingFingerprint(manifest.scan.target.targetId, other);
- other.fingerprints.primary = fingerprint;
- other.findingId = `csf_${sha256(fingerprint).slice(0, 24)}`;
- other.occurrenceId = `occ_${sha256([manifest.scan.id, fingerprint].join("\0")).slice(0, 24)}`;
+ setFindingIdentity(manifest.scan, other);
document.findings.push(other);
await writeFile(
join(scanDirectory, "findings.json"),
@@ -80,23 +78,17 @@ function classifier(
finding: Finding,
excluded = false,
): NonNullable<ClassifySeverityOptions["codex"]> {
- return {
- startThread: () => ({
- run: async () => ({
- finalResponse: JSON.stringify({
- findingId: finding.findingId,
- decision: excluded ? "excluded" : "assessed",
- level: excluded ? null : "medium",
- rubricLabel: excluded ? null : "MEDIUM",
- rationale: excluded
- ? "Administrative record"
- : "Only bounded impact is established.",
- confidence: "high",
- reviewTrigger: null,
- }),
- }),
- }),
- };
+ return jsonCodex(() => ({
+ findingId: finding.findingId,
+ decision: excluded ? "excluded" : "assessed",
+ level: excluded ? null : "medium",
+ rubricLabel: excluded ? null : "MEDIUM",
+ rationale: excluded
+ ? "Administrative record"
+ : "Only bounded impact is established.",
+ confidence: "high",
+ reviewTrigger: null,
+ }));
}
async function query(environment: NodeJS.ProcessEnv, sql: string) {
@@ -417,14 +409,12 @@ test("failed or canceled reassessment leaves the last successful assessment inta
).rejects.toThrow("invalid assessment");
expect(await readFile(path)).toEqual(before);
const controller = new AbortController();
- const codex: NonNullable<ClassifySeverityOptions["codex"]> = {
- startThread: () => ({
- run: async () => {
- controller.abort(new Error("stop"));
- return { finalResponse: "{}" };
- },
- }),
- };
+ const codex: NonNullable<ClassifySeverityOptions["codex"]> = codexWithRun(
+ async () => {
+ controller.abort(new Error("stop"));
+ return { finalResponse: "{}" };
+ },
+ );
await expect(
classifyScanDirectorySeverity(scanDirectory, {
environment,
diff --git a/sdk/typescript/tests-ts/cli-export.test.ts b/sdk/typescript/tests-ts/cli-export.test.ts
index 93403596c..05877fbd7 100644
--- a/sdk/typescript/tests-ts/cli-export.test.ts
+++ b/sdk/typescript/tests-ts/cli-export.test.ts
@@ -1,3 +1,4 @@
+import { scanRegistrationArguments } from "./support/workbench-command.js";
import { resolving } from "./support/promises.js";
import { createHash } from "node:crypto";
import {
@@ -152,20 +153,9 @@ describe("CLI", () => {
};
const workbench = (args: readonly string[]) =>
runWorkbench({ python, pluginRoot: PLUGIN_ROOT, environment }, args);
- const registered = await workbench([
- "register-cli-scan",
- "--repository",
- repository,
- "--scan-dir",
- scanDir,
- "--recipe-json",
- JSON.stringify({
- config: {},
- mode: "standard",
- repository,
- target: { kind: "repository", paths: [] },
- }),
- ]);
+ const registered = await workbench(
+ scanRegistrationArguments(repository, scanDir),
+ );
const scanId = registered["scanId"] as string;
await copyCompletedScan(root);
const content = "# Saved model\n\nSynthetic component boundaries.\n";
diff --git a/sdk/typescript/tests-ts/cli-scan-patch-settings.test.ts b/sdk/typescript/tests-ts/cli-scan-patch-settings.test.ts
index 2011b2880..b0afaee18 100644
--- a/sdk/typescript/tests-ts/cli-scan-patch-settings.test.ts
+++ b/sdk/typescript/tests-ts/cli-scan-patch-settings.test.ts
@@ -184,10 +184,7 @@ describe("inline patch service tier", () => {
test("keeps overlapping scan tiers isolated", async () => {
let arrivals = 0;
- let release!: () => void;
- const ready = new Promise<void>((resolve) => {
- release = resolve;
- });
+ const { promise: ready, resolve: release } = Promise.withResolvers<void>();
const beforeChild = async () => {
if (++arrivals === 2) release();
await ready;
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index 9d0f8123c..0085716cd 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -1,3 +1,4 @@
+import { codexWithRun, jsonCodex } from "./support/codex.js";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { describe, expect, test, mock } from "bun:test";
@@ -1101,26 +1102,16 @@ describe("CLI workbench", () => {
onMatch: (input, options) =>
matchScanFindings(input, {
...options,
- codex: {
- startThread() {
- return {
- async run() {
- return {
- finalResponse: JSON.stringify({
- matches: [],
- uncertain: ["uncertain", "earlier-uncertain"].map(
- (beforeOccurrenceId) => ({
- beforeOccurrenceId,
- afterOccurrenceId: "after",
- reason: "Possibly the same root cause.",
- }),
- ),
- }),
- };
- },
- };
- },
- },
+ codex: jsonCodex(() => ({
+ matches: [],
+ uncertain: ["uncertain", "earlier-uncertain"].map(
+ (beforeOccurrenceId) => ({
+ beforeOccurrenceId,
+ afterOccurrenceId: "after",
+ reason: "Possibly the same root cause.",
+ }),
+ ),
+ })),
}),
}),
),
@@ -1188,11 +1179,7 @@ describe("CLI workbench", () => {
onMatch: (input, options) =>
matchScanFindings(input, {
...options,
- codex: {
- startThread: () => ({
- run,
- }),
- },
+ codex: codexWithRun(run),
}),
}),
),
diff --git a/sdk/typescript/tests-ts/cloud-publish.test.ts b/sdk/typescript/tests-ts/cloud-publish.test.ts
index fa034278f..d931a3654 100644
--- a/sdk/typescript/tests-ts/cloud-publish.test.ts
+++ b/sdk/typescript/tests-ts/cloud-publish.test.ts
@@ -1,4 +1,5 @@
-import { findingFingerprint, sha256 } from "./support/finding-identity.js";
+import { setFindingIdentity, sha256 } from "./support/finding-identity.js";
+import type { FindingsDocument, ScanManifest } from "../src/models.js";
import { responding } from "./support/responses.js";
import { once } from "node:events";
import { rejecting } from "./support/errors.js";
@@ -101,32 +102,16 @@ async function fixture() {
async function addSecondFinding(scan: string): Promise<void> {
const findingsPath = join(scan, "findings.json");
const manifestPath = join(scan, "scan-manifest.json");
- const findings = JSON.parse(await readFile(findingsPath, "utf8")) as {
- findings: Array<{
- findingId: string;
- occurrenceId: string;
- ruleId: string;
- identity: { anchor: string; instance?: string };
- fingerprints: { primary: string };
- title: string;
- }>;
- };
- const manifest = JSON.parse(await readFile(manifestPath, "utf8")) as {
- scan: {
- id: string;
- target: { targetId: string };
- artifacts: Array<{ path: string; sha256: string }>;
- };
- };
+ const findings = JSON.parse(
+ await readFile(findingsPath, "utf8"),
+ ) as FindingsDocument;
+ const manifest = JSON.parse(
+ await readFile(manifestPath, "utf8"),
+ ) as ScanManifest;
const second = structuredClone(findings.findings[0]!);
second.identity.instance = "second-instance";
second.title = "A second synthetic finding";
- const fingerprint = findingFingerprint(manifest.scan.target.targetId, second);
- second.findingId = `csf_${sha256(fingerprint).slice(0, 24)}`;
- second.occurrenceId = `occ_${sha256(
- [manifest.scan.id, fingerprint].join("\0"),
- ).slice(0, 24)}`;
- second.fingerprints.primary = fingerprint;
+ setFindingIdentity(manifest.scan, second);
findings.findings.push(second);
await writeFile(findingsPath, `${JSON.stringify(findings, null, 2)}\n`);
const artifact = manifest.scan.artifacts.find(
diff --git a/sdk/typescript/tests-ts/compact-diff-scan.test.ts b/sdk/typescript/tests-ts/compact-diff-scan.test.ts
index db6e41eb3..32740de40 100644
--- a/sdk/typescript/tests-ts/compact-diff-scan.test.ts
+++ b/sdk/typescript/tests-ts/compact-diff-scan.test.ts
@@ -1,52 +1,29 @@
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { git } from "./git-fixture.js";
+import { initializeMcpClient } from "./support/mcp-client.js";
+import { writeSource } from "./support/shell.js";
import { spawn, spawnSync } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
-import {
- mkdirSync,
- mkdtempSync,
- readFileSync,
- realpathSync,
- rmSync,
- writeFileSync,
-} from "node:fs";
-import { tmpdir } from "node:os";
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import { createInterface } from "node:readline";
import { afterEach, describe, expect, test } from "bun:test";
import { loadContract } from "../src/index.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
type JsonObject = Record<string, unknown>;
-const temporaryRoots: string[] = [];
+const temporaryRoots = createTemporaryDirectoriesSync(true);
-afterEach(() => {
- for (const root of temporaryRoots.splice(0)) {
- rmSync(root, { recursive: true, force: true });
- }
-});
+afterEach(temporaryRoots.cleanup);
function createRepository(): { root: string; repository: string } {
- const root = realpathSync(
- mkdtempSync(join(tmpdir(), "codex-security-diff-")),
- );
- temporaryRoots.push(root);
+ const root = temporaryRoots.create("codex-security-diff-");
const repository = join(root, "repository");
mkdirSync(repository);
git(repository, "init", "-q");
return { root, repository };
}
-function writeSource(
- repository: string,
- path: string,
- content: string | Buffer,
-): void {
- const destination = join(repository, path);
- mkdirSync(dirname(destination), { recursive: true });
- writeFileSync(destination, content);
-}
-
function python(script: string, ...args: string[]) {
const command =
Bun.which("python3") ?? Bun.which("python") ?? Bun.which("py");
@@ -81,49 +58,10 @@ async function startMcp(root: string) {
stdio: ["pipe", "pipe", "pipe"],
},
);
- const messages = createInterface({ input: child.stdout })[
- Symbol.asyncIterator
- ]();
- let stderr = "";
- child.stderr.setEncoding("utf8");
- child.stderr.on("data", (chunk: string) => {
- stderr += chunk;
- });
- let nextId = 0;
-
- async function request(
- method: string,
- params: JsonObject,
- ): Promise<JsonObject> {
- const id = ++nextId;
- child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
- child.stdin.write("\n");
-
- while (true) {
- const message = await messages.next();
- if (message.done) {
- throw new Error(`MCP server exited before replying: ${stderr}`);
- }
- const response = JSON.parse(message.value) as JsonObject;
- if (response["id"] !== id) continue;
- if (response["error"] !== undefined) {
- throw new Error(JSON.stringify(response["error"]));
- }
- return response["result"] as JsonObject;
- }
- }
-
- await request("initialize", {
- protocolVersion: "2025-11-25",
- capabilities: {},
- clientInfo: { name: "compact-diff-test", version: "1.0.0" },
- });
- child.stdin.write(
- `${JSON.stringify({
- jsonrpc: "2.0",
- method: "notifications/initialized",
- params: {},
- })}\n`,
+ const { request, close } = await initializeMcpClient(
+ child,
+ "compact-diff-test",
+ true,
);
return {
@@ -141,12 +79,7 @@ async function startMcp(root: string) {
expect(result["isError"], JSON.stringify(result)).not.toBe(true);
return result["structuredContent"] as JsonObject;
},
- async close(): Promise<void> {
- child.stdin.end();
- await new Promise<void>((resolve) => {
- child.once("close", () => resolve());
- });
- },
+ close,
};
}
diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.ts
index 62be16cab..f76aa484f 100644
--- a/sdk/typescript/tests-ts/component-scan.test.ts
+++ b/sdk/typescript/tests-ts/component-scan.test.ts
@@ -1,3 +1,4 @@
+import { codexWithRun } from "./support/codex.js";
import { createCliTest } from "./support/cli-run.js";
import { gitText } from "./support/shell.js";
import { resolving } from "./support/promises.js";
@@ -202,11 +203,9 @@ async function cli(
function fakeCodex(
response: () => unknown,
): NonNullable<ComponentPlanningOptions["codex"]> {
- return {
- startThread: () => ({
- run: async () => ({ finalResponse: JSON.stringify(await response()) }),
- }),
- };
+ return codexWithRun(async () => ({
+ finalResponse: JSON.stringify(await response()),
+ }));
}
async function scopedInventory(paths: Fixture, scope: string) {
@@ -1092,11 +1091,7 @@ test("does not start another automatic planning call after cancellation", async
await expect(
planComponents(paths.repository, {
signal: controller.signal,
- codex: {
- startThread: () => ({
- run,
- }),
- },
+ codex: codexWithRun(run),
}),
).rejects.toThrow("planning canceled");
expect(run).toHaveBeenCalledTimes(1);
diff --git a/sdk/typescript/tests-ts/container-entrypoint.test.ts b/sdk/typescript/tests-ts/container-entrypoint.test.ts
index 3d98c9706..5243a1d48 100644
--- a/sdk/typescript/tests-ts/container-entrypoint.test.ts
+++ b/sdk/typescript/tests-ts/container-entrypoint.test.ts
@@ -6,34 +6,14 @@ import { delimiter, join } from "node:path";
import { describe, expect, test } from "bun:test";
const testPosix = process.platform === "win32" ? test.skip : test;
-const publicEntrypoint = join(
- import.meta.dir,
- "..",
- "..",
- "..",
- "docker",
- "entrypoint.sh",
-);
-const entrypoint = existsSync(publicEntrypoint)
- ? publicEntrypoint
- : join(import.meta.dir, "..", "public-repo", "docker", "entrypoint.sh");
-const publicVersionVerifier = join(
- import.meta.dir,
- "..",
- "..",
- "..",
- "docker",
- "verify-container-release-version.sh",
-);
-const versionVerifier = existsSync(publicVersionVerifier)
- ? publicVersionVerifier
- : join(
- import.meta.dir,
- "..",
- "public-repo",
- "docker",
- "verify-container-release-version.sh",
- );
+function dockerScript(name: string): string {
+ const canonical = join(import.meta.dir, "..", "..", "..", "docker", name);
+ return existsSync(canonical)
+ ? canonical
+ : join(import.meta.dir, "..", "public-repo", "docker", name);
+}
+const entrypoint = dockerScript("entrypoint.sh");
+const versionVerifier = dockerScript("verify-container-release-version.sh");
async function runEntrypoint(
args: readonly string[],
overrides: Record<string, string> = {},
diff --git a/sdk/typescript/tests-ts/diff-rank-input.test.ts b/sdk/typescript/tests-ts/diff-rank-input.test.ts
index 3baed9245..c0fe64a59 100644
--- a/sdk/typescript/tests-ts/diff-rank-input.test.ts
+++ b/sdk/typescript/tests-ts/diff-rank-input.test.ts
@@ -1,3 +1,4 @@
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { pythonExecutable } from "./support/python.js";
import { git } from "./git-fixture.js";
import { spawnSync } from "node:child_process";
@@ -5,32 +6,23 @@ import {
chmodSync,
existsSync,
mkdirSync,
- mkdtempSync,
readFileSync,
realpathSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
-import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
import { afterEach, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
-const temporaryRoots: string[] = [];
+const temporaryRoots = createTemporaryDirectoriesSync(true);
const testPosix = process.platform === "win32" ? test.skip : test;
-afterEach(() => {
- for (const root of temporaryRoots.splice(0)) {
- rmSync(root, { recursive: true, force: true });
- }
-});
+afterEach(temporaryRoots.cleanup);
test("diff previews stay inside the selected repository", () => {
- const root = realpathSync(
- mkdtempSync(join(tmpdir(), "codex-security-diff-rank-")),
- );
- temporaryRoots.push(root);
+ const root = temporaryRoots.create("codex-security-diff-rank-");
const repository = join(root, "repository");
const nested = join(repository, "src", "nested");
mkdirSync(nested, { recursive: true });
@@ -114,10 +106,7 @@ test("diff previews stay inside the selected repository", () => {
});
test("preserves Unicode Git paths and legacy-encoded commit metadata", () => {
- const root = realpathSync(
- mkdtempSync(join(tmpdir(), "codex-security-diff-rank-unicode-")),
- );
- temporaryRoots.push(root);
+ const root = temporaryRoots.create("codex-security-diff-rank-unicode-");
const repository = join(root, "repository-漢字");
const source = join(repository, "src", "変更.py");
mkdirSync(join(repository, "src"), { recursive: true });
@@ -216,10 +205,7 @@ test("preserves Unicode Git paths and legacy-encoded commit metadata", () => {
testPosix(
"uses only the host-selected Git executable for rank and inventory helpers",
() => {
- const root = realpathSync(
- mkdtempSync(join(tmpdir(), "codex-security-host-git-")),
- );
- temporaryRoots.push(root);
+ const root = temporaryRoots.create("codex-security-host-git-");
const repository = join(root, "repository");
const shimDirectory = join(repository, "tools");
const shim = join(shimDirectory, "git");
diff --git a/sdk/typescript/tests-ts/github-actions-example.test.ts b/sdk/typescript/tests-ts/github-actions-example.test.ts
index 87212b91c..7031d408b 100644
--- a/sdk/typescript/tests-ts/github-actions-example.test.ts
+++ b/sdk/typescript/tests-ts/github-actions-example.test.ts
@@ -1,5 +1,5 @@
-import { mkdtempSync, readFileSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
+import { readFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, expect, test } from "bun:test";
import { parse } from "yaml";
@@ -35,17 +35,12 @@ const workflow = parse(
const job = workflow.jobs.scan;
const scan = job.steps.find((step) => step.id === "scan")!;
const sarif = job.steps.find((step) => step.id === "sarif")!;
-const temporaryDirectories: string[] = [];
+const temporaryDirectories = createTemporaryDirectoriesSync();
-afterEach(() => {
- for (const directory of temporaryDirectories.splice(0)) {
- rmSync(directory, { recursive: true, force: true });
- }
-});
+afterEach(temporaryDirectories.cleanup);
function runStep(step: Step, overrides: Record<string, string> = {}) {
- const directory = mkdtempSync(join(tmpdir(), "codex actions example "));
- temporaryDirectories.push(directory);
+ const directory = temporaryDirectories.create("codex actions example ");
// Git Bash accepts forward-slash drive paths on Windows.
const root = directory.replaceAll("\\", "/");
const result = runWorkflowScript(
diff --git a/sdk/typescript/tests-ts/invoice-desk-workflow.test.ts b/sdk/typescript/tests-ts/invoice-desk-workflow.test.ts
index 2f6c75c48..9686dfc95 100644
--- a/sdk/typescript/tests-ts/invoice-desk-workflow.test.ts
+++ b/sdk/typescript/tests-ts/invoice-desk-workflow.test.ts
@@ -1,13 +1,7 @@
+import { workflowBashCommand } from "./support/shell.js";
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { spawnSync } from "node:child_process";
-import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- readFileSync,
- rmSync,
- writeFileSync,
-} from "node:fs";
-import { tmpdir } from "node:os";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, expect, test } from "bun:test";
import { parse } from "yaml";
@@ -39,17 +33,12 @@ const metrics = steps.find(
(step) => step.name === "Summarize and measure the scan",
)!;
const sourceSha = "a".repeat(40);
-const temporaryDirectories: string[] = [];
+const temporaryDirectories = createTemporaryDirectoriesSync();
-afterEach(() => {
- for (const directory of temporaryDirectories.splice(0)) {
- rmSync(directory, { recursive: true, force: true });
- }
-});
+afterEach(temporaryDirectories.cleanup);
function fixture() {
- const directory = mkdtempSync(join(tmpdir(), "invoice workflow "));
- temporaryDirectories.push(directory);
+ const directory = temporaryDirectories.create("invoice workflow ");
const bin = join(directory, "codex-security-cli/node_modules/.bin");
mkdirSync(bin, { recursive: true });
mkdirSync(join(directory, "invoice-desk"));
@@ -72,15 +61,8 @@ function runStep(
python?: string,
) {
const root = directory.replaceAll("\\", "/");
- const bash =
- process.platform === "win32"
- ? join(
- process.env["ProgramFiles"] ?? "C:/Program Files",
- "Git/bin/bash.exe",
- )
- : "bash";
const result = spawnSync(
- bash,
+ workflowBashCommand(),
[
"--noprofile",
"--norc",
diff --git a/sdk/typescript/tests-ts/plugin-finding-detail-contract.test.ts b/sdk/typescript/tests-ts/plugin-finding-detail-contract.test.ts
index 15bd6c8ce..3ccb6bc8b 100644
--- a/sdk/typescript/tests-ts/plugin-finding-detail-contract.test.ts
+++ b/sdk/typescript/tests-ts/plugin-finding-detail-contract.test.ts
@@ -1,7 +1,7 @@
import { spawn } from "node:child_process";
import { join } from "node:path";
import { describe, expect, test } from "bun:test";
-import Ajv from "ajv";
+import Ajv, { type ValidateFunction } from "ajv";
import Ajv2020 from "ajv/dist/2020.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
import { readJson as readJsonFile } from "./support/json.js";
@@ -104,6 +104,29 @@ async function startMcp() {
return initializeMcpClient(child, "finding-detail-contract-test", false);
}
+function expectScanDraftDetails(validate: ValidateFunction) {
+ expect(validate(scanDraftInput), JSON.stringify(validate.errors)).toBe(true);
+ expect(validate(stringAssessmentInput), JSON.stringify(validate.errors)).toBe(
+ true,
+ );
+ expect(
+ validate({
+ ...scanDraftInput,
+ findings: [{ ...scanDraftFinding, code_evidence: null }],
+ }),
+ JSON.stringify(validate.errors),
+ ).toBe(false);
+ for (const { section, detail } of invalidFindingDetails) {
+ expect(
+ validate({
+ ...scanDraftInput,
+ findings: [{ ...scanDraftFinding, [section]: detail }],
+ }),
+ `${section}: ${JSON.stringify(detail)}`,
+ ).toBe(false);
+ }
+}
+
describe("bundled plugin finding detail contracts", () => {
test("rejects malformed known fields in scan drafts", async () => {
const schemaRoot = join(PLUGIN_ROOT, "schemas");
@@ -116,29 +139,7 @@ describe("bundled plugin finding detail contracts", () => {
validator.addSchema(commonSchema);
const validate = validator.compile(scanDraftSchema);
- expect(validate(scanDraftInput), JSON.stringify(validate.errors)).toBe(
- true,
- );
- expect(
- validate(stringAssessmentInput),
- JSON.stringify(validate.errors),
- ).toBe(true);
- expect(
- validate({
- ...scanDraftInput,
- findings: [{ ...scanDraftFinding, code_evidence: null }],
- }),
- JSON.stringify(validate.errors),
- ).toBe(false);
- for (const { section, detail } of invalidFindingDetails) {
- expect(
- validate({
- ...scanDraftInput,
- findings: [{ ...scanDraftFinding, [section]: detail }],
- }),
- `${section}: ${JSON.stringify(detail)}`,
- ).toBe(false);
- }
+ expectScanDraftDetails(validate);
});
test("publishes the strict scan-draft contract through MCP", async () => {
@@ -155,29 +156,7 @@ describe("bundled plugin finding detail contracts", () => {
validator.addFormat("uuid", /^[0-9a-f-]{36}$/iu);
const validate = validator.compile(tool!["inputSchema"] as JsonObject);
- expect(validate(scanDraftInput), JSON.stringify(validate.errors)).toBe(
- true,
- );
- expect(
- validate(stringAssessmentInput),
- JSON.stringify(validate.errors),
- ).toBe(true);
- expect(
- validate({
- ...scanDraftInput,
- findings: [{ ...scanDraftFinding, code_evidence: null }],
- }),
- JSON.stringify(validate.errors),
- ).toBe(false);
- for (const { section, detail } of invalidFindingDetails) {
- expect(
- validate({
- ...scanDraftInput,
- findings: [{ ...scanDraftFinding, [section]: detail }],
- }),
- `${section}: ${JSON.stringify(detail)}`,
- ).toBe(false);
- }
+ expectScanDraftDetails(validate);
} finally {
await client.close();
}
diff --git a/sdk/typescript/tests-ts/publication-integration.test.ts b/sdk/typescript/tests-ts/publication-integration.test.ts
index 241c682bc..0e4b60652 100644
--- a/sdk/typescript/tests-ts/publication-integration.test.ts
+++ b/sdk/typescript/tests-ts/publication-integration.test.ts
@@ -1,3 +1,4 @@
+import { jsonCodex } from "./support/codex.js";
import {
createCliTest,
captureCli,
@@ -187,16 +188,20 @@ async function fixture(count: number): Promise<PublicationFixture> {
};
}
-function publishCommand(scanDirectory: string, ...flags: string[]): string[] {
+function publicationArguments(
+ command: "scan" | "check",
+ scanDirectory: string,
+ ...options: string[]
+): string[] {
return [
"publish",
- "scan",
+ command,
scanDirectory,
"--to",
"linear",
"--linear-team",
OPTIONS.teamId,
- ...flags,
+ ...options,
"--json",
];
}
@@ -324,21 +329,15 @@ describe("database-backed Linear publication integration", () => {
environment: completed.environment,
rubricPath,
findingIds: [finding.findingId],
- codex: {
- startThread: () => ({
- run: async () => ({
- finalResponse: JSON.stringify({
- findingId: finding.findingId,
- decision: "assessed",
- level: "medium",
- rubricLabel: "MEDIUM",
- rationale: "Only bounded impact is established.",
- confidence: "high",
- reviewTrigger: null,
- }),
- }),
- }),
- },
+ codex: jsonCodex(() => ({
+ findingId: finding.findingId,
+ decision: "assessed",
+ level: "medium",
+ rubricLabel: "MEDIUM",
+ rationale: "Only bounded impact is established.",
+ confidence: "high",
+ reviewTrigger: null,
+ })),
});
const result = await publishScanInternal(
completed.scanDirectory,
@@ -409,7 +408,8 @@ describe("database-backed Linear publication integration", () => {
},
}) as unknown as LinearClient,
});
- const command = publishCommand(
+ const command = publicationArguments(
+ "scan",
completed.scanDirectory,
"--project",
OPTIONS.projectId,
@@ -444,18 +444,12 @@ describe("database-backed Linear publication integration", () => {
const before = sha256(await readFile(database));
expect(
await checkOutput.run(
- [
- "publish",
+ publicationArguments(
"check",
completed.scanDirectory,
- "--to",
- "linear",
- "--linear-team",
- OPTIONS.teamId,
"--project",
OPTIONS.projectId,
- "--json",
- ],
+ ),
checkCli,
),
).toBe(0);
@@ -554,7 +548,9 @@ describe("database-backed Linear publication integration", () => {
},
});
- expect(await runCli(publishCommand(completed.scanDirectory), cli)).toBe(0);
+ expect(
+ await runCli(publicationArguments("scan", completed.scanDirectory), cli),
+ ).toBe(0);
const result = JSON.parse(stdout.text()) as PublishScanResult;
expect(result.destination).toEqual({
@@ -675,7 +671,12 @@ describe("database-backed Linear publication integration", () => {
expect(
await runCli(
- publishCommand(completed.scanDirectory, "--project", OPTIONS.projectId),
+ publicationArguments(
+ "scan",
+ completed.scanDirectory,
+ "--project",
+ OPTIONS.projectId,
+ ),
cli,
),
).toBe(0);
@@ -766,7 +767,9 @@ describe("database-backed Linear publication integration", () => {
},
});
- expect(await runCli(publishCommand(completed.scanDirectory), cli)).toBe(2);
+ expect(
+ await runCli(publicationArguments("scan", completed.scanDirectory), cli),
+ ).toBe(2);
const result = JSON.parse(stdout.text()) as PublishScanResult;
expect(result.destination).toEqual({
@@ -834,7 +837,12 @@ describe("database-backed Linear publication integration", () => {
expect(
await runCli(
- publishCommand(completed.scanDirectory, "--project", OPTIONS.projectId),
+ publicationArguments(
+ "scan",
+ completed.scanDirectory,
+ "--project",
+ OPTIONS.projectId,
+ ),
cli,
),
).toBe(0);
@@ -932,7 +940,8 @@ describe("database-backed Linear publication integration", () => {
expect(
await runCli(
- publishCommand(
+ publicationArguments(
+ "scan",
completed.scanDirectory,
"--project",
OPTIONS.projectId,
@@ -1229,7 +1238,12 @@ for (;;) Atomics.wait(waiter, 0, 0, 1000);`,
expect(
await runCli(
- publishCommand(completed.scanDirectory, "--project", OPTIONS.projectId),
+ publicationArguments(
+ "scan",
+ completed.scanDirectory,
+ "--project",
+ OPTIONS.projectId,
+ ),
cli,
),
).toBe(130);
diff --git a/sdk/typescript/tests-ts/published-install-smoke.test.ts b/sdk/typescript/tests-ts/published-install-smoke.test.ts
index e0696a0e1..50e623746 100644
--- a/sdk/typescript/tests-ts/published-install-smoke.test.ts
+++ b/sdk/typescript/tests-ts/published-install-smoke.test.ts
@@ -1,28 +1,15 @@
import { afterEach, expect, test } from "bun:test";
-import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
-const { verifyInstalledPackage } = (await import(
- new URL("../scripts/smoke-published-package.mjs", import.meta.url).href
-)) as {
- verifyInstalledPackage: (
- consumer: string,
- environment: NodeJS.ProcessEnv,
- ) => Promise<void>;
-};
-const directories: string[] = [];
-afterEach(async () => {
- await Promise.all(
- directories
- .splice(0)
- .map((directory) => rm(directory, { recursive: true, force: true })),
- );
-});
+import { verifyInstalledPackage } from "../scripts/smoke-published-package.mjs";
+import { createTemporaryDirectories } from "./support/temporary-directories.js";
+
+const directories = createTemporaryDirectories();
+afterEach(directories.cleanup);
async function installedFixture(cliVersion: string) {
- const consumer = await mkdtemp(join(tmpdir(), "published smoke "));
- directories.push(consumer);
+ const consumer = await directories.create("published smoke ");
const installedRoot = join(
consumer,
"node_modules",
diff --git a/sdk/typescript/tests-ts/rank-pool.test.ts b/sdk/typescript/tests-ts/rank-pool.test.ts
index f1eb8ea6e..f6e0d8e7e 100644
--- a/sdk/typescript/tests-ts/rank-pool.test.ts
+++ b/sdk/typescript/tests-ts/rank-pool.test.ts
@@ -1,18 +1,16 @@
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import {
existsSync,
mkdirSync,
- mkdtempSync,
readFileSync,
readdirSync,
- realpathSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from "node:fs";
-import { tmpdir } from "node:os";
import { join, sep } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
@@ -20,7 +18,7 @@ import { PLUGIN_ROOT } from "./plugin-root.js";
const node = Bun.which("node")!;
const helper = join(PLUGIN_ROOT, "mcp", "helpers.mjs");
const newline = process.platform === "win32" ? "\r\n" : "\n";
-const roots: string[] = [];
+const roots = createTemporaryDirectoriesSync(true);
interface Worker {
slot: number;
input_shards: string[];
@@ -48,8 +46,7 @@ const ranked = (index: number) => ({
reason: "runtime surface",
});
function fixture(count = 5) {
- const root = realpathSync(mkdtempSync(join(tmpdir(), "rank-pool-")));
- roots.push(root);
+ const root = roots.create("rank-pool-");
const directory = join(root, "rank_shards");
mkdirSync(directory);
for (let index = 1; index <= count; index++)
@@ -68,7 +65,7 @@ function run(f: Fixture, command: string, args: string[], env = process.env) {
input: "stdin is not a plan",
});
}
-function make(f: Fixture, slots = "2", extra: string[] = []) {
+function make(f: Fixture, slots = "2") {
return run(f, "make-rank-pool-plan", [
"--shard-dir",
f.directory,
@@ -76,7 +73,6 @@ function make(f: Fixture, slots = "2", extra: string[] = []) {
slots,
"--out",
f.plan,
- ...extra,
]);
}
function validate(f: Fixture, slot?: string, extra: string[] = []) {
@@ -113,10 +109,7 @@ function complete(f: Fixture, slots?: number[]) {
}
}
}
-afterEach(() => {
- for (const root of roots.splice(0))
- rmSync(root, { recursive: true, force: true });
-});
+afterEach(roots.cleanup);
describe("rank pool helpers", () => {
test("writes stable sorted JSON and assigns every shard round-robin", () => {
diff --git a/sdk/typescript/tests-ts/rank-shards.test.ts b/sdk/typescript/tests-ts/rank-shards.test.ts
index baec4859c..086760723 100644
--- a/sdk/typescript/tests-ts/rank-shards.test.ts
+++ b/sdk/typescript/tests-ts/rank-shards.test.ts
@@ -1,26 +1,24 @@
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { spawnSync } from "node:child_process";
import {
chmodSync,
existsSync,
mkdirSync,
- mkdtempSync,
readFileSync,
readdirSync,
- realpathSync,
renameSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from "node:fs";
-import { tmpdir } from "node:os";
import { dirname, join, sep } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
const node = Bun.which("node")!;
const helper = join(PLUGIN_ROOT, "mcp", "helpers.mjs");
-const roots: string[] = [];
+const roots = createTemporaryDirectoriesSync(true);
const newline = process.platform === "win32" ? "\r\n" : "\n";
type Row = Record<string, unknown>;
const candidate = (path: string, area = "src") => ({
@@ -36,8 +34,7 @@ const ranked = (row: Row) => ({
reason: "runtime surface",
});
function fixture() {
- const root = realpathSync(mkdtempSync(join(tmpdir(), "rank-shards-")));
- roots.push(root);
+ const root = roots.create("rank-shards-");
return {
root,
input: join(root, "input.jsonl"),
@@ -109,10 +106,7 @@ function complete(f: Fixture) {
.map(ranked),
);
}
-afterEach(() => {
- for (const root of roots.splice(0))
- rmSync(root, { recursive: true, force: true });
-});
+afterEach(roots.cleanup);
describe("rank shard helpers", () => {
test.skipIf(process.platform !== "win32")(
diff --git a/sdk/typescript/tests-ts/release-pr.test.ts b/sdk/typescript/tests-ts/release-pr.test.ts
index fadb62bb2..62ba5c10c 100644
--- a/sdk/typescript/tests-ts/release-pr.test.ts
+++ b/sdk/typescript/tests-ts/release-pr.test.ts
@@ -1,9 +1,8 @@
import { gitText } from "./support/shell.js";
-import { mkdtempSync, readFileSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { readFileSync } from "node:fs";
import { afterEach, describe, expect, test } from "bun:test";
import { check } from "prettier";
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
type Change = {
title: string;
@@ -113,16 +112,10 @@ const {
plan: Plan;
}>;
};
-const releaseAutomation = new URL(
- "../scripts/release-automation.mjs",
- import.meta.url,
-);
-const { parseReviewedReleaseNotes, composeReleaseNotes } = (await import(
- releaseAutomation.href
-)) as {
- parseReviewedReleaseNotes: (version: string, notes: string) => string;
- composeReleaseNotes: (inventory: string, summary: string) => string;
-};
+import {
+ parseReviewedReleaseNotes,
+ composeReleaseNotes,
+} from "../scripts/release-automation.mjs";
const template = readFileSync(
new URL("../../../.github/PULL_REQUEST_TEMPLATE.md", import.meta.url),
"utf8",
@@ -131,11 +124,8 @@ const workflow = readFileSync(
new URL("../../../.github/workflows/node-release-pr.yml", import.meta.url),
"utf8",
);
-const directories: string[] = [];
-afterEach(() => {
- for (const directory of directories.splice(0))
- rmSync(directory, { recursive: true, force: true });
-});
+const directories = createTemporaryDirectoriesSync();
+afterEach(directories.cleanup);
function packageText(version = "0.1.23", dependencies = {}) {
return `${JSON.stringify({ name: "@openai/codex-security", version, dependencies }, null, 2)}\n`;
@@ -182,13 +172,12 @@ function apiError(status: number) {
}
class Fixture {
- readonly directory = mkdtempSync(join(tmpdir(), "release pr test "));
+ readonly directory = directories.create("release pr test ");
readonly repo = createGitRepository(this.directory);
readonly github = new FakeGitHub(this);
readonly git = this.repo.git;
constructor() {
- directories.push(this.directory);
this.git("init", "-b", "main");
this.git("config", "user.name", "Release Test");
this.git("config", "user.email", "[email protected]");
diff --git a/sdk/typescript/tests-ts/runtime-plugin-reuse.test.ts b/sdk/typescript/tests-ts/runtime-plugin-reuse.test.ts
index f8ac7eaed..5c30b446a 100644
--- a/sdk/typescript/tests-ts/runtime-plugin-reuse.test.ts
+++ b/sdk/typescript/tests-ts/runtime-plugin-reuse.test.ts
@@ -101,16 +101,13 @@ async function checkWorkerReuse(
else if (metadata === "truncated") await writeFile(manifest, "{");
const originalWrite = fsPromises.writeFile;
let writes = 0;
- let releaseWrites = () => {};
- const bothWriting = new Promise<void>((resolve) => {
- releaseWrites = resolve;
- });
+ const bothWriting = Promise.withResolvers<void>();
const write = concurrent
? spyOn(fsPromises, "writeFile").mockImplementation(async (...args) => {
// Both repairs reach the filesystem before either write completes.
if (dirname(String(args[0])) === dirname(manifest)) {
- if (++writes === 2) releaseWrites();
- await bothWriting;
+ if (++writes === 2) bothWriting.resolve();
+ await bothWriting.promise;
}
return originalWrite(...args);
})
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 9706bde4e..8605c755f 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -1,3 +1,4 @@
+import { scanRegistrationArguments } from "./support/workbench-command.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
import { parseJsonLines, jsonLines } from "./support/json.js";
import { execFile, spawnSync } from "node:child_process";
@@ -5453,20 +5454,7 @@ describe("runtime directories and plugin Python boundary", () => {
CODEX_SECURITY_STATE_DIR: stateDirectory,
},
},
- [
- "register-cli-scan",
- "--repository",
- repository,
- "--scan-dir",
- scanDirectory,
- "--recipe-json",
- JSON.stringify({
- config: {},
- mode: "standard",
- repository,
- target: { kind: "repository", paths: [] },
- }),
- ],
+ scanRegistrationArguments(repository, scanDirectory),
);
expect(registration["scanId"]).toBeString();
@@ -5563,20 +5551,10 @@ describe("runtime directories and plugin Python boundary", () => {
CODEX_SECURITY_STATE_DIR: join(root, "state"),
},
};
- const registration = await runWorkbench(workbenchOptions, [
- "register-cli-scan",
- "--repository",
- repository,
- "--scan-dir",
- scanDir,
- "--recipe-json",
- JSON.stringify({
- config: {},
- mode: "standard",
- repository,
- target: { kind: "repository", paths: [] },
- }),
- ]);
+ const registration = await runWorkbench(
+ workbenchOptions,
+ scanRegistrationArguments(repository, scanDir),
+ );
await Promise.all(
present.map((filename) =>
copyFile(
@@ -5628,20 +5606,10 @@ describe("runtime directories and plugin Python boundary", () => {
CODEX_SECURITY_STATE_DIR: join(root, "state"),
},
};
- const registration = await runWorkbench(workbenchOptions, [
- "register-cli-scan",
- "--repository",
- repository,
- "--scan-dir",
- scanDir,
- "--recipe-json",
- JSON.stringify({
- config: {},
- mode: "standard",
- repository,
- target: { kind: "repository", paths: [] },
- }),
- ]);
+ const registration = await runWorkbench(
+ workbenchOptions,
+ scanRegistrationArguments(repository, scanDir),
+ );
await symlink(
join(root, "missing-manifest.json"),
join(scanDir, "scan-manifest.json"),
diff --git a/sdk/typescript/tests-ts/scan-comparison.property.test.ts b/sdk/typescript/tests-ts/scan-comparison.property.test.ts
index c2950abf6..cb10f0457 100644
--- a/sdk/typescript/tests-ts/scan-comparison.property.test.ts
+++ b/sdk/typescript/tests-ts/scan-comparison.property.test.ts
@@ -1,3 +1,4 @@
+import { jsonCodex } from "./support/codex.js";
import { describe, expect, test } from "bun:test";
import fc from "fast-check";
import {
@@ -40,11 +41,7 @@ function compare(
) {
return matchScanFindings(input, {
...options,
- codex: {
- startThread: () => ({
- run: async () => ({ finalResponse: JSON.stringify(response) }),
- }),
- },
+ codex: jsonCodex(() => response),
});
}
diff --git a/sdk/typescript/tests-ts/security-policy-helper.test.ts b/sdk/typescript/tests-ts/security-policy-helper.test.ts
index aa89df944..b6674d543 100644
--- a/sdk/typescript/tests-ts/security-policy-helper.test.ts
+++ b/sdk/typescript/tests-ts/security-policy-helper.test.ts
@@ -1,26 +1,24 @@
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { spawnSync } from "node:child_process";
import {
chmodSync,
existsSync,
mkdirSync,
- mkdtempSync,
readFileSync,
- rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
-import { tmpdir, userInfo } from "node:os";
+import { userInfo } from "node:os";
import { dirname, join, relative, sep, win32 } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
import { writeSource as write } from "./support/shell.js";
const helper = join(PLUGIN_ROOT, "mcp", "helpers.mjs");
-const temporaryDirectories: string[] = [];
+const temporaryDirectories = createTemporaryDirectoriesSync();
function fixture(name = "repository") {
- const directory = mkdtempSync(join(tmpdir(), "security-policy-helper-"));
- temporaryDirectories.push(directory);
+ const directory = temporaryDirectories.create("security-policy-helper-");
const root = join(directory, name);
const output = join(directory, "output");
mkdirSync(root);
@@ -62,11 +60,7 @@ function expectGuidance(text: string, policies: [string, string][]): void {
);
}
-afterEach(() => {
- for (const directory of temporaryDirectories.splice(0)) {
- rmSync(directory, { recursive: true, force: true });
- }
-});
+afterEach(temporaryDirectories.cleanup);
describe("built SECURITY.md helper", () => {
test("accepts dash-prefixed paths with equals syntax", () => {
diff --git a/sdk/typescript/tests-ts/stopped-scan-results.test.ts b/sdk/typescript/tests-ts/stopped-scan-results.test.ts
index e0b562e68..01efdfdf7 100644
--- a/sdk/typescript/tests-ts/stopped-scan-results.test.ts
+++ b/sdk/typescript/tests-ts/stopped-scan-results.test.ts
@@ -1,17 +1,11 @@
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { afterEach, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
import { runNodePython } from "./support/python-probe.js";
-const temporaryDirectories: string[] = [];
+const temporaryDirectories = createTemporaryDirectoriesSync();
-afterEach(() => {
- for (const path of temporaryDirectories.splice(0)) {
- rmSync(path, { recursive: true, force: true });
- }
-});
+afterEach(temporaryDirectories.cleanup);
const stoppedScanProbe = [
"import argparse, hashlib, json, os, pathlib, shutil, sqlite3, subprocess, sys, uuid",
@@ -162,8 +156,7 @@ function runStoppedScanProbe(
) {
const python = Bun.which("python3") ?? Bun.which("python");
expect(python).not.toBeNull();
- const root = mkdtempSync(join(tmpdir(), prefix));
- temporaryDirectories.push(root);
+ const root = temporaryDirectories.create(prefix);
const result = runNodePython(python!, [
"-c",
stoppedScanProbe,
diff --git a/sdk/typescript/tests-ts/support/codex.ts b/sdk/typescript/tests-ts/support/codex.ts
new file mode 100644
index 000000000..d4c499e27
--- /dev/null
+++ b/sdk/typescript/tests-ts/support/codex.ts
@@ -0,0 +1,9 @@
+export function codexWithRun<Run>(run: Run) {
+ return { startThread: () => ({ run }) };
+}
+
+export function jsonCodex(response: () => unknown) {
+ return codexWithRun(async () => ({
+ finalResponse: JSON.stringify(response()),
+ }));
+}
diff --git a/sdk/typescript/tests-ts/support/shell.ts b/sdk/typescript/tests-ts/support/shell.ts
index ce44ee29e..2fec8ac9e 100644
--- a/sdk/typescript/tests-ts/support/shell.ts
+++ b/sdk/typescript/tests-ts/support/shell.ts
@@ -11,6 +11,15 @@ export function bashCommand(): string {
return existsSync(gitBash) ? gitBash : "bash";
}
+export function workflowBashCommand(): string {
+ return process.platform === "win32"
+ ? join(
+ process.env["ProgramFiles"] ?? "C:/Program Files",
+ "Git/bin/bash.exe",
+ )
+ : "bash";
+}
+
export function runCommand(
command: string,
args: string[],
diff --git a/sdk/typescript/tests-ts/support/temporary-directories.ts b/sdk/typescript/tests-ts/support/temporary-directories.ts
index f32017a34..b5ef19c74 100644
--- a/sdk/typescript/tests-ts/support/temporary-directories.ts
+++ b/sdk/typescript/tests-ts/support/temporary-directories.ts
@@ -1,3 +1,6 @@
+import { mkdtempSync, realpathSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { rm } from "node:fs/promises";
import {
createTemporaryDirectories,
@@ -40,3 +43,20 @@ export function temporaryDirectory(
): Promise<string> {
return createPluginTemporaryDirectory(prefix, canonicalize);
}
+
+export function createTemporaryDirectoriesSync(canonicalize = false) {
+ const roots: string[] = [];
+ return {
+ create(prefix: string): string {
+ const directory = mkdtempSync(join(tmpdir(), prefix));
+ const root = canonicalize ? realpathSync(directory) : directory;
+ roots.push(root);
+ return root;
+ },
+ cleanup(): void {
+ for (const root of roots.splice(0)) {
+ rmSync(root, { recursive: true, force: true });
+ }
+ },
+ };
+}
diff --git a/sdk/typescript/tests-ts/support/workbench-command.ts b/sdk/typescript/tests-ts/support/workbench-command.ts
index b11051fc5..9d51ad68d 100644
--- a/sdk/typescript/tests-ts/support/workbench-command.ts
+++ b/sdk/typescript/tests-ts/support/workbench-command.ts
@@ -17,3 +17,23 @@ export function workbenchCommand(
input,
);
}
+
+export function scanRegistrationArguments(
+ repository: string,
+ scanDirectory: string,
+): string[] {
+ return [
+ "register-cli-scan",
+ "--repository",
+ repository,
+ "--scan-dir",
+ scanDirectory,
+ "--recipe-json",
+ JSON.stringify({
+ config: {},
+ mode: "standard",
+ repository,
+ target: { kind: "repository", paths: [] },
+ }),
+ ];
+}
diff --git a/sdk/typescript/tests-ts/support/workflow-script.ts b/sdk/typescript/tests-ts/support/workflow-script.ts
index f1dd7c907..92e0f3726 100644
--- a/sdk/typescript/tests-ts/support/workflow-script.ts
+++ b/sdk/typescript/tests-ts/support/workflow-script.ts
@@ -1,5 +1,5 @@
import { spawnSync } from "node:child_process";
-import { join } from "node:path";
+import { workflowBashCommand } from "./shell.js";
export function runWorkflowScript(
directory: string,
@@ -8,15 +8,8 @@ export function runWorkflowScript(
shellOptions: string[] = [],
argumentsPath = "$ARGUMENTS_PATH",
) {
- const bash =
- process.platform === "win32"
- ? join(
- process.env["ProgramFiles"] ?? "C:/Program Files",
- "Git/bin/bash.exe",
- )
- : "bash";
const result = spawnSync(
- bash,
+ workflowBashCommand(),
[
"--noprofile",
"--norc",
diff --git a/sdk/typescript/tests-ts/workbench-nested-git-utf8.test.ts b/sdk/typescript/tests-ts/workbench-nested-git-utf8.test.ts
index 98f908d03..239014e2b 100644
--- a/sdk/typescript/tests-ts/workbench-nested-git-utf8.test.ts
+++ b/sdk/typescript/tests-ts/workbench-nested-git-utf8.test.ts
@@ -1,25 +1,15 @@
+import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { pythonExecutable } from "./support/python.js";
import { spawnSync } from "node:child_process";
-import {
- mkdirSync,
- mkdtempSync,
- readFileSync,
- realpathSync,
- rmSync,
-} from "node:fs";
-import { tmpdir } from "node:os";
+import { mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
import { runNodePython } from "./support/python-probe.js";
-const temporaryDirectories: string[] = [];
+const temporaryDirectories = createTemporaryDirectoriesSync(true);
-afterEach(() => {
- for (const directory of temporaryDirectories.splice(0)) {
- rmSync(directory, { recursive: true, force: true });
- }
-});
+afterEach(temporaryDirectories.cleanup);
function git(directory: string, ...args: string[]): void {
const result = spawnSync("git", ["-C", directory, ...args], {
@@ -30,10 +20,7 @@ function git(directory: string, ...args: string[]): void {
}
test("writes nested Git pointers as UTF-8 independently of the locale", () => {
- const root = realpathSync(
- mkdtempSync(join(tmpdir(), "codex-security-nested-git-utf8-")),
- );
- temporaryDirectories.push(root);
+ const root = temporaryDirectories.create("codex-security-nested-git-utf8-");
const repository = join(root, "repository");
const nested = join(repository, "nested-漢字");
const checkout = join(root, "checkout");