diff --git a/README.md b/README.md index 3fc6e01..e10bd22 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ renderdiff [options] | `--accept ` | Record this run's differences as accepted, with a reason. See **Accepted differences and reruns**. | | `--rerun-failed` | Rerun only what the last run in `--out` didn't find clean or accepted, keeping the rest. | | `--cache-right` | Replay the right side's network traffic from the last `--cache-right` run in `--out`, when it's under an hour old and covers every shot; otherwise load it live and record it. Keeps `/.cache/` when the out dir is wiped. See **Accepted differences and reruns**. | +| `--no-recheck` | Don't reload a differing shot's right side to find content that varies per load. Off anyway under `--cache-right`. | | `--computed` | Also diff the computed style of every rendered element and its `::before`/`::after`, and say per route whether the markup is identical apart from asset hashes and origin. Pixels still decide the score and exit code. See [docs/output.md](docs/output.md#computed-styles---computed). | | `--dry-run` | Print the URL pairs and exit. No browser. | | `--open` | Open the report when the run finishes. | @@ -129,7 +130,7 @@ range rather than on a boundary, so a layout switch never flaps between runs. | Exit | Meaning | | --- | --- | | `0` | No route errored and no shot differs (with `--threshold`: none scored below it). Accepted differences don't count; nor do unstable pixels or a failed asset alone, which still get their own row. | -| `1` | A shot differs, or with `--threshold` scored below it. Wins over `3` when both happen. A difference that can't be accepted (unstable pixels beside it, a width change, a height change whose rows don't align) exits 1 even on the `--accept` run. | +| `1` | A shot differs, or with `--threshold` scored below it. Wins over `3` when both happen. A difference that can't be accepted (unstable pixels beside it, content that varies per load, a width change, a height change whose rows don't align) exits 1 even on the `--accept` run. | | `2` | Bad arguments or config, an origin that isn't responding, an unreadable storage state or `renderdiff.accepted.json`, an out dir holding files renderdiff didn't write, or a `--rerun-failed` that doesn't repeat the last run. | | `3` | A route errored, so it went unmeasured, or the run crashed (e.g. no Chromium). | @@ -240,7 +241,7 @@ banner, your verdict, crops embedded) to attach to a ticket or publish as proof: - **Pins what varies between loads**: clock, `Math.random`, timezone, locale, colour scheme, reduced motion, animated image frames, video frames and video.js overlays. - **Kills animation, transitions and caret blink**, and hides common consent banners and dev toolbars. - **Settles the page**: lazy images, fonts and network idle before the shot. -- **Shoots until stable**, and excludes pixels still moving as `unstable`. +- **Shoots until stable**, and excludes pixels still moving as `unstable`; rechecks differing shots for content that varies per load. - **Isolates state** per origin, **retries once** per shot, and **stitches tall pages** past 16,384px. Each run's report ends with a "What was neutralized" section listing what was in effect. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 2e348f6..4dd69d4 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -34,6 +34,10 @@ honestly. This is what renderdiff does to make sure of that. noise from that origin: they're painted magenta on both sides, reported per comparison as `unstable`, and excluded from the measurement — the score is over the remaining pixels. A route more than 25% unstable errors as `page did not settle`. +- **Rechecks a differing shot** — reloads the right side once in a fresh context. The + elements that differ between the two loads are `varies`: painted out on both sides like a + mask, excluded from the score, and listed with the mask that would cover them. Off with + `--no-recheck`, and under `--cache-right`, whose replay serves the same bytes each load. - **Counts a pixel as changed** when pixelmatch's YIQ colour distance is over threshold 0.05 (a delta of about 88), with anti-aliased pixels left out. Its default of 0.1 passed Tailwind v3 → v4 `pink-500` as identical; a recolour still smaller than that passes. The diff --git a/docs/output.md b/docs/output.md index 97b51b7..ae8abdb 100644 --- a/docs/output.md +++ b/docs/output.md @@ -30,8 +30,9 @@ as the largest. Under a row, `failed` lists stylesheets and font faces a side fa (`@w` when the row covers several widths: the first one's), and `crops` lists that row's crop files. Errors print in full, grouped across the widths that share a message. Clean means not one pixel differs, none went unmeasured as unstable and no stylesheet or font failed; a route -with unstable pixels or a failed asset gets its own row. `--progress` gets the per-shot output -when piped, `--no-progress` the summary on a terminal. +with unstable pixels or a failed asset gets its own row. A shot whose only difference varied +between two loads of the right side is clean, but listed under `varies`. `--progress` gets +the per-shot output when piped, `--no-progress` the summary on a terminal. ## Tokens @@ -46,6 +47,9 @@ when piped, `--no-progress` the summary on a terminal. | `line -1px@y812` | A 1–2px line across the page only the right draws (`+`: only the left; no sign: both, differently). A lost border or divider; not counted in `reg`. | | `3 reg` | Regions: connected patches of differing pixels. A missing link barely moves the score, but it is still a region. | | `unstable 1,204px` | Pixels that kept changing between shots of the same load (a ticker, a carousel). Excluded from the score, so the route is never clean. | +| `varies /a @1440 148,480px div.drift` | After the routes: the right side differed between two fresh loads there (a counter, a rotating banner). Those elements are painted out on both sides like a mask and left out of the score; the shot can't be accepted. `(not located)`: no element was named, its region was painted. | +| ` --mask 'div.drift'` | The flag that masks every `varies` element, for the next run. | +| ` masks: [{ selector: … }]` | The same as config `masks` entries, with `reason: "varies per load"`. | | `failed left: font Inter 700` | A stylesheet or font face that side failed to load (blocked URLs aside). Fix that first: a fallback font changes every line of text. | | `text -"Pricing"` | A line of visible text only the reference has (`+`: only your change). Up to three, then `(+N more)`. | | `dom sel prop a→b` | Element on both sides whose computed `prop` differs, left value first. | @@ -305,6 +309,7 @@ pulls a route), scores rounded down to four decimals (so a shot that differs nev "score": 0.9714, // share of measured pixels that match "alignedScore": 1, // score over the aligned rows; null unless there are bands "diffPixels": 33120, "totalPixels": 1158000, "unstablePixels": 0, + "varies": [], "variesPixels": 0, // absent unless a second right load differed: its regions, with elements, and the px painted out "heightDelta": -24, "widthDelta": 0, // left − right "regions": [], // left-page px; with bands, from the realigned rows "bands": [{ "side": "right", "y": 196, "h": 24, // null: too different to align diff --git a/skills/renderdiff/SKILL.md b/skills/renderdiff/SKILL.md index bd9a793..6070472 100644 --- a/skills/renderdiff/SKILL.md +++ b/skills/renderdiff/SKILL.md @@ -35,11 +35,11 @@ Pixels decide the score and the exit code in every mode. § Reference and routes; moved page, component, sign-in, click state: § Scoping. 2. **Baseline**: base vs base. Before changing code, the untouched change side against the reference; if the change is already made, the base build served on two ports. Whatever - differs varies per load: mask it (`--mask-media` for iframes, `--mask ` or a config - mask with a `reason`; video is already frozen; a looping carousel: stop it with a - `before` hook on both sides, or mask it), and rerun until clean. Against production instead: - open each difference, then `--accept "differs before the change"`. § Masks, accepts and - thresholds. + differs varies per load: mask it (a `varies` line prints the mask; `--mask-media` for + iframes, `--mask ` or a config mask with a `reason`; video is already frozen; a + looping carousel: stop it with a `before` hook on both sides, or mask it), and rerun + until clean. Against production instead: open each difference, then + `--accept "differs before the change"`. § Masks, accepts and thresholds. 3. **Change, run all routes at default widths, read each row in this order**: `ERROR` → `failed` (a missing stylesheet or font explains the whole row: fix, rerun) → `text` → `h`/`w`, `band`, `aligned`, `line` → `dom` (`sel prop l→r` is a computed value: find the diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index b96a73e..5c039d8 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -60,6 +60,7 @@ on stderr: `✗ 2 routes differ (10 shots).` (`below 97.00%` with `--threshold`) | ` dom …` | Up to three elements behind the changes, two properties each. `dom @1440 …`: from the first width of the row. | | ` crops …` | At most three crop PNGs per shot (bands first, tallest first, then largest regions), relative to `results.json`. | | ` @w ERROR …` | Unmeasured. Grouped across widths sharing a message. See Errors. | +| `varies /a @1440 Npx sel` | A differing shot's right side, reloaded in a fresh context, differed from its first load there. Painted out on both sides like a mask, left out of the score (clean if nothing else differs), never accepted. Then ` --mask '…'` and ` masks: [{ …, reason: "varies per load" }]`: confirm it with a base-vs-base baseline before you use either. Off with `--no-recheck` and under `--cache-right`. | | `renderdiff: D of R routes differ (S of T shots), E errors, worst …` | `S` counts unaccepted shots with any differing pixel; `worst` leaves accepted shots out. With `--threshold`: `, K below 97.00%`. | **Row tokens**, in order @@ -174,8 +175,8 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so - Accepted entries go to `renderdiff.accepted.json` next to the config (or cwd), one per band or region, scoped by the run's routes and widths. A match ignores `y` and needs the same kind, side, box, pixel hash (4 bits a channel) and named elements, so anything else drawn - there still surfaces. Never accepted: a shot with unstable pixels, a width delta, or a height - delta without bands; `--accept` exits 1 on those. A new change can make an accepted one + there still surfaces. Never accepted: a shot with unstable pixels, `varies`, a width delta, + or a height delta without bands; `--accept` exits 1 on those. A new change can make an accepted one re-read as different (repeated rows aligning differently): look, then accept again. - **Accept where you check.** The pixel hash isn't portable: entries accepted on macOS mostly come back stale on a Linux CI runner. For CI, accept in CI. @@ -293,7 +294,8 @@ For scripts and drilling into one route; the loop doesn't need it. One result pe - **Each result:** `url`, `left`, `right`, `selector` (`{ left, right }` or null), `hook`, `width`, `status` (`compared` or `error` with `error`); `score`, `alignedScore`, - `diffPixels`, `totalPixels`, `unstablePixels`, `heightDelta`, `widthDelta`; `regions` + `diffPixels`, `totalPixels`, `unstablePixels`, `varies` and `variesPixels` (absent unless a + recheck found some; regions with `elements`), `heightDelta`, `widthDelta`; `regions` (`x,y,w,h,pixels`, left-page px, `line` `{ y, h, side }`, `accepted` reason); `bands` (`side`, `y`, `h`, or null when unaligned); each with `elements` (`selector`, `side`, each side's box, `changed` `{ prop: [left, right] }`, `text`, `rightSelector`, `reparented`; absent when not diff --git a/src/accept.ts b/src/accept.ts index 6f4b75b..ed13915 100644 --- a/src/accept.ts +++ b/src/accept.ts @@ -69,11 +69,13 @@ const acceptable = (r: ComparedResult) => !unacceptable(r); export const unacceptable = (r: ComparedResult) => r.unstablePixels ? "unstable" - : r.widthDelta - ? "width change" - : r.bands === null && r.heightDelta - ? "unaligned height" - : null; + : r.variesPixels + ? "varies per load" + : r.widthDelta + ? "width change" + : r.bands === null && r.heightDelta + ? "unaligned height" + : null; export function readAccepted(file: string): Accepted[] { if (!fs.existsSync(file)) return []; diff --git a/src/cli.ts b/src/cli.ts index fcfb018..65bd342 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -42,6 +42,7 @@ interface Args extends CliOverrides { accept?: string; rerunFailed: boolean; cacheRight: boolean; + recheck: boolean; } /** `Number(raw)`, but reject anything that isn't a finite number with a flag-named error. */ @@ -59,6 +60,7 @@ function parseArgs(argv: string[]): Args { open: false, rerunFailed: false, cacheRight: false, + recheck: true, help: false, version: false, routes: [], @@ -91,6 +93,7 @@ function parseArgs(argv: string[]): Args { else if (v === "--no-progress") a.progress = false; else if (v === "--rerun-failed") a.rerunFailed = true; else if (v === "--cache-right") a.cacheRight = true; + else if (v === "--no-recheck") a.recheck = false; else if (v === "--computed") a.computed = true; else if (v === "--mask-media") a.maskMedia = true; else if (v === "--no-freeze-video") a.freezeVideo = false; @@ -224,6 +227,8 @@ const HELP = ` --cache-right Replay the right side's network from the last --cache-right run in --out, if under an hour old and covering every shot; else load it live and record it. The page still renders and is shot fresh. + --no-recheck Don't reload a differing shot's right side to find content that + varies per load. Off anyway under --cache-right. --computed Also diff every element's computed style and ::before/::after, and say whether the markup is identical. Pixels still decide. --dry-run Print the URL pairs and exit. No browser. @@ -389,6 +394,7 @@ try { accept: args.accept ?? null, rerun: args.rerunFailed, cacheRight: args.cacheRight, + recheck: args.recheck, acceptedFile: path.join(configPath ? path.dirname(configPath) : process.cwd(), ACCEPTED_FILE), }), ); diff --git a/src/report.ts b/src/report.ts index 9c84d5e..36b2ef3 100644 --- a/src/report.ts +++ b/src/report.ts @@ -40,6 +40,10 @@ export interface ComparedResult extends BaseResult { widthDelta: number; /** Pixels that changed between shots of the same load, painted out on both sides. */ unstablePixels: number; + /** Regions where a second, fresh load of the right side differed from the first. Absent when none did or it wasn't rechecked. */ + varies?: Region[]; + /** Pixels painted out for them on both sides, like unstable ones, and left out of the score. */ + variesPixels?: number; /** Connected diff patches, largest first. */ regions: Region[]; /** Rows only one side has; null when the rows were too different to align. */ @@ -356,6 +360,7 @@ const head = (r: ComparedResult) => ` ${r.heightDelta ? `height ${signed(r.heightDelta)}px` : ""} ${r.widthDelta ? `width ${signed(r.widthDelta)}px` : ""} ${r.unstablePixels ? `${r.unstablePixels.toLocaleString("en-US")} px unstable` : ""} + ${r.variesPixels ? `${r.variesPixels.toLocaleString("en-US")} px vary per load` : ""} ${r.alignedScore !== null ? `aligned ${pct(r.alignedScore)}` : ""} ${r.computed ? `${r.computed.dom ? `dom differs (${r.computed.dom})` : "dom identical"}` : ""} ${r.diffPixels.toLocaleString()} / ${r.totalPixels.toLocaleString()} px differ @@ -580,6 +585,7 @@ export async function writeEvidence( const notes = [ ...count(errors.length, "error(s)"), ...count(open.filter((r) => r.unstablePixels).length, "shot(s) with unstable pixels"), + ...count(open.filter((r) => r.varies).length, "shot(s) vary per load (painted out)"), ...count(open.filter((r) => fmtFailed(r.failed)).length, "shot(s) with failed assets"), ...count( open.filter((r) => r.diffPixels > 0 && !fails(r, meta.threshold)).length, diff --git a/src/run.ts b/src/run.ts index 9e4f04c..c4c5949 100644 --- a/src/run.ts +++ b/src/run.ts @@ -3,11 +3,12 @@ import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; -import { chromium, errors, type Browser, type Page } from "playwright"; +import { chromium, errors, type Browser, type BrowserContext, type Page } from "playwright"; +import sharp from "sharp"; import { applyAccepted, readAccepted, unacceptable, updateAccepted } from "./accept.ts"; import { CACHE_DIR, cacheFile, replayable, REPLAY_TTL, saveRecording, shotId } from "./cache.ts"; import { cancelUnstable, capture, HookError, prepare, step, type Shot } from "./capture.ts"; -import { compare, crops, type Band, type Region } from "./compare.ts"; +import { compare, crops, type Band, type Box, type Region } from "./compare.ts"; import { diffSnapshots, fmtComputed, pageError } from "./computed.ts"; import { locate, snapshot, type ElementDiff } from "./locate.ts"; import { @@ -60,6 +61,8 @@ interface RunOpts { acceptedFile: string; /** Replay the right side's traffic from the out dir's recording, or record one. */ cacheRight: boolean; + /** Reload a differing shot's right side in a fresh context to find what varies per load. */ + recheck: boolean; } const slug = (url: string) => @@ -170,6 +173,7 @@ export async function run({ rerun, acceptedFile, cacheRight, + recheck, }: RunOpts): Promise { const names = routes.map(name); const setup = { @@ -319,13 +323,73 @@ export async function run({ } // A replay that went live in part compared against two different moments of the reference. if (missed) rightShot.failed.push(`${missed} request(s) not in the recording, loaded live`); + const raw = [leftShot.png, rightShot.png] as const; const unstablePixels = await cancelUnstable(leftShot, rightShot); - const { diffPng, spots, ...metrics } = await compare(leftShot, rightShot); + let { diffPng, spots, ...metrics } = await compare(leftShot, rightShot); if (unstablePixels > MAX_UNSTABLE_SHARE * metrics.totalPixels) { throw new Error(`page did not settle: ${unstablePixels}px unstable at ${key}`); } - const measured = metrics.totalPixels - unstablePixels; + let varies: Region[] = []; + let variesPixels = 0; + if (recheck && !har && metrics.diffPixels) { + let ctx: BrowserContext | undefined; + try { + ctx = await browser.newContext({ + ...CONTEXT_OPTIONS, + storageState: cfg.storageState.right ?? undefined, + }); + const again = { left: pages.left, right: await ctx.newPage() }; + await prepare(again.right, cfg, now); + const shot = await shoot( + again, + cfg.right + route.right, + route, + "right", + width, + cfg, + now, + ); + const self = await compare({ ...rightShot, png: raw[1] }, shot); + if (self.diffPixels) { + const found = self.spots.filter((s) => s.kind === "region"); + const named = await Promise.race([ + locate([pages.right, again.right], [rightShot, shot], found, [ + masksFor(cfg, pages.right, route), + masksFor(cfg, again.right, route), + ]).catch(() => null), + sleep(LOCATE_TIMEOUT, null, { ref: false }), + ]); + named?.forEach((els, i) => (found[i]!.target.elements = els)); + const regions = self.regions.map(({ hash, ...g }) => g); + // Element boxes, not the pixels that changed: those miss the left's own value. + const mask = await boxMask( + raw[1], + regions.flatMap((g) => { + const own = g.elements?.flatMap((e) => (e.left ? [e.left] : [])) ?? []; + return own.length ? own : [g]; + }), + ); + const u = rightShot.unstable; + const l = { ...leftShot, png: raw[0] }; + const r = { + ...rightShot, + png: raw[1], + unstable: u ? mask.map((v, i) => v | u[i]!) : mask, + }; + const painted = await cancelUnstable(l, r); + ({ diffPng, spots, ...metrics } = await compare(l, r)); + [leftShot.png, rightShot.png] = [l.png, r.png]; + varies = regions; + variesPixels = painted - unstablePixels; + } + } catch { + // A hint, like locate: a failed recheck leaves the shot as first measured. + } finally { + await ctx?.close().catch(() => {}); + } + } + const measured = metrics.totalPixels - unstablePixels - variesPixels; metrics.score = measured > 0 ? 1 - metrics.diffPixels / measured : 0; const base = `${stems.get(key)}.${width}`; const images = { @@ -384,6 +448,7 @@ export async function run({ status: "compared", ...metrics, unstablePixels, + ...(variesPixels ? { varies, variesPixels } : {}), images, crops: cropped, accepted: false, @@ -642,6 +707,56 @@ async function shoot( } } +/** A per-pixel mask the size of `png`, set inside each box. */ +async function boxMask(png: Buffer, boxes: Box[]): Promise { + const { width = 0, height = 0 } = await sharp(png).metadata(); + const mask = new Uint8Array(width * height); + for (const b of boxes) { + const [x0, y0] = [Math.max(0, Math.floor(b.x)), Math.max(0, Math.floor(b.y))]; + const [x1, y1] = [ + Math.min(width, Math.ceil(b.x + b.w)), + Math.min(height, Math.ceil(b.y + b.h)), + ]; + for (let y = y0; y < y1; y++) mask.fill(1, y * width + x0, y * width + Math.max(x0, x1)); + } + return mask; +} + +/** Routes whose right side differed between two loads, and the mask that would cover it. */ +function fmtVaries(results: RouteResult[], routes: string[]): string[] { + const rows = results.filter((r): r is ComparedResult => r.status === "compared" && !!r.varies); + const selectors = (rs: ComparedResult[]) => [ + ...new Set( + rs.flatMap((r) => + r.varies!.flatMap((g) => g.elements ?? []).map((e) => e.selector.replace(/::\w+$/, "")), + ), + ), + ]; + const out: string[] = []; + const masks: string[] = []; + for (const route of routes) { + const rs = rows.filter((r) => name(r) === route); + if (!rs.length) continue; + const sels = selectors(rs); + const px = rs.reduce((n, r) => n + r.variesPixels!, 0); + out.push( + `varies ${route} @${rs.map((r) => r.width).join(",")} ` + + `${px.toLocaleString("en-US")}px ${sels.join(" ") || "(not located)"}`, + ); + for (const s of sels) { + masks.push( + `{ selector: ${JSON.stringify(s)}, urlPath: ${JSON.stringify(rs[0]!.right)}, reason: "varies per load" }`, + ); + } + } + const sels = selectors(rows); + if (sels.length) { + out.push(` --mask ${sels.map((s) => `'${s.replace(/'/g, `'\\''`)}'`).join(" --mask ")}`); + out.push(` masks: [${masks.join(", ")}]`); + } + return out; +} + function summarize( results: RouteResult[], routes: string[], @@ -677,6 +792,8 @@ function summarize( const computed = fmtComputed(results, routes); if (computed.length) console.log(`\n${computed.join("\n")}`); + const varies = fmtVaries(results, routes); + if (varies.length) console.log(`\n${varies.join("\n")}`); console.log(`\nReport: ${reportPath}`); console.log(`Results: ${resultsPath}`); @@ -769,7 +886,7 @@ export function compact( } if (accepted.length) out.unshift(`accepted: ${accepted.join(" ")}`); if (clean.length) out.unshift(`clean: ${clean.join(" ")}`); - out.push(...fmtComputed(results, routes)); + out.push(...fmtComputed(results, routes), ...fmtVaries(results, routes)); const all = results.filter((r): r is ComparedResult => r.status === "compared"); const compared = all.filter((r) => !r.accepted); const shots = compared.filter((r) => r.diffPixels > 0).length; diff --git a/tests/unit/cli-args.test.ts b/tests/unit/cli-args.test.ts index 82f4118..6547d36 100644 --- a/tests/unit/cli-args.test.ts +++ b/tests/unit/cli-args.test.ts @@ -60,6 +60,7 @@ describe("help and version", () => { "--mask", "--mask-media", "--no-freeze-video", + "--no-recheck", ]) { assert.ok(r.stdout.includes(flag), `--help does not mention ${flag}`); } diff --git a/tests/visual/guardrails.test.ts b/tests/visual/guardrails.test.ts index 0bf4cc1..85afb2d 100644 --- a/tests/visual/guardrails.test.ts +++ b/tests/visual/guardrails.test.ts @@ -388,11 +388,12 @@ describe("masks", () => { test("an unmasked drifting value costs the score", async () => { // Runs at 1440 only: the counter is rendered smaller at mobile, so it is a smaller share of // the page and the contrast with the masked run is less clear-cut. - const run = await capture(["/drifting"]); + const run = await capture(["/drifting"], { extra: ["--no-recheck"] }); const c = cardFor(run, "/drifting"); // Measured 99.38%. What matters is that it is not parity. assert.ok(c.diffPixels > 0, `the fixture did not drift${context(run)}`); assert.ok(c.score < 0.999, `expected < 0.999, got ${c.score}${context(run)}`); + assert.equal(result(results(run.outDir), "/drifting", 1440).varies, undefined, context(run)); assert.equal(c.heightDelta, 0, "masking should never have been about height"); assert.deepEqual( [c.added.length, c.removed.length], @@ -424,6 +425,40 @@ describe("masks", () => { "render counter on /drifting differs between the two origins", ]); }); + + test("content that varies per load is painted out, clean and listed", async () => { + const run = await capture(["/drifting", "/color"]); + assert.equal(run.code, 1, `/color still differs${context(run)}`); + const s = parseSummary(run.stdout); + assert.ok(s.clean.includes("/drifting"), context(run)); + const res = results(run.outDir); + assert.equal(result(res, "/color", 1440).varies, undefined, context(run)); + const r = result(res, "/drifting", 1440); + assert.equal(r.diffPixels, 0, context(run)); + assert.ok(r.variesPixels! > 0, context(run)); + assert.match(r.varies![0]!.elements![0]!.selector, /drift/, context(run)); + assert.match(run.stdout, /^varies \/drifting @1440 /m); + assert.match(run.stdout, /^ {2}--mask '/m); + assert.match(run.stdout, /urlPath: "\/drifting", reason: "varies per load" \}\]$/m); + }); + + test("a real change beside varying content still differs, and can't be accepted", async () => { + const dir = tempDir(); + const hook = path.join(dir, "hook.mjs"); + fs.writeFileSync( + hook, + `export default { before: async (page, { side }) => { if (side === "left") await page.addStyleTag({ content: "h1 { color: red }" }); } };\n`, + ); + const run = await capture(["/drifting"], { config: hook, extra: ["--accept", "x"] }); + const r = result(results(run.outDir), "/drifting", 1440); + assert.ok(r.diffPixels > 0, context(run)); + assert.ok(r.variesPixels! > 0, context(run)); + assert.match( + run.stdout, + /not accepted: 1 differing shot\(s\) can't be \(1 varies per load\)/, + context(run), + ); + }); }); describe("selector masks", () => {