mirror of
https://github.com/software-mansion/argent.git
synced 2026-09-14 19:27:14 +08:00
82db9e2f9f
Three issues, one theme: tests and the shared system temp directory. - **#858 / #854** were live leaks — three call sites captured a real temp path and never removed it. One reaches the cleanup its file already had; the other two get a cleanup the file lacked. - **#836** turned out to be **already fixed on `main`** by #714, which scoped those three tests' `TMPDIR` to a directory they own. This PR verifies that rather than changing it — reproduction and mutation evidence below. - Sweeping the same shape across the two packages turned up **six more test files** doing it, worth **44** leftover entries per run. - A third shape, in **two** more files: `resolveFileInputs` hands its caller a `cleanup` for whatever it materialized — the dispatcher's job in production. Five call sites kept the result and never called it, stranding 5 dirs per run. A scoped-`TMPDIR` run of all 12 affected files leaves **one** entry behind: an empty `argent-chromium-media/`, production's own fixed staging dir. 173 tests, no other file or directory. Fixes #858 Fixes #854 Closes #836 <details> <summary>#858 — before/after temp scope</summary> ``` rm -rf /tmp/scope && mkdir -p /tmp/scope TMPDIR=/tmp/scope TMP=/tmp/scope TEMP=/tmp/scope \ npx vitest run --root packages/tool-server test/chromium-server-screenshot.test.ts ``` | site | before | after | |---|---|---| | `chromium-server-screenshot.test.ts` | `argent-chromium-media/argent-screenshot-test-1788803062089-38318.png` | *(no PNG)* | | `chromium-cdp-blueprint.test.ts` | `argent-chromium-media/argent-screenshot-chromium-cdp-52204-1788803091335-39401.png` | *(no PNG)* | Both files keep an empty `argent-chromium-media/` — that is production's fixed staging dir (`src/chromium-server/cdp-session.ts:218`), shared with any live chromium-server on the machine and not per-run garbage. A test `rm`ing it would be the machine-global-resource defect #714 removed elsewhere, so it is left alone deliberately. </details> <details> <summary>#854 — before/after temp scope</summary> ``` TMPDIR=/tmp/scope … npx vitest run --root packages/argent-mcp test/content.test.ts ``` Before (`34 passed`, two directories left): ``` argent-mcp-content-kPfgYa/context.diff.png argent-artifacts/test-temp-dir-hygiene-037c31/20260907-174453-39458/home-diff.png ``` After: **empty**. The `mkdtemp` moved onto a `beforeEach`/`afterEach` pair mirroring the sibling describe, and `flowRunToMcpContent` now pins `ARGENT_ARTIFACTS_DIR` the way the artifact describe above it already did. The unconditional `delete process.env.ARGENT_ARTIFACTS_DIR` is kept, not converted to a save/restore: it is what keeps any future unpinned write landing in `tmpdir` rather than a developer's configured artifacts directory. The pin is not hygiene-only — it is asserted. Removing `process.env.ARGENT_ARTIFACTS_DIR = root` fails the test: ``` - diff: /tmp/scopeM4/content-flow-artifacts-LZKPAl + diff: /tmp/scopeM4/argent-artifacts/test-temp-dir-hygiene-037c31/20260908-100837-89701/home-diff.png ❯ test/content.test.ts:627 expect(artifactText?.text).toContain(`diff: ${root}`) ``` </details> <details> <summary>#836 — why no code changed, and the evidence</summary> (This PR does change `file-inputs.test.ts`, but for the unrelated third shape above — not for the sites #836 cites.) The issue cites `readdir(os.tmpdir())` at `file-inputs.test.ts:180-197` and `flow-visual.test.ts:586-602`. On current `main` neither exists: #714 replaced both (and the `http-upload.test.ts:154-158` sibling the issue also flags) with a per-test scratch directory the test creates, points `os.tmpdir()` at via `redirectTmpdir`, and removes. There is now **no** `readdir` of `os.tmpdir()` anywhere in either package. The per-path assertion the issue asks for is not reachable at these three sites — every name is a `mkdtemp` random suffix or a server-side `randomUUID`, so the test cannot know the path. Scoping the tmpdir to a directory the test owns is the same guarantee, and is what landed. **Reproduced the reported failure** by reverting each site to the global-listing shape, then running two simultaneous instances in a loop: | file | pre-#714 shape | current | |---|---|---| | `file-inputs.test.ts` | **1 / 12** — `expected [ 'argent-file-input-00mPU7', …(1371) ] to deeply equal [ …(1370) ]` | **0 / 12** | | `flows/flow-visual.test.ts` | **12 / 12** — `expected [ 'argent-flow-crop-00R9XZ', …(4853) ] to deeply equal []` | **0 / 12** | | `http-upload.test.ts` | — | **0 / 12** | **Mutation-tested all three assertions** — each still catches a real leak; production cleanup broken, test run, source restored: | assertion | mutation | result | |---|---|---| | `file-inputs.test.ts:249` | drop `await cleanup()` from `resolveFileInputs`' catch path | ✗ `+ [ "argent-file-input-amPJuK" ]` | | `flow-visual.test.ts:610` | drop `cleanupDiffDir(cropDir, …)` from the outer `finally` | ✗ `+ [ "argent-flow-crop-rWT9Bd" ]` | | `http-upload.test.ts:187` | drop `rm(tarPath)` from the `req.on("close")` handler | ✗ `+ [ "argent-upload-43d82021-….tar.gz" ]` | </details> <details> <summary>Sibling sweep — the same two shapes across both packages</summary> **Shape "assertion diffing a listing of `os.tmpdir()`": zero remaining.** No `readdir`/`readdirSync`/`glob` over `os.tmpdir()`, `tmpdir()` or a literal `/tmp` in either test tree. Every literal `/tmp` string left is a fixture handed to a mocked API; the three that do touch disk were checked by hand and are clean (`native-devtools-socket-bind.test.ts` mkdtemps and removes, `flow-utils.test.ts` is pure path math, `native-profiler-external-device.test.ts` writes only inside its own per-test `mkdtemp`). **Shape "a captured temp path never cleaned up": six files fixed.** Each gets one recording choke point plus an `afterEach`. Running those six under a scoped `TMPDIR` (`48 passed` both times): ``` before: 44 entries after: 1 entry ``` | file | sites | |---|---| | `screenshot-diff-tool.test.ts` | 9 | | `react-profiler/ast-index.test.ts` | 6 | | `event-log.test.ts` | 1 helper (4 dirs/run) | | `screenshot-diff.test.ts` | 1 helper | | `react-profiler/component-source-duplicates.test.ts` | 2 | | `ios-instruments/combined-report-frozen-anchor.test.ts` | 1 | | `flows/flow-visual.test.ts` | production's crop + diff dirs (5/run) | **Left deliberately (1 entry):** an **empty** `argent-chromium-media/` — production's fixed staging dir (`src/chromium-server/cdp-session.ts:218`), shared with any live chromium-server on the machine. A test `rm`ing it would be the machine-global-resource defect #714 removed elsewhere. Two further shapes turned up while checking that claim, both *production* dirs a test drove and then abandoned: | site | per run | why the test could not just `rm` it | |---|---|---| | `screenshot-diff-tool.test.ts` | 2 dirs + 2 PNGs | `resolveOutputDir` mints `argent-screenshot-diff/<hex>` before anything validates the call, so the path exists before the test can learn it — and on a throw it never learns it at all | | `flows/flow-visual.test.ts` | 5 dirs + 5 PNGs | `runSnapshot` leaves the file it registered as an artifact inside its `argent-flow-crop-*` / `argent-flow-diff-*` scratch dir; from there the dir belongs to whoever consumes the artifact, which here is the test | Both are fixed the same way, with `redirectTmpdir` (already used by seven other test files): point `os.tmpdir()` at a directory the test already owns and removes, so whatever production mints lands inside it whether the call returns or throws. The `<hex>` and `mkdtemp` suffixes are per-call and never shared, so nothing a concurrent tool-server owns is touched — verified with a decoy file planted under the shared root, which survives the run. Measured under a scoped `TMPDIR`, three consecutive runs each: `screenshot-diff-tool` 6 dirs + 6 PNGs → **0 + 0**; `flow-visual` 15 + 15 → **0 + 0**. The underlying production leak behind the first is still #790. `argent-mcp` is now clean end to end: every `mkdtemp` in the package has a matching `rm`. </details> <details> <summary>Checks</summary> Run from the worktree root, exit codes read unpiped: - `npm run format` → 0, no files rewritten - `npx tsc --noEmit -p packages/tool-server/tsconfig.test.json` → 0 - `npx tsc --noEmit -p packages/argent-mcp/tsconfig.test.json` → 0 - `npm run lint` → 0 - `npm run knip` → 0 - no `it.only` / `describe.only` in the diff Suites: `argent-mcp` **90 passed**; `tool-server` run as six shards under a scoped `TMPDIR`. `lens-tools-platform-gate.test.ts` times out at the 5 s default under full-suite load and passes in isolation (`2 passed`, 3.14 s). It is not in this diff and #714 recorded the same behaviour before it. </details> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Tests** - Improved test isolation by consistently cleaning up temporary files and directories after each test. - Added coverage verifying generated artifacts are stored under the configured artifacts directory. - Ensured screenshot, upload, event-log, profiling, visual-flow, and diff-test artifacts are removed reliably after execution. - Standardized temporary-directory handling and cleanup across test scenarios to reduce leftover test data and improve repeatability. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
472 lines
17 KiB
TypeScript
472 lines
17 KiB
TypeScript
import fs from "fs/promises";
|
|
import os from "os";
|
|
import path from "path";
|
|
import { PNG } from "pngjs";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import { ArtifactStore } from "@argent/registry";
|
|
import { executeScreenshotDiffTool, screenshotDiffTool } from "../src/tools/screenshot-diff";
|
|
import { RUNNER_COMMAND_TIMEOUT_MS } from "../src/utils/ios-device/runner-client";
|
|
import { redirectTmpdir } from "./helpers/tmpdir-env";
|
|
|
|
const tempDirs: string[] = [];
|
|
|
|
afterEach(async () => {
|
|
for (const dir of tempDirs.splice(0)) await fs.rm(dir, { recursive: true, force: true });
|
|
});
|
|
|
|
async function makeTempDir(prefix: string): Promise<string> {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
|
|
tempDirs.push(dir);
|
|
return dir;
|
|
}
|
|
|
|
describe("screenshotDiffTool", () => {
|
|
it("rejects public tuning options so defaults stay internal", () => {
|
|
const result = screenshotDiffTool.zodSchema!.safeParse({
|
|
baselinePath: "/tmp/baseline.png",
|
|
currentPath: "/tmp/current.png",
|
|
udid: "ABC",
|
|
outputDir: "/tmp",
|
|
includeTextAnalysis: false,
|
|
threshold: 0.2,
|
|
textChangeMinConfidence: 0.9,
|
|
maxRegions: 3,
|
|
});
|
|
|
|
expect(result.success).toBe(false);
|
|
});
|
|
|
|
it("requires udid and only declares the simulator-server service for live captures", () => {
|
|
expect(
|
|
screenshotDiffTool.zodSchema!.safeParse({
|
|
baselinePath: "/tmp/baseline.png",
|
|
currentPath: "/tmp/current.png",
|
|
outputDir: "/tmp",
|
|
}).success
|
|
).toBe(false);
|
|
|
|
// A pure static-PNG diff needs no SimulatorServer — requesting it
|
|
// unconditionally would fail on tvOS sims that have no such backend.
|
|
const staticParams = {
|
|
baselinePath: "/tmp/baseline.png",
|
|
currentPath: "/tmp/current.png",
|
|
udid: "ABC",
|
|
outputDir: "/tmp",
|
|
};
|
|
expect(screenshotDiffTool.zodSchema!.safeParse(staticParams).success).toBe(true);
|
|
expect(screenshotDiffTool.services(staticParams)).toEqual({});
|
|
|
|
// A live capture resolves and starts the SimulatorServer for the device.
|
|
const liveParams = {
|
|
baselinePath: "/tmp/baseline.png",
|
|
captureCurrent: true,
|
|
udid: "ABC",
|
|
outputDir: "/tmp",
|
|
};
|
|
expect(screenshotDiffTool.zodSchema!.safeParse(liveParams).success).toBe(true);
|
|
expect(screenshotDiffTool.services(liveParams)).toEqual({
|
|
simulatorServer: {
|
|
urn: "SimulatorServer:ABC",
|
|
options: {
|
|
device: {
|
|
id: "ABC",
|
|
platform: "android",
|
|
// A non-`emulator-*` serial resolves to a physical device.
|
|
kind: "device",
|
|
},
|
|
},
|
|
},
|
|
});
|
|
});
|
|
|
|
it("returns only the summary and diff artifact paths", async () => {
|
|
const dir = await makeTempDir("argent-screenshot-diff-tool-");
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
|
|
await writePng(currentPath, 2, 2, { r: 10, g: 20, b: 30 });
|
|
|
|
const result = await executeScreenshotDiffTool(
|
|
{},
|
|
{
|
|
baselinePath,
|
|
currentPath,
|
|
udid: "ABC",
|
|
outputDir: dir,
|
|
},
|
|
{ artifacts: new ArtifactStore() }
|
|
);
|
|
|
|
// Diff outputs leave as artifact handles so a remote client can download
|
|
// them; hostPath still points at the requested outputDir.
|
|
expect(result.summary).toContain("Screenshot diff summary");
|
|
expect(result.diffPath).toMatchObject({
|
|
__argentArtifact: true,
|
|
kind: "screenshot-diff",
|
|
hostPath: path.join(dir, "current-diff.png"),
|
|
mimeType: "image/png",
|
|
});
|
|
expect(result.contextDiffPath).toMatchObject({
|
|
__argentArtifact: true,
|
|
kind: "screenshot-diff-context",
|
|
hostPath: path.join(dir, "current-context-diff.png"),
|
|
mimeType: "image/png",
|
|
});
|
|
expect(Object.keys(result).sort()).toEqual(["contextDiffPath", "diffPath", "summary"]);
|
|
});
|
|
|
|
it("captures one live side at full resolution and copies it into outputDir", async () => {
|
|
const dir = await makeTempDir("argent-screenshot-diff-live-");
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const capturedPath = path.join(dir, "captured.png");
|
|
await writePng(baselinePath, 2, 2, { r: 0, g: 0, b: 0 });
|
|
await writePng(capturedPath, 2, 2, { r: 0, g: 0, b: 0 });
|
|
const signal = AbortSignal.timeout(1000);
|
|
const captureScreenshot = vi.fn(async () => ({
|
|
url: "http://localhost/current.png",
|
|
path: capturedPath,
|
|
}));
|
|
|
|
const result = await executeScreenshotDiffTool(
|
|
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
|
|
{
|
|
baselinePath,
|
|
captureCurrent: true,
|
|
udid: "ABC",
|
|
rotation: "LandscapeLeft",
|
|
outputDir: dir,
|
|
},
|
|
{ signal, artifacts: new ArtifactStore() },
|
|
captureScreenshot as never
|
|
);
|
|
|
|
expect(captureScreenshot).toHaveBeenCalledWith(
|
|
{ apiUrl: "http://localhost:4949" },
|
|
"LandscapeLeft",
|
|
signal,
|
|
1.0
|
|
);
|
|
|
|
const entries = await fs.readdir(dir);
|
|
const liveCaptures = entries.filter((name) => /^current-[a-f0-9]{8}\.live\.png$/.test(name));
|
|
expect(liveCaptures).toHaveLength(1);
|
|
const liveBaseName = path.parse(liveCaptures[0]!).name;
|
|
await expect(fs.stat(path.join(dir, liveCaptures[0]!))).resolves.toMatchObject({
|
|
size: expect.any(Number),
|
|
});
|
|
expect(result.diffPath).toMatchObject({
|
|
hostPath: path.join(dir, `${liveBaseName}-diff.png`),
|
|
});
|
|
});
|
|
|
|
it("falls back to the default scale when the full-resolution capture fails (Android framebuffer mismatch)", async () => {
|
|
const dir = await makeTempDir("argent-screenshot-diff-fallback-");
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const capturedPath = path.join(dir, "captured.png");
|
|
await writePng(baselinePath, 2, 2, { r: 0, g: 0, b: 0 });
|
|
await writePng(capturedPath, 2, 2, { r: 0, g: 0, b: 0 });
|
|
// Full-res (scale 1.0) fails the way the Android simulator-server does;
|
|
// the default-scale retry (no scale arg) succeeds.
|
|
const captureScreenshot = vi.fn(
|
|
async (_api: unknown, _rotation: unknown, _signal: unknown, scale?: number) => {
|
|
if (scale === 1.0) {
|
|
throw new Error("Screenshot failed: wrong data size, expected 7853760 got 17627328.");
|
|
}
|
|
return { url: "http://localhost/current.png", path: capturedPath };
|
|
}
|
|
);
|
|
|
|
const result = await executeScreenshotDiffTool(
|
|
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
|
|
{ baselinePath, captureCurrent: true, udid: "ABC", outputDir: dir },
|
|
{ artifacts: new ArtifactStore() },
|
|
captureScreenshot as never
|
|
);
|
|
|
|
// Full-res attempted first, then a default-scale retry without an explicit scale.
|
|
expect(captureScreenshot).toHaveBeenCalledTimes(2);
|
|
expect(captureScreenshot.mock.calls[0]![3]).toBe(1.0);
|
|
expect(captureScreenshot.mock.calls[1]![3]).toBeUndefined();
|
|
const liveCaptures = (await fs.readdir(dir)).filter((name) =>
|
|
/^current-[a-f0-9]{8}\.live\.png$/.test(name)
|
|
);
|
|
expect(liveCaptures).toHaveLength(1);
|
|
expect(result.diffPath).toBeTruthy();
|
|
});
|
|
|
|
it("propagates the error when both the full-res capture and the fallback fail", async () => {
|
|
const dir = await makeTempDir("argent-screenshot-diff-bothfail-");
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
await writePng(baselinePath, 2, 2, { r: 0, g: 0, b: 0 });
|
|
const captureScreenshot = vi.fn(
|
|
async (_api: unknown, _rotation: unknown, _signal: unknown, scale?: number) => {
|
|
throw new Error(scale === 1.0 ? "full-res failed" : "device offline");
|
|
}
|
|
);
|
|
|
|
await expect(
|
|
executeScreenshotDiffTool(
|
|
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
|
|
{ baselinePath, captureCurrent: true, udid: "ABC", outputDir: dir },
|
|
{},
|
|
captureScreenshot as never
|
|
)
|
|
).rejects.toThrow("device offline");
|
|
expect(captureScreenshot).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("uses a fresh hashed filename for each live capture so concurrent diffs do not collide", async () => {
|
|
const dir = await makeTempDir("argent-screenshot-diff-unique-");
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const capturedPath = path.join(dir, "captured.png");
|
|
await writePng(baselinePath, 2, 2, { r: 0, g: 0, b: 0 });
|
|
await writePng(capturedPath, 2, 2, { r: 0, g: 0, b: 0 });
|
|
const captureScreenshot = vi.fn(async () => ({
|
|
url: "http://localhost/current.png",
|
|
path: capturedPath,
|
|
}));
|
|
|
|
await executeScreenshotDiffTool(
|
|
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
|
|
{ baselinePath, captureCurrent: true, udid: "ABC", outputDir: dir },
|
|
{ artifacts: new ArtifactStore() },
|
|
captureScreenshot as never
|
|
);
|
|
await executeScreenshotDiffTool(
|
|
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
|
|
{ baselinePath, captureCurrent: true, udid: "ABC", outputDir: dir },
|
|
{ artifacts: new ArtifactStore() },
|
|
captureScreenshot as never
|
|
);
|
|
|
|
const liveCaptures = (await fs.readdir(dir)).filter((name) =>
|
|
/^current-[a-f0-9]{8}\.live\.png$/.test(name)
|
|
);
|
|
expect(liveCaptures).toHaveLength(2);
|
|
expect(new Set(liveCaptures).size).toBe(2);
|
|
});
|
|
|
|
it("validates mutually exclusive saved and live inputs at execute time", async () => {
|
|
await expect(
|
|
executeScreenshotDiffTool(
|
|
{},
|
|
{
|
|
baselinePath: "/tmp/baseline.png",
|
|
currentPath: "/tmp/current.png",
|
|
captureCurrent: true,
|
|
udid: "ABC",
|
|
outputDir: "/tmp",
|
|
}
|
|
)
|
|
).rejects.toThrow("Provide either currentPath or captureCurrent, not both.");
|
|
});
|
|
|
|
// The boundary probe reports `presentOnHost: false` for ANY path that does not
|
|
// already exist here, so a local agent naming a fresh output directory looked
|
|
// exactly like a remote client's own directory and was silently redirected to
|
|
// a temp dir. A directory we can create next to an existing parent is ours.
|
|
it("creates and honors an outputDir that does not exist yet on this host", async () => {
|
|
const parent = await makeTempDir("argent-screenshot-diff-fresh-");
|
|
const baselinePath = path.join(parent, "baseline.png");
|
|
const currentPath = path.join(parent, "current.png");
|
|
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
|
|
await writePng(currentPath, 2, 2, { r: 200, g: 20, b: 30 });
|
|
|
|
const outputDir = path.join(parent, "diff-out");
|
|
|
|
const result = await executeScreenshotDiffTool(
|
|
{},
|
|
{ baselinePath, currentPath, udid: "ABC", outputDir },
|
|
{
|
|
artifacts: new ArtifactStore(),
|
|
fileInputs: {
|
|
outputDir: { clientPath: outputDir, presentOnHost: false, viaUpload: false },
|
|
},
|
|
}
|
|
);
|
|
|
|
expect(result.diffPath).toMatchObject({
|
|
hostPath: path.join(outputDir, "current-diff.png"),
|
|
});
|
|
await expect(fs.stat(path.join(outputDir, "current-diff.png"))).resolves.toBeTruthy();
|
|
});
|
|
|
|
// The probe runs before the create, so a directory that appears in between —
|
|
// a concurrent diff on the same outputDir, or the agent creating it itself —
|
|
// reaches mkdir as EEXIST. That is the directory the caller asked for, not a
|
|
// reason to redirect them to a temp dir.
|
|
it("honors an outputDir that raced into existence after the probe", async () => {
|
|
const parent = await makeTempDir("argent-screenshot-diff-race-");
|
|
const baselinePath = path.join(parent, "baseline.png");
|
|
const currentPath = path.join(parent, "current.png");
|
|
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
|
|
await writePng(currentPath, 2, 2, { r: 200, g: 20, b: 30 });
|
|
|
|
// Exists on disk, but the probe captured the earlier state.
|
|
const outputDir = path.join(parent, "diff-out");
|
|
await fs.mkdir(outputDir);
|
|
|
|
const result = await executeScreenshotDiffTool(
|
|
{},
|
|
{ baselinePath, currentPath, udid: "ABC", outputDir },
|
|
{
|
|
artifacts: new ArtifactStore(),
|
|
fileInputs: {
|
|
outputDir: { clientPath: outputDir, presentOnHost: false, viaUpload: false },
|
|
},
|
|
}
|
|
);
|
|
|
|
expect(result.diffPath).toMatchObject({
|
|
hostPath: path.join(outputDir, "current-diff.png"),
|
|
});
|
|
await expect(fs.stat(path.join(outputDir, "current-diff.png"))).resolves.toBeTruthy();
|
|
});
|
|
|
|
const PHYSICAL_UDID = "00008110-000978540290401E";
|
|
|
|
it("declares the runner service only for live captures on a physical iPhone", () => {
|
|
// A pure file-vs-file diff must not spin up the runner.
|
|
expect(
|
|
screenshotDiffTool.services({
|
|
baselinePath: "/tmp/baseline.png",
|
|
currentPath: "/tmp/current.png",
|
|
udid: PHYSICAL_UDID,
|
|
})
|
|
).toEqual({});
|
|
|
|
expect(
|
|
screenshotDiffTool.services({
|
|
baselinePath: "/tmp/baseline.png",
|
|
captureCurrent: true,
|
|
udid: PHYSICAL_UDID,
|
|
})
|
|
).toEqual({
|
|
iosDeviceRunner: {
|
|
urn: `IosDeviceRunner:${PHYSICAL_UDID}`,
|
|
options: { device: { id: PHYSICAL_UDID, platform: "ios", kind: "device" } },
|
|
},
|
|
});
|
|
});
|
|
|
|
it("captures the live side through the runner on a physical iPhone and ignores rotation", async () => {
|
|
const dir = await makeTempDir("argent-screenshot-diff-device-");
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
|
|
const run = vi.fn(async () => ({
|
|
imageBase64: pngBytes(2, 2, { r: 10, g: 20, b: 30 }).toString("base64"),
|
|
}));
|
|
|
|
const result = await executeScreenshotDiffTool(
|
|
{ iosDeviceRunner: { run, udid: PHYSICAL_UDID } },
|
|
{
|
|
baselinePath,
|
|
captureCurrent: true,
|
|
udid: PHYSICAL_UDID,
|
|
rotation: "LandscapeLeft",
|
|
outputDir: dir,
|
|
},
|
|
{ artifacts: new ArtifactStore() }
|
|
);
|
|
|
|
// The rotation parameter is not forwarded. Hardware captures always follow
|
|
// the device's real orientation, the same behaviour as the screenshot tool.
|
|
expect(run).toHaveBeenCalledTimes(1);
|
|
expect(run).toHaveBeenCalledWith(
|
|
{ command: "screenshot" },
|
|
{ readOnly: true, timeoutMs: RUNNER_COMMAND_TIMEOUT_MS }
|
|
);
|
|
const liveCaptures = (await fs.readdir(dir)).filter((name) =>
|
|
/^current-[a-f0-9]{8}\.live\.png$/.test(name)
|
|
);
|
|
expect(liveCaptures).toHaveLength(1);
|
|
expect(result.summary).toContain("Screenshot diff summary");
|
|
});
|
|
|
|
it("demands the runner service when a direct caller requests a device live capture", async () => {
|
|
// outputDir is resolved before the service check, so omitting it would mint
|
|
// a fallback dir under argent-screenshot-diff that the throw then strands.
|
|
const outputDir = await makeTempDir("argent-screenshot-diff-norunner-");
|
|
await expect(
|
|
executeScreenshotDiffTool(
|
|
{},
|
|
{
|
|
baselinePath: "/tmp/baseline.png",
|
|
captureCurrent: true,
|
|
udid: PHYSICAL_UDID,
|
|
outputDir,
|
|
}
|
|
)
|
|
).rejects.toThrow("requires an iosDeviceRunner service");
|
|
});
|
|
|
|
// The remote case must still fall back: a client-side path whose parent does
|
|
// not exist here cannot be created, so diffs go to a temp dir as before.
|
|
it("falls back to a temp dir when outputDir is not creatable on this host", async () => {
|
|
const dir = await makeTempDir("argent-screenshot-diff-remote-");
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
|
|
await writePng(currentPath, 2, 2, { r: 200, g: 20, b: 30 });
|
|
|
|
// Parent does not exist on this host — a remote client's own directory.
|
|
const outputDir = path.join(dir, "no-such-parent", "nested", "diff-out");
|
|
|
|
// resolveOutputDir mints the fallback under os.tmpdir() before anything
|
|
// validates the call, so a throw downstream would strand it with the path
|
|
// known only to the code that threw. Point os.tmpdir() at the dir already
|
|
// registered for removal and the sweep takes it either way — never the
|
|
// shared argent-screenshot-diff root, which belongs to any tool-server
|
|
// running alongside.
|
|
const restoreTmpdir = redirectTmpdir(dir);
|
|
let result;
|
|
try {
|
|
result = await executeScreenshotDiffTool(
|
|
{},
|
|
{ baselinePath, currentPath, udid: "ABC", outputDir },
|
|
{
|
|
artifacts: new ArtifactStore(),
|
|
fileInputs: {
|
|
outputDir: { clientPath: outputDir, presentOnHost: false, viaUpload: false },
|
|
},
|
|
}
|
|
);
|
|
} finally {
|
|
restoreTmpdir();
|
|
}
|
|
|
|
const diffHostPath = (result.diffPath as { hostPath: string }).hostPath;
|
|
expect(diffHostPath.startsWith(outputDir)).toBe(false);
|
|
expect(diffHostPath).toContain("argent-screenshot-diff");
|
|
});
|
|
});
|
|
|
|
function pngBytes(
|
|
width: number,
|
|
height: number,
|
|
fill: { r: number; g: number; b: number }
|
|
): Buffer {
|
|
const png = new PNG({ width, height });
|
|
|
|
for (let y = 0; y < height; y++) {
|
|
for (let x = 0; x < width; x++) {
|
|
const offset = (width * y + x) * 4;
|
|
png.data[offset] = fill.r;
|
|
png.data[offset + 1] = fill.g;
|
|
png.data[offset + 2] = fill.b;
|
|
png.data[offset + 3] = 255;
|
|
}
|
|
}
|
|
|
|
return PNG.sync.write(png);
|
|
}
|
|
|
|
async function writePng(
|
|
filePath: string,
|
|
width: number,
|
|
height: number,
|
|
fill: { r: number; g: number; b: number }
|
|
): Promise<void> {
|
|
await fs.writeFile(filePath, pngBytes(width, height, fill));
|
|
}
|