From 94c3077355d3d904dcd200cce532a82bdea6d3db Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:06:31 -0500 Subject: [PATCH] test(providers): own temporary directories through createTestTempDirectory (#12722) * test(providers): own temporary directories through createTestTempDirectory Route provider-boundary fixtures through createTestTempDirectory so each case removes its canonical directory after the test. Process shutdown stays in afterEach, which still runs before that removal. Skip the two Windows Cutter checks with it.skipIf, and compare unknown plugin recovery with cutterBridgeSourceRecovery. * test(providers): keep gated fixture cleanup with its owner createTestTempDirectory always deletes after the test, including when GDB or inferior cleanup fails and when the Rizin MCP harness already owns the directory. Restore mkdtemp removal behind confirmed process cleanup, and leave decoder inputs owned by the harness. Co-authored-by: morluto * test(cutter): keep an independent unknown-source recovery check Comparing discovery recovery with cutterBridgeSourceRecovery follows the formatter, so dropping the unknown-source explanation still passes. Assert that explanation directly, beside bridge_source and the plugin path. Co-authored-by: morluto --------- Co-authored-by: Cursor Agent Co-authored-by: morluto --- .../providers/CutterBridgeClient.test.ts | 226 ++++++++--------- .../CutterBridgeNullIdentity.test.ts | 11 +- .../providers/GdbCommandQueue.test.ts | 1 + .../providers/GdbSessionManagers.test.ts | 1 + .../GdbSessionReviewRegressions.test.ts | 1 + .../RizinDebugSessionManagers.test.ts | 16 +- ...RizinDebugSessionReviewRegressions.test.ts | 33 ++- .../providers/RizinDecoderInputs.test.ts | 1 + .../providers/RizinInferiorExit.test.ts | 1 + .../providers/RizinInferiorTty.test.ts | 20 +- .../apktoolRuntimeExhaustion.test.ts | 8 +- .../artifactReadCleanupRetry.test.ts | 8 +- .../bundleResourceComposition.test.ts | 23 +- .../providers/cutterBridgeProducer.test.ts | 14 +- .../cutterBridgeRequestLimit.test.ts | 10 +- .../providers/desktopExportPython.test.ts | 228 ++++++++++-------- .../providers/desktopLaunchCommand.test.ts | 141 +++++------ .../ghidra/ghidraCheckpointLifecycle.test.ts | 20 +- .../hopper/hopperFileOffsetClose.test.ts | 33 +-- .../hopper/linuxPrivateDisplay.test.ts | 8 +- .../ida/verifierRequirements.test.ts | 89 ++++--- .../native/lldbCallTracerFailures.test.ts | 32 +-- .../native/lldbReadbackFiles.test.ts | 14 +- .../native/objcClassMetadataFallback.test.ts | 8 +- 24 files changed, 434 insertions(+), 513 deletions(-) diff --git a/tests/boundary/providers/CutterBridgeClient.test.ts b/tests/boundary/providers/CutterBridgeClient.test.ts index 410f675e25..f00d15d1b1 100644 --- a/tests/boundary/providers/CutterBridgeClient.test.ts +++ b/tests/boundary/providers/CutterBridgeClient.test.ts @@ -8,7 +8,6 @@ import { readFileSync } from "node:fs"; import { chmod, mkdir, - mkdtemp, readFile, rm, symlink, @@ -19,6 +18,7 @@ import { homedir, tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js"; import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js"; @@ -110,7 +110,7 @@ const createClient = ( }; const verifyCutterCancellationAfterDispatch = async (): Promise => { - const directory = await mkdtemp(join(tmpdir(), "rea-cutter-cancel-test-")); + const directory = await createTestTempDirectory("rea-cutter-cancel-test-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; let markDispatched: (() => void) | undefined; @@ -148,14 +148,13 @@ const verifyCutterCancellationAfterDispatch = async (): Promise => { }); } finally { await new Promise((resolve) => server.close(() => resolve())); - await rm(directory, { recursive: true, force: true }); } }; it.skipIf(process.platform === "win32").each(["discovery", "command"] as const)( "retains closed sockets and completed facts when %s is cancelled", async (operation) => { - const directory = await mkdtemp(join(tmpdir(), "rea-cutter-close-order-")); + const directory = await createTestTempDirectory("rea-cutter-close-order-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "close-order-test-token"; const controller = new AbortController(); @@ -248,7 +247,6 @@ it.skipIf(process.platform === "win32").each(["discovery", "command"] as const)( vi.doUnmock("node:net"); await vi.resetModules(); await new Promise((resolve) => peer.close(() => resolve())); - await rm(directory, { recursive: true, force: true }); } }, ); @@ -260,8 +258,6 @@ describe("CutterBridgeClient: selected POSIX paths", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); @@ -271,7 +267,7 @@ describe("CutterBridgeClient: selected POSIX paths", () => { .each(["explicit", "tilde", "default"] as const)( "discovers descriptors through symlink parent traversal in %s directory selection", async (selection) => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-selected-path-")); + directory = await createTestTempDirectory("rea-cutter-selected-path-"); const home = `${directory}/home`; const target = `${directory}/actual`; await mkdir(home); @@ -317,8 +313,6 @@ describe("CutterBridgeClient: plugin source identity", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); @@ -336,7 +330,7 @@ describe("CutterBridgeClient: plugin source identity", () => { ] as const)( "reports a %s plugin source in discovery (digest: %s)", async (source, digest) => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-source-")); + directory = await createTestTempDirectory("rea-cutter-source-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; server = createStatusHarness(token, "/tmp/sample.bin", 4).server; @@ -362,7 +356,7 @@ describe("CutterBridgeClient: plugin source identity", () => { ); it("surfaces a missing packaged plugin instead of hiding the live session", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-missing-plugin-")); + directory = await createTestTempDirectory("rea-cutter-missing-plugin-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; const status = createStatusHarness(token, "/tmp/sample.bin", 4); @@ -415,7 +409,7 @@ describe("CutterBridgeClient: plugin source identity", () => { }); it("refuses a command to a modified plugin before sending it", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-source-")); + directory = await createTestTempDirectory("rea-cutter-source-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; const requests: unknown[] = []; @@ -451,14 +445,12 @@ describe("CutterBridgeClient: scenario group 1", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); it("discovers a live bridge using the exact session ID from its descriptor", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-bridge-test-")); + directory = await createTestTempDirectory("rea-cutter-bridge-test-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; const harness = createStatusHarness(token, "/tmp/sample.bin", 4); @@ -480,7 +472,7 @@ describe("CutterBridgeClient: scenario group 1", () => { }); it("does not disclose a client proof or command to a spoofed loopback peer", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-spoofed-peer-")); + directory = await createTestTempDirectory("rea-cutter-spoofed-peer-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; let received = ""; @@ -507,24 +499,26 @@ describe("CutterBridgeClient: scenario group 1", () => { expect(received).not.toContain("write /tmp/secret"); }); - it("rejects a POSIX bridge directory that is accessible to other users", async () => { - if (process.platform === "win32") return; - directory = await mkdtemp(join(tmpdir(), "rea-cutter-insecure-")); - await chmod(directory, 0o755); + it.skipIf(process.platform === "win32")( + "rejects a POSIX bridge directory that is accessible to other users", + async () => { + directory = await createTestTempDirectory("rea-cutter-insecure-"); + await chmod(directory, 0o755); - const result = await new CutterBridgeClient({ - REA_CUTTER_BRIDGE_DIR: directory, - }).listSessions(); + const result = await new CutterBridgeClient({ + REA_CUTTER_BRIDGE_DIR: directory, + }).listSessions(); - expect(result).toMatchObject({ - sessions: [], - discovery_status: "bridge_directory_insecure", - bridge_directory_security: "not_private", - }); - }); + expect(result).toMatchObject({ + sessions: [], + discovery_status: "bridge_directory_insecure", + bridge_directory_security: "not_private", + }); + }, + ); it("preserves unknown execution state when a live bridge closes after command dispatch", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-close-test-")); + directory = await createTestTempDirectory("rea-cutter-close-test-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; server = authenticatedServer( "synthetic-cutter-bridge-token-for-test", @@ -560,8 +554,8 @@ describe("CutterBridgeClient: scenario group 1", () => { ); it("uses verified Windows handle reads before trusting Cutter descriptors", async () => { - directory = await mkdtemp( - join(tmpdir(), "rea-cutter-windows-bridge-test-"), + directory = await createTestTempDirectory( + "rea-cutter-windows-bridge-test-", ); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; @@ -613,14 +607,12 @@ describe("CutterBridgeClient: scenario group 2", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); it("fails closed when Windows ACL verification is unavailable", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-windows-insecure-")); + directory = await createTestTempDirectory("rea-cutter-windows-insecure-"); const result = await new CutterBridgeClient( { REA_CUTTER_BRIDGE_DIR: directory }, @@ -641,8 +633,8 @@ describe("CutterBridgeClient: scenario group 2", () => { }); it("omits invalid, unresponsive, and mismatched bridge descriptors", async () => { - directory = await mkdtemp( - join(tmpdir(), "rea-cutter-invalid-descriptors-"), + directory = await createTestTempDirectory( + "rea-cutter-invalid-descriptors-", ); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; @@ -715,7 +707,7 @@ describe("CutterBridgeClient: scenario group 2", () => { }); it("ignores a descriptor whose status endpoint is unavailable", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-dead-status-")); + directory = await createTestTempDirectory("rea-cutter-dead-status-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const dead = createServer(); const port = await listen(dead); @@ -748,14 +740,12 @@ describe("CutterBridgeClient: scenario group 3", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); it("reports discovery failure when reading bridge directory entries fails", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-readdir-error-")); + directory = await createTestTempDirectory("rea-cutter-readdir-error-"); await vi.resetModules(); vi.doMock("node:fs/promises", async () => { const real = @@ -787,7 +777,7 @@ describe("CutterBridgeClient: scenario group 3", () => { }); it("reports unavailable directories and ignores a non-directory bridge path", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-path-")); + directory = await createTestTempDirectory("rea-cutter-path-"); const filePath = join(directory, "not-a-directory"); await writeFile(filePath, "x"); await expect( @@ -817,7 +807,7 @@ describe("CutterBridgeClient: scenario group 3", () => { }); it("uses descriptor status values when a live bridge omits optional fields", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-status-defaults-")); + directory = await createTestTempDirectory("rea-cutter-status-defaults-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; server = authenticatedServer( "synthetic-cutter-bridge-token-for-test", @@ -854,14 +844,12 @@ describe("CutterBridgeClient: scenario group 4", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); it("covers command response defaults, failures, malformed data, and generation changes", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-command-responses-")); + directory = await createTestTempDirectory("rea-cutter-command-responses-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; let response: unknown = { ok: true, execution_state: "complete" }; @@ -958,7 +946,7 @@ describe("CutterBridgeClient: scenario group 4", () => { }); it("returns unknown completion for invalid JSON and rejects a pre-aborted request", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-malformed-response-")); + directory = await createTestTempDirectory("rea-cutter-malformed-response-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; server = authenticatedServer( "synthetic-cutter-bridge-token-for-test", @@ -1009,14 +997,12 @@ describe("CutterBridgeClient: scenario group 5", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); it("handles malformed framed JSON and fragmented response frames", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-framed-response-")); + directory = await createTestTempDirectory("rea-cutter-framed-response-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; let malformed = false; server = authenticatedServer( @@ -1072,7 +1058,7 @@ describe("CutterBridgeClient: scenario group 5", () => { }); it("times out a dispatched bridge request without claiming completion", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-timeout-")); + directory = await createTestTempDirectory("rea-cutter-timeout-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; let markDispatched: (() => void) | undefined; const dispatched = new Promise((resolve) => { @@ -1120,14 +1106,12 @@ describe("CutterBridgeClient: scenario group 6", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); it("rejects bridge frames that exceed the bounded response size", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-large-response-")); + directory = await createTestTempDirectory("rea-cutter-large-response-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; server = authenticatedServer( "synthetic-cutter-bridge-token-for-test", @@ -1168,7 +1152,7 @@ describe("CutterBridgeClient: scenario group 6", () => { }); it("rejects stale sessions and preserves failures before command dispatch", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-stale-session-")); + directory = await createTestTempDirectory("rea-cutter-stale-session-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const client = createClient({ REA_CUTTER_BRIDGE_DIR: directory }); await expect( @@ -1199,58 +1183,62 @@ describe("CutterBridgeClient: scenario group 6", () => { ).rejects.toThrow("Cutter bridge is unavailable"); }); - it("filters descriptors with unsafe permissions and symbolic links", async () => { - if (process.platform === "win32") return; - directory = await mkdtemp(join(tmpdir(), "rea-cutter-unsafe-descriptor-")); - const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; - const token = "synthetic-cutter-bridge-token-for-test"; - server = statusServer(token, null, 0); - let connections = 0; - server.on("connection", () => { - connections += 1; - }); - const port = await listen(server); - const name = `cutter-${process.pid}-${sessionId}.json`; - const target = join(directory, "target.json"); - await writeDescriptor(directory, sessionId, port, token); - await writeFile(target, await readFile(join(directory, name)), { - mode: 0o600, - }); - await chmod(join(directory, name), 0o644); - await expect( - new CutterBridgeClient({ - REA_CUTTER_BRIDGE_DIR: directory, - }).listSessions(), - ).resolves.toMatchObject({ - sessions: [], - discovery_status: "no_live_bridge_found", - }); - expect(connections).toBe(0); - await rm(join(directory, name)); - await symlink(target, join(directory, name)); - await expect( - new CutterBridgeClient({ - REA_CUTTER_BRIDGE_DIR: directory, - }).listSessions(), - ).resolves.toMatchObject({ - sessions: [], - discovery_status: "no_live_bridge_found", - }); - expect(connections).toBe(0); - await rm(join(directory, name)); - await writeFile(join(directory, name), await readFile(target), { - mode: 0o600, - }); - await expect( - new CutterBridgeClient({ - REA_CUTTER_BRIDGE_DIR: directory, - }).listSessions(), - ).resolves.toMatchObject({ - sessions: [{ session_id: sessionId }], - discovery_status: "sessions_found", - }); - expect(connections).toBe(1); - }); + it.skipIf(process.platform === "win32")( + "filters descriptors with unsafe permissions and symbolic links", + async () => { + directory = await createTestTempDirectory( + "rea-cutter-unsafe-descriptor-", + ); + const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; + const token = "synthetic-cutter-bridge-token-for-test"; + server = statusServer(token, null, 0); + let connections = 0; + server.on("connection", () => { + connections += 1; + }); + const port = await listen(server); + const name = `cutter-${process.pid}-${sessionId}.json`; + const target = join(directory, "target.json"); + await writeDescriptor(directory, sessionId, port, token); + await writeFile(target, await readFile(join(directory, name)), { + mode: 0o600, + }); + await chmod(join(directory, name), 0o644); + await expect( + new CutterBridgeClient({ + REA_CUTTER_BRIDGE_DIR: directory, + }).listSessions(), + ).resolves.toMatchObject({ + sessions: [], + discovery_status: "no_live_bridge_found", + }); + expect(connections).toBe(0); + await rm(join(directory, name)); + await symlink(target, join(directory, name)); + await expect( + new CutterBridgeClient({ + REA_CUTTER_BRIDGE_DIR: directory, + }).listSessions(), + ).resolves.toMatchObject({ + sessions: [], + discovery_status: "no_live_bridge_found", + }); + expect(connections).toBe(0); + await rm(join(directory, name)); + await writeFile(join(directory, name), await readFile(target), { + mode: 0o600, + }); + await expect( + new CutterBridgeClient({ + REA_CUTTER_BRIDGE_DIR: directory, + }).listSessions(), + ).resolves.toMatchObject({ + sessions: [{ session_id: sessionId }], + discovery_status: "sessions_found", + }); + expect(connections).toBe(1); + }, + ); }); describe("CutterBridgeClient: scenario group 7", () => { @@ -1260,14 +1248,12 @@ describe("CutterBridgeClient: scenario group 7", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); it("retains large JSON integer digits in authenticated command evidence", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-json-output-")); + directory = await createTestTempDirectory("rea-cutter-json-output-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; server = authenticatedServer(token, sessionId, (request, respond) => { @@ -1325,7 +1311,7 @@ describe("CutterBridgeClient: scenario group 7", () => { }); it("handles an abort detected immediately after listener registration", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-abort-race-")); + directory = await createTestTempDirectory("rea-cutter-abort-race-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; await writeDescriptor( directory, @@ -1356,7 +1342,7 @@ describe("CutterBridgeClient: scenario group 7", () => { }); it("supports platforms without O_NOFOLLOW using the documented read-only flags", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-no-nofollow-")); + directory = await createTestTempDirectory("rea-cutter-no-nofollow-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; server = statusServer(token, null, 0); @@ -1395,14 +1381,12 @@ describe("CutterBridgeClient: conservative platform checks", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); directory = undefined; server = undefined; }); it("uses conservative platform and Windows descriptor checks", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-platform-checks-")); + directory = await createTestTempDirectory("rea-cutter-platform-checks-"); const getuid = vi .spyOn(process, "getuid") .mockImplementation(() => undefined as never); @@ -1499,14 +1483,12 @@ describe("CutterBridgeClient: bridge paths and native descriptor reads", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); it("uses the selected caller home for tilde and default bridge discovery", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-selected-home-")); + directory = await createTestTempDirectory("rea-cutter-selected-home-"); const selectedHome = join(directory, "selected-home"); const tildeDirectory = join(selectedHome, "bridge"); const defaultDirectory = join( @@ -1589,7 +1571,7 @@ describe("CutterBridgeClient: bridge paths and native descriptor reads", () => { }); it("uses the packaged Windows authority for descriptor verification and reads", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-native-reader-")); + directory = await createTestTempDirectory("rea-cutter-native-reader-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const token = "synthetic-cutter-bridge-token-for-test"; server = statusServer(token, null, 0); @@ -1654,8 +1636,6 @@ describe("CutterBridgeClient: scenario group 9", () => { afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); @@ -1680,7 +1660,7 @@ describe("CutterBridgeClient: scenario group 9", () => { }); it("accepts only the exact completed-command receipt from status", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-completion-receipt-")); + directory = await createTestTempDirectory("rea-cutter-completion-receipt-"); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; const staleId = "ede4bbfd-6348-46aa-963b-0de0e78ccbdc"; const token = "synthetic-cutter-bridge-token-for-test"; diff --git a/tests/boundary/providers/CutterBridgeNullIdentity.test.ts b/tests/boundary/providers/CutterBridgeNullIdentity.test.ts index 2afb39e3d8..30fd6407db 100644 --- a/tests/boundary/providers/CutterBridgeNullIdentity.test.ts +++ b/tests/boundary/providers/CutterBridgeNullIdentity.test.ts @@ -1,11 +1,12 @@ import { createServer } from "node:net"; import { createHmac } from "node:crypto"; import { readFileSync } from "node:fs"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { afterEach, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js"; @@ -17,8 +18,6 @@ let server: ReturnType | undefined; afterEach(async () => { if (server !== undefined) await new Promise((resolve) => server?.close(() => resolve())); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); server = undefined; directory = undefined; }); @@ -148,7 +147,7 @@ const writeDescriptor = async (port: number): Promise => { }; it("preserves a live Cutter status that explicitly has no active document", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-null-status-")); + directory = await createTestTempDirectory("rea-cutter-null-status-"); server = bridgeServer(null, 2); await writeDescriptor(await listen(server)); @@ -162,7 +161,7 @@ it("preserves a live Cutter status that explicitly has no active document", asyn }); it("preserves a null active document returned after a Cutter command", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-cutter-null-command-")); + directory = await createTestTempDirectory("rea-cutter-null-command-"); server = bridgeServer(null, 2); await writeDescriptor(await listen(server)); diff --git a/tests/boundary/providers/GdbCommandQueue.test.ts b/tests/boundary/providers/GdbCommandQueue.test.ts index e24e430e0e..d199fe05d2 100644 --- a/tests/boundary/providers/GdbCommandQueue.test.ts +++ b/tests/boundary/providers/GdbCommandQueue.test.ts @@ -6,6 +6,7 @@ import { } from "./gdbTestHelpers.js"; import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; + import { join } from "node:path"; import { afterEach, expect, it } from "vitest"; diff --git a/tests/boundary/providers/GdbSessionManagers.test.ts b/tests/boundary/providers/GdbSessionManagers.test.ts index 8634567450..6233c3bdaa 100644 --- a/tests/boundary/providers/GdbSessionManagers.test.ts +++ b/tests/boundary/providers/GdbSessionManagers.test.ts @@ -11,6 +11,7 @@ import { EventEmitter } from "node:events"; import { runInNewContext } from "node:vm"; import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; + import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; diff --git a/tests/boundary/providers/GdbSessionReviewRegressions.test.ts b/tests/boundary/providers/GdbSessionReviewRegressions.test.ts index 63e95edd4b..445e1b7c34 100644 --- a/tests/boundary/providers/GdbSessionReviewRegressions.test.ts +++ b/tests/boundary/providers/GdbSessionReviewRegressions.test.ts @@ -8,6 +8,7 @@ import { import { readFileSync } from "node:fs"; import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; + import { delimiter, join } from "node:path"; import { afterEach, expect, it } from "vitest"; diff --git a/tests/boundary/providers/RizinDebugSessionManagers.test.ts b/tests/boundary/providers/RizinDebugSessionManagers.test.ts index 49768049c6..98f5110437 100644 --- a/tests/boundary/providers/RizinDebugSessionManagers.test.ts +++ b/tests/boundary/providers/RizinDebugSessionManagers.test.ts @@ -1,8 +1,9 @@ -import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, writeFile } from "node:fs/promises"; + import { join, resolve } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { evidenceSchema } from "../../../src/domain/evidence.js"; import { @@ -23,13 +24,11 @@ describe.skipIf(process.platform === "win32")( .splice(0) .map((manager) => manager.closeAll().catch(() => undefined)), ); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); directory = undefined; }); it("uses an absolute target path and waits for Rizin's completion marker", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-manager-")); + directory = await createTestTempDirectory("rea-rizin-manager-"); const provider = join(directory, "fake-rizin.mjs"); const argsFile = join(directory, "args.json"); await writeFile( @@ -115,15 +114,13 @@ describe.skipIf(process.platform === "win32")( .splice(0) .map((manager) => manager.closeAll().catch(() => undefined)), ); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); directory = undefined; }); it.each(["stopped", "throw", "reject"] as const)( "retains timeout output and retryable cleanup when stop outcome is %s", async (stopOutcome) => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-timeout-")); + directory = await createTestTempDirectory("rea-rizin-timeout-"); const provider = join(directory, "fake-rizin-stall.mjs"); await writeFile( provider, @@ -215,7 +212,7 @@ process.stdin.on("data", (chunk) => { it.skipIf(process.platform === "win32")( "stops Rizin when empty unsolicited NUL frames exhaust the bounded queue", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-rizin-empty-frames-")); + const directory = await createTestTempDirectory("rea-rizin-empty-frames-"); const provider = join(directory, "fake-rizin-empty.mjs"); const manager = createRizinTestManager({ REA_RIZIN_COMMAND: provider, @@ -243,7 +240,6 @@ process.stdin.resume(); expect((await manager.close(started.value.session_id)).ok).toBe(true); } finally { await manager.closeAll().catch(() => undefined); - await rm(directory, { recursive: true, force: true }); } }, ); diff --git a/tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts b/tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts index 9fdd543edf..dd0b6988da 100644 --- a/tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts +++ b/tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts @@ -1,9 +1,10 @@ import { spawn, type ChildProcess } from "node:child_process"; -import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, readFile, writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { afterEach, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { phaseArrival } from "../../support/lifecycleHarness.js"; import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs"; @@ -98,8 +99,6 @@ afterEach(async () => { .splice(0) .map((manager) => manager.closeAll().catch(() => undefined)), ); - if (directory !== undefined) - await rm(directory, { recursive: true, force: true }); directory = undefined; }); @@ -122,7 +121,7 @@ const spawnTestInferior = async (): Promise => { const createInferiorInventoryProvider = async ( rows: readonly { readonly fd: number; readonly pid: number }[], ): Promise => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-owned-inferior-")); + directory = await createTestTempDirectory("rea-rizin-owned-inferior-"); const provider = join(directory, "fake-rizin-owned-inferior.mjs"); await writeFile( provider, @@ -290,7 +289,7 @@ it.skipIf(process.platform === "win32")( it.skipIf(process.platform === "win32")( "keeps session UTF-8 status cumulative while command evidence reports only its frames", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-utf8-scope-")); + directory = await createTestTempDirectory("rea-rizin-command-utf8-scope-"); const provider = join(directory, "fake-rizin-command-utf8-scope.mjs"); await writeFile( provider, @@ -425,7 +424,7 @@ it.skipIf(process.platform !== "linux")( it.skipIf(process.platform === "win32")( "retains Rizin cleanup when target state is unknown at debugger exit", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-unknown-target-")); + directory = await createTestTempDirectory("rea-rizin-unknown-target-"); const provider = join(directory, "fake-rizin-unknown-target.mjs"); await writeFile( provider, @@ -463,7 +462,7 @@ process.stdin.on("data", (chunk) => { it.skipIf(process.platform === "win32")( "preserves command parameters in Rizin observation evidence", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-evidence-")); + directory = await createTestTempDirectory("rea-rizin-command-evidence-"); const provider = join(directory, "fake-rizin-command-evidence.mjs"); const inferiorTty = await rizinTestInferiorTty(); await writeFile( @@ -520,7 +519,7 @@ process.stdin.on("data", (chunk) => { it.skipIf(process.platform === "win32")( "keeps queued Rizin commands serialized when a waiting request is cancelled", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-queue-cancel-")); + directory = await createTestTempDirectory("rea-rizin-queue-cancel-"); const provider = join(directory, "fake-rizin-queue-cancel.mjs"); const overlapPath = join(directory, "overlap"); await writeFile( @@ -565,7 +564,7 @@ process.stdin.on("data", (chunk) => { it.skipIf(process.platform === "win32")( "preserves a truncated single Rizin frame that exceeds the protocol limit", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-frame-overflow-")); + directory = await createTestTempDirectory("rea-rizin-frame-overflow-"); const provider = join(directory, "fake-rizin-frame-overflow.mjs"); await writeFile( provider, @@ -615,7 +614,7 @@ process.stdin.on("data", (chunk) => { it.skipIf(process.platform === "win32")( "returns bounded partial Rizin output with unknown completion after overflow", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-output-overflow-")); + directory = await createTestTempDirectory("rea-rizin-output-overflow-"); const provider = join(directory, "fake-rizin-output-overflow.mjs"); await writeFile( provider, @@ -659,7 +658,7 @@ process.stdin.on("data", (chunk) => { it.skipIf(process.platform === "win32")( "waits for the Rizin process to exit when command correlation times out", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-timeout-")); + directory = await createTestTempDirectory("rea-rizin-command-timeout-"); const provider = join(directory, "fake-rizin-command-timeout.mjs"); await writeFile( provider, @@ -707,7 +706,7 @@ process.stdin.on("data", () => process.stdout.write(Buffer.from([0xff, 0]))); it.skipIf(process.platform === "win32")( "cancels a running Rizin command and retains its closed status", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-cancel-")); + directory = await createTestTempDirectory("rea-rizin-command-cancel-"); const provider = join(directory, "fake-rizin-command-cancel.mjs"); await writeFile( provider, @@ -779,7 +778,7 @@ process.stdin.on("data", (chunk) => { it.skipIf(process.platform === "win32")( "reports bounded Rizin stderr retention in session status", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-diagnostic-limit-")); + directory = await createTestTempDirectory("rea-rizin-diagnostic-limit-"); const provider = join(directory, "fake-rizin-diagnostic-limit.mjs"); await writeFile( provider, @@ -811,7 +810,7 @@ process.stdin.resume(); it.skipIf(process.platform === "win32")( "returns cancellation when Rizin startup is cancelled after spawn", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-start-cancel-")); + directory = await createTestTempDirectory("rea-rizin-start-cancel-"); const provider = join(directory, "fake-rizin-start-cancel.mjs"); await writeFile( provider, @@ -855,7 +854,7 @@ it.skipIf(process.platform === "win32")( it.skipIf(process.platform === "win32")( "converts a Rizin stdin pipe failure into a provider session error", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-stdin-error-")); + directory = await createTestTempDirectory("rea-rizin-stdin-error-"); const provider = join(directory, "fake-rizin-stdin-error.mjs"); await writeFile( provider, @@ -888,7 +887,7 @@ setInterval(() => {}, 1000); it.skipIf(process.platform === "win32")( "preserves Rizin process-exit reason and partial command output", async () => { - directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-exit-")); + directory = await createTestTempDirectory("rea-rizin-command-exit-"); const provider = join(directory, "fake-rizin-command-exit.mjs"); const writerPidPath = join(directory, "writer.pid"); await writeFile( diff --git a/tests/boundary/providers/RizinDecoderInputs.test.ts b/tests/boundary/providers/RizinDecoderInputs.test.ts index 468e42039b..f4e8543d02 100644 --- a/tests/boundary/providers/RizinDecoderInputs.test.ts +++ b/tests/boundary/providers/RizinDecoderInputs.test.ts @@ -1,6 +1,7 @@ import { execFileSync } from "node:child_process"; import { mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; + import { join } from "node:path"; import { expect, it } from "vitest"; diff --git a/tests/boundary/providers/RizinInferiorExit.test.ts b/tests/boundary/providers/RizinInferiorExit.test.ts index 36ce76113c..434040502c 100644 --- a/tests/boundary/providers/RizinInferiorExit.test.ts +++ b/tests/boundary/providers/RizinInferiorExit.test.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; + import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; diff --git a/tests/boundary/providers/RizinInferiorTty.test.ts b/tests/boundary/providers/RizinInferiorTty.test.ts index e031f14ae3..6b7b1c3803 100644 --- a/tests/boundary/providers/RizinInferiorTty.test.ts +++ b/tests/boundary/providers/RizinInferiorTty.test.ts @@ -1,16 +1,10 @@ import { execFileSync, spawn as spawnChild } from "node:child_process"; -import { - chmod, - mkdtemp, - readFile, - realpath, - rm, - writeFile, -} from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, readFile, realpath, writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { spawn } from "@lydell/node-pty"; import { afterEach, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { assertRizinProcessStartTimeStable, @@ -84,8 +78,6 @@ afterEach(async () => { } } inferiorPid = undefined; - if (testDirectory !== undefined) - await rm(testDirectory, { recursive: true, force: true }); testDirectory = undefined; }); @@ -195,7 +187,7 @@ it.skipIf(process.platform !== "linux").each([ "validates Rizin `olj` close response: $name", async ({ response, closeSucceeds }) => { const tty = await rizinTestInferiorTty(); - testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-olj-")); + testDirectory = await createTestTempDirectory("rea-rizin-olj-"); const provider = join(testDirectory, "fake-rizin.cjs"); await writeFile( provider, @@ -447,7 +439,7 @@ it.skipIf( }); }); const tty = await realpath(ttyPath); - testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-tty-")); + testDirectory = await createTestTempDirectory("rea-rizin-tty-"); const wrapper = join(testDirectory, "rizin-with-long-lived-inferior.sh"); const pidPath = join(testDirectory, "target.pid"); const releasePath = join(testDirectory, "emit-output"); @@ -526,7 +518,7 @@ async function startFakeInferiorSession( } = {}, ): Promise { const tty = await realpath(await rizinTestInferiorTty()); - testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-protocol-")); + testDirectory = await createTestTempDirectory("rea-rizin-protocol-"); const targetPath = join(testDirectory, "inferior.mjs"); const pidPath = join(testDirectory, "target.pid"); const provider = join(testDirectory, "fake-rizin.cjs"); diff --git a/tests/boundary/providers/apktoolRuntimeExhaustion.test.ts b/tests/boundary/providers/apktoolRuntimeExhaustion.test.ts index c96d96e732..a8abe08e75 100644 --- a/tests/boundary/providers/apktoolRuntimeExhaustion.test.ts +++ b/tests/boundary/providers/apktoolRuntimeExhaustion.test.ts @@ -1,7 +1,8 @@ -import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { expect, onTestFinished, test } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { ApktoolProvider } from "../../../src/apktool/ApktoolProvider.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; @@ -9,8 +10,7 @@ const it = test.skipIf(process.platform === "win32"); /** A launcher whose decode prints the given stderr and exits with status 1. */ const failingDecode = async (stderr: string) => { - const root = await mkdtemp(join(tmpdir(), "rea-apktool-oom-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + const root = await createTestTempDirectory("rea-apktool-oom-"); const command = join(root, "apktool"); await writeFile( command, diff --git a/tests/boundary/providers/artifactReadCleanupRetry.test.ts b/tests/boundary/providers/artifactReadCleanupRetry.test.ts index 3e21464cd5..e0f15f69cc 100644 --- a/tests/boundary/providers/artifactReadCleanupRetry.test.ts +++ b/tests/boundary/providers/artifactReadCleanupRetry.test.ts @@ -1,8 +1,9 @@ import type { FileHandle } from "node:fs/promises"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; const cleanupState = vi.hoisted(() => ({ failFirstClose: false, @@ -58,7 +59,7 @@ import { peResourceFixture } from "../../../src/domain/pe/peResources.fixture.js it.each(["go", "pe"] as const)( "%s provider retains a failed descriptor close and retries that owner before the next read", async (kind) => { - const root = await mkdtemp(join(tmpdir(), "rea-read-cleanup-")); + const root = await createTestTempDirectory("rea-read-cleanup-"); const path = join(root, kind === "go" ? "program.elf" : "program.exe"); const bytes = kind === "go" ? createGoBinaryFixture().bytes : peResourceFixture().bytes; @@ -104,7 +105,6 @@ it.each(["go", "pe"] as const)( cleanupState.abortController = undefined; cleanupState.firstHandle = undefined; cleanupState.firstHandleCloseAttempts = 0; - await rm(root, { recursive: true, force: true }); } }, ); diff --git a/tests/boundary/providers/bundleResourceComposition.test.ts b/tests/boundary/providers/bundleResourceComposition.test.ts index c25c4370b7..9f296b36aa 100644 --- a/tests/boundary/providers/bundleResourceComposition.test.ts +++ b/tests/boundary/providers/bundleResourceComposition.test.ts @@ -1,10 +1,11 @@ import { unknownTarget } from "../../../src/domain/targetIdentity.js"; import { projectCliAnalysisResult } from "../../../src/cli/projectCliAnalysisResult.js"; -import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { build } from "plist"; -import { afterEach, expect, it } from "vitest"; +import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { parseConfig } from "../../../src/config/parseConfig.js"; import type { DirectAnalysisDependencies } from "../../../src/application/DirectAnalysisDependencies.js"; @@ -17,19 +18,8 @@ import { createNativeDispatchBinarySession, } from "../../../src/composition/binary.js"; -const temporaryDirectories: string[] = []; - -afterEach(async () => { - await Promise.all( - temporaryDirectories - .splice(0) - .map((path) => rm(path, { recursive: true, force: true })), - ); -}); - it("routes a CLI app resource path through the resource session and keeps the target identity unknown", async () => { - const bundlePath = await mkdtemp(join(tmpdir(), "rea-cli-resource-root-")); - temporaryDirectories.push(bundlePath); + const bundlePath = await createTestTempDirectory("rea-cli-resource-root-"); await mkdir(join(bundlePath, "Resources")); await writeFile( join(bundlePath, "Info.plist"), @@ -77,8 +67,7 @@ it("routes a CLI app resource path through the resource session and keeps the ta }); it("reports resource capabilities from their providers on supported and unsupported hosts", async () => { - const rootPath = await mkdtemp(join(tmpdir(), "rea-resource-capabilities-")); - temporaryDirectories.push(rootPath); + const rootPath = await createTestTempDirectory("rea-resource-capabilities-"); await writeFile(join(rootPath, "Info.plist"), ""); for (const [platform, expected] of [ diff --git a/tests/boundary/providers/cutterBridgeProducer.test.ts b/tests/boundary/providers/cutterBridgeProducer.test.ts index 52be788afe..5a03b6c22f 100644 --- a/tests/boundary/providers/cutterBridgeProducer.test.ts +++ b/tests/boundary/providers/cutterBridgeProducer.test.ts @@ -1,9 +1,10 @@ import { execFileSync } from "node:child_process"; -import { chmod, mkdtemp, rm } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod } from "node:fs/promises"; + import { join, resolve } from "node:path"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js"; import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js"; @@ -13,7 +14,7 @@ import { } from "../../../tests/support/process/processFixture.js"; const startPythonBridge = async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-cutter-receipt-")); + const directory = await createTestTempDirectory("rea-cutter-receipt-"); await chmod(directory, 0o700); const processes = createTestProcessRegistry(); const child = processes.spawn( @@ -77,11 +78,7 @@ const startPythonBridge = async () => { async close(): Promise { child.stdin.end("shutdown\n"); const exited = await waitForExit(child, 3_000); - try { - await processes.shutdown(); - } finally { - await rm(directory, { recursive: true, force: true }); - } + await processes.shutdown(); if (!exited) throw new Error(`Python bridge did not exit: ${stderr}`); }, }; @@ -89,7 +86,6 @@ const startPythonBridge = async () => { child.stdin.end("shutdown\n"); await waitForExit(child, 3_000); await processes.shutdown(); - await rm(directory, { recursive: true, force: true }); throw error; } }; diff --git a/tests/boundary/providers/cutterBridgeRequestLimit.test.ts b/tests/boundary/providers/cutterBridgeRequestLimit.test.ts index dc8b86214d..994b6caf11 100644 --- a/tests/boundary/providers/cutterBridgeRequestLimit.test.ts +++ b/tests/boundary/providers/cutterBridgeRequestLimit.test.ts @@ -1,10 +1,11 @@ import { bridgeMaxRequestBytesRecovery } from "../../../src/config/bridgeMaxRequestBytes.js"; import { createServer } from "node:net"; -import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, readFile, writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { expect, it, onTestFinished, vi } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js"; import { runWithAnalysisOperationSnapshot } from "../../../src/domain/analysisOperationSnapshot.js"; @@ -25,11 +26,8 @@ const SESSION = "00000000-0000-4000-8000-000000000001"; const TOKEN = "bridge-token-0123456789abcdef"; const privateDirectory = async (): Promise => { - const directory = await mkdtemp(join(tmpdir(), "rea-cutter-request-limit-")); + const directory = await createTestTempDirectory("rea-cutter-request-limit-"); await chmod(directory, 0o700); - onTestFinished(async () => { - await rm(directory, { recursive: true, force: true }); - }); return directory; }; diff --git a/tests/boundary/providers/desktopExportPython.test.ts b/tests/boundary/providers/desktopExportPython.test.ts index 8f7e8e4e73..1e62fe5c70 100644 --- a/tests/boundary/providers/desktopExportPython.test.ts +++ b/tests/boundary/providers/desktopExportPython.test.ts @@ -8,8 +8,6 @@ import { spawnSync, type ExecFileSyncOptionsWithStringEncoding, } from "node:child_process"; -import { mkdtempSync, writeFileSync, unlinkSync, rmdirSync } from "node:fs"; -import { tmpdir } from "node:os"; import { chmod, mkdir, @@ -38,34 +36,29 @@ import { withheldSettingsClass } from "../../../src/domain/desktop/appExportWith import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; /** Keep the exported Python helpers out of the host command-line size limit. */ -const execPython = ( +const execPython = async ( args: string[], options: ExecFileSyncOptionsWithStringEncoding, -): string => { - const directory = mkdtempSync(join(tmpdir(), "rea-export-python-")); +): Promise => { + const directory = await createTestTempDirectory("rea-export-python-"); const script = join(directory, "fixture.py"); const codeIndex = args.indexOf("-c"); - try { - writeFileSync(script, args[codeIndex + 1]!, "utf8"); - return execFileSync( - process.platform === "win32" ? "python" : "python3", - [ - "-X", - "utf8", - ...args.slice(0, codeIndex), - script, - ...args.slice(codeIndex + 2), - ], - options, - ); - } finally { - unlinkSync(script); - rmdirSync(directory); - } + await writeFile(script, args[codeIndex + 1]!, "utf8"); + return execFileSync( + process.platform === "win32" ? "python" : "python3", + [ + "-X", + "utf8", + ...args.slice(0, codeIndex), + script, + ...args.slice(codeIndex + 2), + ], + options, + ); }; /** The exported module's view format for each file, run with only its standard library imports. */ -const pythonFormats = (files: readonly (readonly [string, string])[]) => { +const pythonFormats = async (files: readonly (readonly [string, string])[]) => { const imports = PYTHON_IMPORTS.split("\n") .filter((line) => !line.includes("agentenv_protocol")) .join("\n"); @@ -73,15 +66,17 @@ const pythonFormats = (files: readonly (readonly [string, string])[]) => { for name, text in json.load(sys.stdin): print(_text_view(name, text, len(text.encode()))["format"]) `; - return execPython(["-I", "-B", "-c", program], { - input: JSON.stringify(files), - encoding: "utf8", - }) + return ( + await execPython(["-I", "-B", "-c", program], { + input: JSON.stringify(files), + encoding: "utf8", + }) + ) .trim() .split(/\r?\n/u); }; -it("detects Unicode XML names in both state readers while rejecting non-XML text", () => { +it("detects Unicode XML names in both state readers while rejecting non-XML text", async () => { const files = [ ["map.dat", '<地图 名称="甲"><节点/>'], ["map.dat", '<地图/>'], @@ -110,7 +105,7 @@ it("detects Unicode XML names in both state readers while rejecting non-XML text "text", "text", ]; - expect(pythonFormats(files)).toEqual(expected); + expect(await pythonFormats(files)).toEqual(expected); expect( files.map(([name, text]) => detectStateFormat(name, new TextEncoder().encode(text)), @@ -118,7 +113,7 @@ it("detects Unicode XML names in both state readers while rejecting non-XML text ).toEqual(expected); }); -it("detects key files by the state view's rule rather than a name or any group header", () => { +it("detects key files by the state view's rule rather than a name or any group header", async () => { const files = [ ["list.txt", "Groceries\n[x]\nmilk\n"], ["settings.ini", "free text\n"], @@ -127,7 +122,7 @@ it("detects key files by the state view's rule rather than a name or any group h ["notes.rc", "[a]\r\nkey = value\r\n"], ] as const; - const formats = pythonFormats(files); + const formats = await pythonFormats(files); expect(formats).toEqual(["text", "text", "text", "keyfile", "keyfile"]); expect(formats).toEqual( @@ -137,7 +132,7 @@ it("detects key files by the state view's rule rather than a name or any group h ); }); -it("keeps JSON Lines holding a number it cannot read exactly as text, as REA does", () => { +it("keeps JSON Lines holding a number it cannot read exactly as text, as REA does", async () => { const lines = '{"id":9007199254740993}\n{"id":2}\n'; const files = [ ["events.jsonl", lines], @@ -147,7 +142,7 @@ it("keeps JSON Lines holding a number it cannot read exactly as text, as REA doe ["long.json", `{"id":${"9".repeat(5000)}}`], ] as const; - const formats = pythonFormats(files); + const formats = await pythonFormats(files); expect(formats).toEqual(["text", "text", "json", "json", "json"]); expect(formats).toEqual( @@ -158,7 +153,7 @@ it("keeps JSON Lines holding a number it cannot read exactly as text, as REA doe }); /** The exported module's UTF-16 seed respelling of each file, from /home/ada to /home/user, as hex. */ -const pythonUtf16Respelled = (files: readonly string[]) => { +const pythonUtf16Respelled = async (files: readonly string[]) => { const imports = PYTHON_IMPORTS.split("\n") .filter((line) => !line.includes("agentenv_protocol")) .join("\n"); @@ -169,10 +164,12 @@ ${PYTHON_HELPERS} for data in json.load(sys.stdin): print(_respelled_utf16(bytes.fromhex(data), PurePosixPath("/home/user")).hex()) `; - return execPython(["-I", "-B", "-c", program], { - input: JSON.stringify(files), - encoding: "utf8", - }) + return ( + await execPython(["-I", "-B", "-c", program], { + input: JSON.stringify(files), + encoding: "utf8", + }) + ) .trim() .split(/\r?\n/u); }; @@ -182,7 +179,7 @@ const utf16 = (text: string, order: "le" | "be") => { return order === "le" ? le : Buffer.from(le).swap16(); }; -it("respells the captured home in UTF-16 seeds with a byte-order mark, keeping the mark and order", () => { +it("respells the captured home in UTF-16 seeds with a byte-order mark, keeping the mark and order", async () => { const work = "# build\n20260216;1;/home/ada/.varicad\n"; const files = [ utf16(work, "le"), @@ -193,7 +190,7 @@ it("respells the captured home in UTF-16 seeds with a byte-order mark, keeping t Buffer.from("/home/ada/plain\n"), ]; - const respelled = pythonUtf16Respelled( + const respelled = await pythonUtf16Respelled( files.map((file) => file.toString("hex")), ); @@ -258,7 +255,7 @@ home = Path(sys.argv[1]) _ensure_state_aliases(home) _ensure_state_aliases(home) `; - execPython(["-I", "-B", "-c", program, home], { encoding: "utf8" }); + await execPython(["-I", "-B", "-c", program, home], { encoding: "utf8" }); expect( await readFile(join(home, "settings", "profile", "profile.ini"), "utf8"), ).toBe("profile"); @@ -279,7 +276,7 @@ ${PYTHON_HELPERS} home = Path(sys.argv[1]) _ensure_state_aliases(home) `; - execPython(["-I", "-B", "-c", program, home], { encoding: "utf8" }); + await execPython(["-I", "-B", "-c", program, home], { encoding: "utf8" }); expect( await readFile(join(home, "settings", "profile", "profile.ini"), "utf8"), ).toBe("profile"); @@ -303,7 +300,7 @@ home = Path(sys.argv[1]) _ensure_state_aliases(home) _ensure_state_aliases(home) `; - execPython(["-I", "-B", "-c", program, home], { encoding: "utf8" }); + await execPython(["-I", "-B", "-c", program, home], { encoding: "utf8" }); expect(await readFile(join(home, "settings"), "utf8")).toBe("saved"); const absent = join(root, "absent"); @@ -314,7 +311,9 @@ ${PYTHON_HELPERS} home = Path(sys.argv[1]) _ensure_state_aliases(home) `; - execPython(["-I", "-B", "-c", absentProgram, absent], { encoding: "utf8" }); + await execPython(["-I", "-B", "-c", absentProgram, absent], { + encoding: "utf8", + }); await writeFile(join(absent, "settings"), "created"); expect(await readFile(join(absent, ".config", "tellicorc"), "utf8")).toBe( "created", @@ -324,7 +323,9 @@ _ensure_state_aliases(home) ); const bare = join(root, "bare"); await mkdir(bare); - execPython(["-I", "-B", "-c", absentProgram, bare], { encoding: "utf8" }); + await execPython(["-I", "-B", "-c", absentProgram, bare], { + encoding: "utf8", + }); await writeFile(join(bare, "settings"), "created"); expect(await readFile(join(bare, ".config", "tellicorc"), "utf8")).toBe( "created", @@ -338,7 +339,9 @@ ${PYTHON_HELPERS} home = Path(sys.argv[1]) _ensure_state_aliases(home) `; - execPython(["-I", "-B", "-c", legacyProgram, legacy], { encoding: "utf8" }); + await execPython(["-I", "-B", "-c", legacyProgram, legacy], { + encoding: "utf8", + }); await writeFile(join(legacy, "settings"), "legacy"); expect(await readFile(join(legacy, ".config", "tellicorc"), "utf8")).toBe( "legacy", @@ -378,7 +381,7 @@ _seed_home(home) _ensure_state_aliases(home) _ensure_state_aliases(home) `; - execPython( + await execPython( ["-I", "-B", "-c", program, root, home, JSON.stringify("directory")], { encoding: "utf8" }, ); @@ -394,7 +397,7 @@ _ensure_state_aliases(home) const other = join(root, "other-home"); await mkdir(other); await writeFile(join(other, "settings"), "preserve"); - expect(() => + await expect( execPython( ["-I", "-B", "-c", program, root, other, JSON.stringify("directory")], { @@ -402,14 +405,14 @@ _ensure_state_aliases(home) stdio: "pipe", }, ), - ).toThrow(); + ).rejects.toThrow(); expect(await readFile(join(other, "settings"), "utf8")).toBe("preserve"); const empty = join(root, "empty-home"); await mkdir(empty); const emptySeed = join(root, "empty-seed"); await mkdir(emptySeed); - execPython( + await execPython( ["-I", "-B", "-c", program, emptySeed, empty, JSON.stringify("directory")], { encoding: "utf8", @@ -423,7 +426,7 @@ _ensure_state_aliases(home) // An older capture does not establish the missing target's kind. const unknown = join(root, "unknown-home"); await mkdir(unknown); - execPython(["-I", "-B", "-c", program, emptySeed, unknown, "null"], { + await execPython(["-I", "-B", "-c", program, emptySeed, unknown, "null"], { encoding: "utf8", }); expect(await readlink(join(unknown, "settings"))).toBe( @@ -454,23 +457,28 @@ else: return bin; }; -const taskbarWindow = (bin: string, windowClass: string): string => { +const taskbarWindow = async ( + bin: string, + windowClass: string, +): Promise => { const imports = PYTHON_IMPORTS.split("\n") .filter((line) => !line.includes("agentenv_protocol")) .join("\n"); - return execPython( - [ - "-I", - "-B", - "-c", - `${imports}\nfrom pathlib import PurePosixPath + return ( + await execPython( + [ + "-I", + "-B", + "-c", + `${imports}\nfrom pathlib import PurePosixPath SEED_HOME = "/home/ada"\n${PYTHON_HELPERS}\nprint(_taskbar_window(sys.argv[1]))`, - windowClass, - ], - { - encoding: "utf8", - env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}` }, - }, + windowClass, + ], + { + encoding: "utf8", + env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}` }, + }, + ) ).trim(); }; @@ -482,22 +490,28 @@ it("holds readiness until a window of the app's class that the taskbar lists is const other = 'WM_CLASS(STRING) = "mousepad", "Mousepad"\n_NET_WM_STATE(ATOM) = '; - expect(taskbarWindow(await fakeXprop({ "0x1": splash }), "varicad")).toBe( - "False", - ); expect( - taskbarWindow(await fakeXprop({ "0x1": splash, "0x2": main }), "varicad"), + await taskbarWindow(await fakeXprop({ "0x1": splash }), "varicad"), + ).toBe("False"); + expect( + await taskbarWindow( + await fakeXprop({ "0x1": splash, "0x2": main }), + "varicad", + ), ).toBe("True"); expect( - taskbarWindow(await fakeXprop({ "0x1": splash, "0x3": other }), "varicad"), + await taskbarWindow( + await fakeXprop({ "0x1": splash, "0x3": other }), + "varicad", + ), ).toBe("False"); - expect(taskbarWindow(await fakeXprop({ "0x3": other }), "Mousepad")).toBe( - "True", - ); + expect( + await taskbarWindow(await fakeXprop({ "0x3": other }), "Mousepad"), + ).toBe("True"); const typedSplash = 'WM_CLASS(STRING) = "varicad", "varicad"\n_NET_WM_STATE(ATOM) = \n_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_SPLASH'; expect( - taskbarWindow(await fakeXprop({ "0x4": typedSplash }), "varicad"), + await taskbarWindow(await fakeXprop({ "0x4": typedSplash }), "varicad"), ).toBe("False"); }); @@ -547,12 +561,12 @@ it.each([ ])( "interprets X11 readiness when xprop %s", async (_, windows, class_, ready) => { - expect(taskbarWindow(await fakeXprop(windows), class_)).toBe(ready); + expect(await taskbarWindow(await fakeXprop(windows), class_)).toBe(ready); }, ); /** The exported module's JSON verdict for each text, with only its standard library imports: its view or its error. */ -const pythonJson = (texts: readonly string[]) => { +const pythonJson = async (texts: readonly string[]) => { const imports = PYTHON_IMPORTS.split("\n") .filter((line) => !line.includes("agentenv_protocol")) .join("\n"); @@ -560,16 +574,18 @@ const pythonJson = (texts: readonly string[]) => { for text in json.load(sys.stdin): print(json.dumps(_text_view("a.json", text, len(text.encode())))) `; - return execPython(["-I", "-B", "-c", program], { - input: JSON.stringify(texts), - encoding: "utf8", - }) + return ( + await execPython(["-I", "-B", "-c", program], { + input: JSON.stringify(texts), + encoding: "utf8", + }) + ) .trim() .split(/\r?\n/u) .map((line) => JSON.parse(line) as { view: unknown; error?: string }); }; -it("refuses the JSON numbers REA's state view refuses, as JSON with an error rather than an infinity", () => { +it("refuses the JSON numbers REA's state view refuses, as JSON with an error rather than an infinity", async () => { const texts = [ '{"a": 1e999}', '{"a": -1e999}', @@ -583,7 +599,7 @@ it("refuses the JSON numbers REA's state view refuses, as JSON with an error rat '{"a": 1, "a": 9007199254740993}', ]; - const python = pythonJson(texts); + const python = await pythonJson(texts); texts.forEach((text, index) => { const typescript = textualView("json", new TextEncoder().encode(text)); @@ -594,7 +610,7 @@ it("refuses the JSON numbers REA's state view refuses, as JSON with an error rat }); /** The exported module's format, view and error for each named text, and REA's for the same bytes. */ -const textViews = ( +const textViews = async ( files: readonly (readonly [string, string])[], policy: DesktopViewPolicy = DESKTOP_VIEW_DEFAULTS, ) => { @@ -606,11 +622,13 @@ for name, text in json.load(sys.stdin): view = _text_view(name, text, len(text.encode())) print(json.dumps({"format": view["format"], "view": view["view"], "error": view.get("error")})) `; - const python = execPython(["-I", "-B", "-c", program], { - input: JSON.stringify(files), - encoding: "utf8", - maxBuffer: 64 * 1024 * 1024, - }) + const python = ( + await execPython(["-I", "-B", "-c", program], { + input: JSON.stringify(files), + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + }) + ) .trim() .split("\n") .map((line) => JSON.parse(line) as unknown); @@ -627,12 +645,12 @@ for name, text in json.load(sys.stdin): return { python, rea }; }; -it("applies the selected desktop view budgets equally in TypeScript and emitted Python", () => { +it("applies the selected desktop view budgets equally in TypeScript and emitted Python", async () => { const files = [ ["lines.txt", "one\ntwo\nthree"], ["value.json", '{"key":"value"}'], ] as const; - const limited = textViews( + const limited = await textViews( files, desktopViewPolicy({ text_lines: 2, parsed_bytes: 4 }), ); @@ -643,7 +661,7 @@ it("applies the selected desktop view budgets equally in TypeScript and emitted line_count: 3, }); expect(limited.rea[1]?.error).toContain("limit for JSON"); - const recovered = textViews( + const recovered = await textViews( files, desktopViewPolicy({ text_lines: 3, parsed_bytes: 64 }), ); @@ -659,7 +677,7 @@ it("applies the selected desktop view budgets equally in TypeScript and emitted }); }); -it("bounds the emitted reader's probe when an app grows a file after its size check", () => { +it("bounds the emitted reader's probe when an app grows a file after its size check", async () => { const imports = PYTHON_IMPORTS.split("\n") .filter((line) => !line.includes("agentenv_protocol")) .join("\n"); @@ -693,7 +711,7 @@ with tempfile.TemporaryDirectory() as root: print(json.dumps({"ordinary": ordinary, "grown": grown, "read_bytes": read_bytes, "grown_bytes": growing.stat().st_size})) `; const result = JSON.parse( - execPython(["-I", "-B", "-c", program], { encoding: "utf8" }), + await execPython(["-I", "-B", "-c", program], { encoding: "utf8" }), ); expect(result.ordinary).toMatchObject({ format: "text", @@ -709,7 +727,7 @@ with tempfile.TemporaryDirectory() as root: expect(result.grown_bytes).toBe(20000); }); -it("reads text nested past Python's recursion limit as JSON only when all of it is, as REA does", () => { +it("reads text nested past Python's recursion limit as JSON only when all of it is, as REA does", async () => { const brackets = (open: number, close: number) => `${"[".repeat(open)}${"]".repeat(close)}`; const files = [ @@ -719,7 +737,7 @@ it("reads text nested past Python's recursion limit as JSON only when all of it ["deep.json", `${brackets(1100, 1100)} x`], ] as const; - const { python, rea } = textViews(files); + const { python, rea } = await textViews(files); expect(python).toEqual(rea); expect(rea.map(({ format, error }) => [format, error])).toEqual([ @@ -730,7 +748,7 @@ it("reads text nested past Python's recursion limit as JSON only when all of it ]); }); -it("refuses JSON and key files over 4 MiB as REA does, telling JSON apart from text without parsing it", () => { +it("refuses JSON and key files over 4 MiB as REA does, telling JSON apart from text without parsing it", async () => { const objects = `[{}${",{}".repeat(1_400_000)}]`; const files = [ ["objects.json", objects], @@ -739,7 +757,7 @@ it("refuses JSON and key files over 4 MiB as REA does, telling JSON apart from t ["log", `[0] ${"x".repeat(4_200_000)}`], ] as const; - const { python, rea } = textViews(files); + const { python, rea } = await textViews(files); expect(python).toEqual(rea); const refused = "larger than the 4 MiB limit for JSON and key file views"; @@ -751,7 +769,7 @@ it("refuses JSON and key files over 4 MiB as REA does, telling JSON apart from t ]); }); -it("checks text for JSON the way REA does, token by token, without parsing it", () => { +it("checks text for JSON the way REA does, token by token, without parsing it", async () => { const [bom, nbsp, lineSeparator] = [0xfeff, 0xa0, 0x2028].map((code) => String.fromCharCode(code), ); @@ -768,7 +786,7 @@ it("checks text for JSON the way REA does, token by token, without parsing it", .join("\n"); const python = JSON.parse( - execPython( + await execPython( [ "-I", "-B", @@ -788,7 +806,7 @@ it("checks text for JSON the way REA does, token by token, without parsing it", expect(parsed.filter(Boolean)).toHaveLength(10); }); -it("checks JSON depth with one iterator per level, copying no wide list", () => { +it("checks JSON depth with one iterator per level, copying no wide list", async () => { const imports = PYTHON_IMPORTS.split("\n") .filter((line) => !line.includes("agentenv_protocol")) .join("\n"); @@ -807,7 +825,7 @@ print(json.dumps({"deep": deep, "peak": peak, "edge": _deeper_than(nested, 501), `; const result = JSON.parse( - execPython(["-I", "-B", "-c", program], { encoding: "utf8" }), + await execPython(["-I", "-B", "-c", program], { encoding: "utf8" }), ) as { deep: boolean; peak: number; edge: boolean; over: boolean }; expect(result).toMatchObject({ deep: false, edge: false, over: true }); @@ -815,11 +833,11 @@ print(json.dumps({"deep": deep, "peak": peak, "edge": _deeper_than(nested, 501), expect(result.peak).toBeLessThan(1024 * 1024); }); -it("keeps special SQLite numbers distinct from text in exported table views", () => { +it("keeps special SQLite numbers distinct from text in exported table views", async () => { const imports = PYTHON_IMPORTS.split("\n") .filter((line) => !line.includes("agentenv_protocol")) .join("\n"); - const cells = execPython( + const cells = await execPython( [ "-I", "-B", @@ -853,7 +871,7 @@ with sqlite3.connect(":memory:") as db: }); }); -it("agrees on keyfile whitespace in both state readers", () => { +it("agrees on keyfile whitespace in both state readers", async () => { const files = [ ["settings.ini", "[ui]\n\u0085\nzoom=2\n"], ["settings.ini", "[ui]\n\ufeffzoom=2\n"], @@ -887,7 +905,7 @@ it("agrees on keyfile whitespace in both state readers", () => { error: null, }, ]; - const { python, rea } = textViews(files); + const { python, rea } = await textViews(files); expect(rea).toEqual(expected); expect(python).toEqual(expected); }); @@ -923,7 +941,7 @@ ${PYTHON_HELPERS} settings = Exported.Settings(**{name: "YQ==" for name in json.loads(sys.argv[2])}) _write_withheld(Path(sys.argv[1]), settings, json.loads(sys.argv[3])) `; - execPython( + await execPython( [ "-B", "-c", diff --git a/tests/boundary/providers/desktopLaunchCommand.test.ts b/tests/boundary/providers/desktopLaunchCommand.test.ts index 51767a524b..69203d116c 100644 --- a/tests/boundary/providers/desktopLaunchCommand.test.ts +++ b/tests/boundary/providers/desktopLaunchCommand.test.ts @@ -1,16 +1,11 @@ import { expect, it } from "vitest"; import { spawnSync } from "node:child_process"; -import { - existsSync, - mkdtempSync, - realpathSync, - rmSync, - writeFileSync, -} from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, realpathSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + import { capturedHomePlan, launchCommand, @@ -23,80 +18,72 @@ it.skipIf(process.platform === "win32").each([ ["-iC", true], ])( "replays an empty directory selected by env %s with the expected environment", - (option, clean) => { - const home = mkdtempSync(join(tmpdir(), "rea-working-home-")); - try { - const selected = "Projects/Empty workspace"; - const capture = { - host: { home: "/home/ada" }, - application: { - argv: [ - "/usr/bin/env", - option, - `/home/ada/${selected}`, - process.execPath, - "-e", - "console.log(process.cwd()); console.log(process.env.REA_REPLAY_MARKER)", - ], - working_directory: "/home/ada/ambient", - application_working_directory: `/home/ada/${selected}`, - state_directories: [], - }, - state: { state_directories: [] }, - } as unknown as DesktopApplicationCapture; - const { - command: [program, ...args], - } = planLaunch(capture, false, new Map(), { - ...capturedHomePlan(capture), - files: new Map(), - restoredFiles: [], - }); - const result = spawnSync(program!, args, { - encoding: "utf8", - env: { ...process.env, HOME: home, REA_REPLAY_MARKER: "inherited" }, - }); - expect(result.status, result.stderr).toBe(0); - expect(result.stdout.trimEnd().split("\n")).toEqual([ - join(realpathSync(home), selected), - clean ? "undefined" : "inherited", - ]); - } finally { - rmSync(home, { recursive: true, force: true }); - } + async (option, clean) => { + const home = await createTestTempDirectory("rea-working-home-"); + const selected = "Projects/Empty workspace"; + const capture = { + host: { home: "/home/ada" }, + application: { + argv: [ + "/usr/bin/env", + option, + `/home/ada/${selected}`, + process.execPath, + "-e", + "console.log(process.cwd()); console.log(process.env.REA_REPLAY_MARKER)", + ], + working_directory: "/home/ada/ambient", + application_working_directory: `/home/ada/${selected}`, + state_directories: [], + }, + state: { state_directories: [] }, + } as unknown as DesktopApplicationCapture; + const { + command: [program, ...args], + } = planLaunch(capture, false, new Map(), { + ...capturedHomePlan(capture), + files: new Map(), + restoredFiles: [], + }); + const result = spawnSync(program!, args, { + encoding: "utf8", + env: { ...process.env, HOME: home, REA_REPLAY_MARKER: "inherited" }, + }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trimEnd().split("\n")).toEqual([ + join(realpathSync(home), selected), + clean ? "undefined" : "inherited", + ]); }, ); it.skipIf(process.platform === "win32")( "does not import seeded Python modules while encoding a file URL", - () => { - const home = mkdtempSync(join(tmpdir(), "rea-url-home-")); - try { - writeFileSync( - join(home, "urllib.py"), - 'open("seed-ran", "w").write("unexpected")\n', - ); - const command = launchCommand( - [ - process.execPath, - "-e", - "process.stdout.write(process.argv[1])", - "file:///home/ada/Documents/report.txt", - ], - "/home/ada", - "/home/ada", - ); - const result = spawnSync(command[0]!, command.slice(1), { - encoding: "utf8", - env: { ...process.env, HOME: home }, - }); - expect(result.status).toBe(0); - expect(result.stdout).toBe( - pathToFileURL(join(home, "Documents/report.txt")).href, - ); - expect(existsSync(join(home, "seed-ran"))).toBe(false); - } finally { - rmSync(home, { recursive: true, force: true }); - } + async () => { + const home = await createTestTempDirectory("rea-url-home-"); + writeFileSync( + join(home, "urllib.py"), + 'open("seed-ran", "w").write("unexpected")\n', + ); + const command = launchCommand( + [ + process.execPath, + "-e", + "process.stdout.write(process.argv[1])", + "file:///home/ada/Documents/report.txt", + ], + "/home/ada", + "/home/ada", + ); + const result = spawnSync(command[0]!, command.slice(1), { + encoding: "utf8", + env: { ...process.env, HOME: home }, + }); + expect(result.status).toBe(0); + expect(result.stdout).toBe( + pathToFileURL(join(home, "Documents/report.txt")).href, + ); + expect(existsSync(join(home, "seed-ran"))).toBe(false); }, ); diff --git a/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts b/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts index 0edffa6b6a..90e11e5c04 100644 --- a/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts +++ b/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts @@ -1,14 +1,8 @@ import { afterEach, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; import { createHash } from "node:crypto"; -import { - access, - mkdtemp, - readFile, - readdir, - rm, - writeFile, -} from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { access, readFile, readdir, rm, writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { ArtifactResourceScope } from "../../../../src/resources/ArtifactResourceScope.js"; import { createAnalysisProfile } from "../../../../src/domain/analysisProfile.js"; @@ -23,8 +17,7 @@ vi.mock("node:fs/promises", async (importOriginal) => { return { ...actual, rm: vi.fn(actual.rm) }; }); -const roots: string[] = [], - clients: GhidraClient[] = [], +const clients: GhidraClient[] = [], launchers: GhidraFixtureLauncher[] = []; afterEach(async () => { const actual = @@ -36,8 +29,6 @@ afterEach(async () => { for (const child of launcher.processes) if (child.connected) child.send("release_checkpoint"); for (const client of clients.splice(0)) await client.close(); - for (const root of roots.splice(0)) - await rm(root, { recursive: true, force: true }); }); it.skipIf(process.platform === "win32")( @@ -76,8 +67,7 @@ async function fixture( mode: ConstructorParameters[0] = "checkpoint", bridgeMaxReplyBytes?: BridgeMaxReplyBytes, ) { - const root = await mkdtemp(join(tmpdir(), "rea-checkpoint-lifecycle-")); - roots.push(root); + const root = await createTestTempDirectory("rea-checkpoint-lifecycle-"); const targetPath = join(root, "target"); await writeFile(targetPath, "source target bytes"); const sha256 = createHash("sha256") diff --git a/tests/boundary/providers/hopper/hopperFileOffsetClose.test.ts b/tests/boundary/providers/hopper/hopperFileOffsetClose.test.ts index be51702182..1ee06b8744 100644 --- a/tests/boundary/providers/hopper/hopperFileOffsetClose.test.ts +++ b/tests/boundary/providers/hopper/hopperFileOffsetClose.test.ts @@ -1,15 +1,10 @@ import { createHash } from "node:crypto"; -import { - mkdir, - mkdtemp, - rm, - writeFile, - type FileHandle, -} from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, rm, writeFile, type FileHandle } from "node:fs/promises"; + import { join } from "node:path"; import { expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; import { createAnalysisProfile } from "../../../../src/domain/analysisProfile.js"; import { @@ -104,7 +99,7 @@ const clientFor = async (path: string, bytes: Buffer) => { }; it("preserves file-offset reads and retries the exact descriptor after close fails", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-hopper-file-offset-close-")); + const root = await createTestTempDirectory("rea-hopper-file-offset-close-"); const bytes = Buffer.alloc(64); bytes.writeUInt32LE(0xfeedfacf, 0); bytes.writeUInt32LE(0x0100000c, 4); @@ -240,12 +235,11 @@ it("preserves file-offset reads and retries the exact descriptor after close fai state.fail = false; for (const entry of state.handles) await entry.close(); await client.close(); - await rm(root, { recursive: true, force: true }); } }); it("clears a combined Hopper close only after the descriptor and session release", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-hopper-combined-close-")); + const root = await createTestTempDirectory("rea-hopper-combined-close-"); const bytes = Buffer.alloc(64); bytes.writeUInt32LE(0xfeedfacf, 0); bytes.writeUInt32LE(0x0100000c, 4); @@ -308,15 +302,14 @@ it("clears a combined Hopper close only after the descriptor and session release state.fail = false; for (const entry of state.handles) await entry.close(); await client.close(); - await rm(root, { recursive: true, force: true }); } }); it.each([false, true])( "retains a source metadata failure when cancellation arrives during close (close failure: %s)", async (closeFails) => { - const root = await mkdtemp( - join(tmpdir(), "rea-hopper-file-offset-primary-"), + const root = await createTestTempDirectory( + "rea-hopper-file-offset-primary-", ); const bytes = Buffer.alloc(64); state.path = join(root, "sample"); @@ -359,7 +352,6 @@ it.each([false, true])( state.abortOnClose = undefined; call.mockRestore(); await client.close(); - await rm(root, { recursive: true, force: true }); } }, ); @@ -367,8 +359,8 @@ it.each([false, true])( it.each([false, true])( "retains verified source coordinates when cancellation arrives during close (close failure: %s)", async (closeFails) => { - const root = await mkdtemp( - join(tmpdir(), "rea-hopper-file-offset-cancel-"), + const root = await createTestTempDirectory( + "rea-hopper-file-offset-cancel-", ); const bytes = Buffer.alloc(64); state.path = join(root, "sample"); @@ -425,7 +417,6 @@ it.each([false, true])( state.abortOnClose = undefined; call.mockRestore(); await client.close(); - await rm(root, { recursive: true, force: true }); } }, ); @@ -433,7 +424,7 @@ it.each([false, true])( it.each([false, true])( "uses the descriptor read outcome when cancellation and an I/O result coincide (read failure: %s)", async (readFails) => { - const root = await mkdtemp(join(tmpdir(), "rea-hopper-file-offset-read-")); + const root = await createTestTempDirectory("rea-hopper-file-offset-read-"); const bytes = Buffer.alloc(64); state.path = join(root, "sample"); await writeFile(state.path, bytes); @@ -473,13 +464,12 @@ it.each([false, true])( state.afterRead = undefined; call.mockRestore(); await client.close(); - await rm(root, { recursive: true, force: true }); } }, ); it("retains a changed source digest without publishing verified coordinates after late cancellation", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-hopper-file-offset-changed-")); + const root = await createTestTempDirectory("rea-hopper-file-offset-changed-"); const bytes = Buffer.alloc(64); state.path = join(root, "sample"); await writeFile(state.path, bytes); @@ -512,6 +502,5 @@ it("retains a changed source digest without publishing verified coordinates afte state.abortOnClose = undefined; call.mockRestore(); await client.close(); - await rm(root, { recursive: true, force: true }); } }); diff --git a/tests/boundary/providers/hopper/linuxPrivateDisplay.test.ts b/tests/boundary/providers/hopper/linuxPrivateDisplay.test.ts index fa0f9bd5c9..a2f71fdbc1 100644 --- a/tests/boundary/providers/hopper/linuxPrivateDisplay.test.ts +++ b/tests/boundary/providers/hopper/linuxPrivateDisplay.test.ts @@ -3,8 +3,9 @@ import { spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; import { describe, expect, it, onTestFinished, vi } from "vitest"; -import { access, mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; +import { access, writeFile } from "node:fs/promises"; + import { join } from "node:path"; import * as ownership from "../../../../src/process/ProcessOwnership.js"; @@ -467,7 +468,7 @@ it("passes the private X authority cookie through xauth stdin", () => { }); const inertProbe = async (keepLeader = false) => { - const root = await mkdtemp(join(tmpdir(), "rea-private-display-lifecycle-")); + const root = await createTestTempDirectory("rea-private-display-lifecycle-"); const marker = join(root, "descendant-survived"); const ready = join(root, "ready"); const helper = join(root, "probe.py"); @@ -483,7 +484,6 @@ const inertProbe = async (keepLeader = false) => { ...(keepLeader ? ["time.sleep(2)"] : []), ].join("\n"), ); - onTestFinished(() => rm(root, { recursive: true, force: true })); return { helper, marker, ready }; }; diff --git a/tests/boundary/providers/ida/verifierRequirements.test.ts b/tests/boundary/providers/ida/verifierRequirements.test.ts index 403ed4dc42..20ed9497b6 100644 --- a/tests/boundary/providers/ida/verifierRequirements.test.ts +++ b/tests/boundary/providers/ida/verifierRequirements.test.ts @@ -1,9 +1,10 @@ import { execFile } from "node:child_process"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { promisify } from "node:util"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; const execute = promisify(execFile); @@ -18,50 +19,46 @@ it.each([ ])( "enforces native switching requirements for $protocol with $flags", async ({ protocol, flags, required }) => { - const root = await mkdtemp(join(tmpdir(), "rea-ida-verifier-options-")); - try { - const config = join(root, "ida.json"); - await writeFile( - config, - JSON.stringify({ - url: "http://127.0.0.1:13337/mcp", - mode: protocol === "modern" ? "headless" : "attached", - ...(protocol === "modern" ? {} : { protocol }), - }), - ); - // The absent target stops accepted option sets at admission, before any provider call. - await expect( - execute( - process.execPath, - [ - "scripts/verify-real-ida.mjs", - "--target", - join(root, "absent"), - ...flags, - ], - { - cwd: process.cwd(), - env: { ...process.env, REA_IDA_MCP_CONFIG: config }, - timeout: 10_000, + const root = await createTestTempDirectory("rea-ida-verifier-options-"); + const config = join(root, "ida.json"); + await writeFile( + config, + JSON.stringify({ + url: "http://127.0.0.1:13337/mcp", + mode: protocol === "modern" ? "headless" : "attached", + ...(protocol === "modern" ? {} : { protocol }), + }), + ); + // The absent target stops accepted option sets at admission, before any provider call. + await expect( + execute( + process.execPath, + [ + "scripts/verify-real-ida.mjs", + "--target", + join(root, "absent"), + ...flags, + ], + { + cwd: process.cwd(), + env: { ...process.env, REA_IDA_MCP_CONFIG: config }, + timeout: 10_000, + }, + ), + ).rejects.toMatchObject( + required + ? { + stdout: "", + stderr: expect.stringContaining( + "Native IDA verification requires --second-procedure and --second-marker", + ), + } + : { + stderr: "", + stdout: expect.stringContaining( + '"failed_phase": "target admission"', + ), }, - ), - ).rejects.toMatchObject( - required - ? { - stdout: "", - stderr: expect.stringContaining( - "Native IDA verification requires --second-procedure and --second-marker", - ), - } - : { - stderr: "", - stdout: expect.stringContaining( - '"failed_phase": "target admission"', - ), - }, - ); - } finally { - await rm(root, { recursive: true, force: true }); - } + ); }, ); diff --git a/tests/boundary/providers/native/lldbCallTracerFailures.test.ts b/tests/boundary/providers/native/lldbCallTracerFailures.test.ts index b220c2fa5e..b79ea8f13f 100644 --- a/tests/boundary/providers/native/lldbCallTracerFailures.test.ts +++ b/tests/boundary/providers/native/lldbCallTracerFailures.test.ts @@ -1,6 +1,5 @@ import { access, - mkdtemp, readFile, rm, writeFile, @@ -10,9 +9,9 @@ import { } from "node:fs/promises"; import { ChildProcess } from "node:child_process"; import { dirname, join } from "node:path"; -import { tmpdir } from "node:os"; import { describe, expect, it, onTestFinished, vi } from "vitest"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; import { z } from "zod"; import { @@ -823,8 +822,8 @@ describe("LLDB primary outcome during owned process cleanup", () => { .each(["caller cancellation", "deadline timeout"] as const)( "preserves a physical bridge failure and no-target proof when %s arrives during successful process cleanup", async (interruption) => { - const fixtureRoot = await mkdtemp( - join(tmpdir(), "rea-lldb-primary-outcome-"), + const fixtureRoot = await createTestTempDirectory( + "rea-lldb-primary-outcome-", ); const fakeLldb = join(fixtureRoot, "fake-lldb"); await writeFile( @@ -901,7 +900,6 @@ describe("LLDB primary outcome during owned process cleanup", () => { stopSpy.mockRestore(); deadlineSpy?.mockRestore(); await tracer.close(); - await rm(fixtureRoot, { recursive: true, force: true }); } }, ); @@ -911,8 +909,8 @@ describe("LLDB process exit while output is still open", () => { it.skipIf(process.platform === "win32")( "keeps a nonzero leader exit observed before cancellation while inherited output is still open", async () => { - const fixtureRoot = await mkdtemp( - join(tmpdir(), "rea-lldb-exit-before-cancel-"), + const fixtureRoot = await createTestTempDirectory( + "rea-lldb-exit-before-cancel-", ); const fakeLldb = join(fixtureRoot, "fake-lldb"); await writeFile( @@ -981,7 +979,6 @@ describe("LLDB process exit while output is still open", () => { drainSpy.mockRestore(); stopSpy.mockRestore(); await tracer.close(); - await rm(fixtureRoot, { recursive: true, force: true }); } }, ); @@ -992,7 +989,7 @@ describe("LLDB process exit while output is still open", () => { * does after rea_trace, while an inherited child keeps its output open. */ const publishedResultLldb = async (result: string) => { - const fixtureRoot = await mkdtemp(join(tmpdir(), "rea-lldb-published-")); + const fixtureRoot = await createTestTempDirectory("rea-lldb-published-"); const fakeLldb = join(fixtureRoot, "fake-lldb"); await writeFile( fakeLldb, @@ -1131,7 +1128,6 @@ describe("LLDB target proof published before interruption", () => { deadlineSpy?.mockRestore(); if (retainedRoot !== undefined) await rm(retainedRoot, { recursive: true, force: true }); - await rm(fixtureRoot, { recursive: true, force: true }); } }, ); @@ -1205,15 +1201,14 @@ describe("LLDB target proof read by cleanup retry", () => { stopSpy.mockRestore(); if (retainedRoot !== undefined) await rm(retainedRoot, { recursive: true, force: true }); - await rm(fixtureRoot, { recursive: true, force: true }); } }, ); }); const completedOutputCloseFixture = async () => { - const fixtureRoot = await mkdtemp( - join(tmpdir(), "rea-lldb-complete-output-"), + const fixtureRoot = await createTestTempDirectory( + "rea-lldb-complete-output-", ); const fakeLldb = join(fixtureRoot, "fake-lldb"); const completedPidPath = join(fixtureRoot, "completed-target.pid"); @@ -1332,7 +1327,6 @@ describe("LLDB process exit at output-close loop completion", () => { } finally { waitSpy.mockRestore(); expect((await tracer.close()).ok).toBe(true); - await rm(fixture.fixtureRoot, { recursive: true, force: true }); } }, ); @@ -1340,8 +1334,8 @@ describe("LLDB process exit at output-close loop completion", () => { it.skipIf(process.platform === "win32")( "keeps a nonzero exit when output closure and cancellation meet at loop exit", async () => { - const fixtureRoot = await mkdtemp( - join(tmpdir(), "rea-lldb-closed-output-cancel-"), + const fixtureRoot = await createTestTempDirectory( + "rea-lldb-closed-output-cancel-", ); const fakeLldb = join(fixtureRoot, "fake-lldb"); await writeFile( @@ -1407,7 +1401,6 @@ describe("LLDB process exit at output-close loop completion", () => { waitSpy.mockRestore(); stopSpy.mockRestore(); await tracer.close(); - await rm(fixtureRoot, { recursive: true, force: true }); } }, ); @@ -1471,8 +1464,8 @@ describe("LLDB work budget elapsing during process cleanup", () => { .each(["confirmed", "unconfirmed"] as const)( "keeps the completed trace when the budget elapses during %s process cleanup", async (cleanup) => { - const fixtureRoot = await mkdtemp( - join(tmpdir(), "rea-lldb-cleanup-deadline-"), + const fixtureRoot = await createTestTempDirectory( + "rea-lldb-cleanup-deadline-", ); const fakeLldb = join(fixtureRoot, "fake-lldb"); const observation = `${JSON.stringify({ kind: "event", event: EVENT })}\n`; @@ -1541,7 +1534,6 @@ describe("LLDB work budget elapsing during process cleanup", () => { stopSpy.mockRestore(); deadlineSpy.mockRestore(); await tracer.close(); - await rm(fixtureRoot, { recursive: true, force: true }); } }, ); diff --git a/tests/boundary/providers/native/lldbReadbackFiles.test.ts b/tests/boundary/providers/native/lldbReadbackFiles.test.ts index f37dbfc390..2074889743 100644 --- a/tests/boundary/providers/native/lldbReadbackFiles.test.ts +++ b/tests/boundary/providers/native/lldbReadbackFiles.test.ts @@ -1,18 +1,13 @@ -import { - mkdtemp, - open, - rm, - writeFile, - type FileHandle, -} from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { open, writeFile, type FileHandle } from "node:fs/promises"; + import { join } from "node:path"; import { expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; import { LldbReadbackFiles } from "../../../../src/native/LldbReadbackFiles.js"; it("bounds PID readback while retaining newline-terminated producer fixtures", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-lldb-pid-")); + const directory = await createTestTempDirectory("rea-lldb-pid-"); const values = [ ["max-safe.pid", String(Number.MAX_SAFE_INTEGER), Number.MAX_SAFE_INTEGER], [ @@ -84,6 +79,5 @@ it("bounds PID readback while retaining newline-terminated producer fixtures", a readSpy.mockRestore(); readFileSpy.mockRestore(); await files.retryCleanup(); - await rm(directory, { recursive: true, force: true }); } }); diff --git a/tests/boundary/providers/native/objcClassMetadataFallback.test.ts b/tests/boundary/providers/native/objcClassMetadataFallback.test.ts index 1729095318..ff14521d96 100644 --- a/tests/boundary/providers/native/objcClassMetadataFallback.test.ts +++ b/tests/boundary/providers/native/objcClassMetadataFallback.test.ts @@ -1,8 +1,9 @@ import { createHash } from "node:crypto"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; + import { join } from "node:path"; import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; import type { AnalysisOperation, @@ -40,7 +41,7 @@ const inspect = async ( bytes: Buffer, architecture: "x86" | "arm" | "x86_64", ) => { - const directory = await mkdtemp(join(tmpdir(), "rea-objc-macho-fallback-")); + const directory = await createTestTempDirectory("rea-objc-macho-fallback-"); const path = join(directory, "fixture"); await writeFile(path, bytes); const sha256 = createHash("sha256").update(bytes).digest("hex"); @@ -84,7 +85,6 @@ const inspect = async ( } catch (cause: unknown) { closeError = cause; } - await rm(directory, { recursive: true, force: true }); if (closeError !== undefined) throw closeError; expect(closeResult).toMatchObject({ ok: true }); }