Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 57 additions & 9 deletions .github/actions/runtime-gate/src/crawl.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -326,13 +326,41 @@ function baselineCoverage() {
try { return JSON.parse(fs.readFileSync(f, 'utf8')).coverage || null; } catch { return null; }
}

function diff(name) {
// pngjs's synchronous reader (PNG.sync.read) subclasses zlib.Inflate the
// pre-ES2015 way, with zlib.Inflate.call(this), which throws "Class
// constructor Inflate cannot be invoked without 'new'" from Node 27: zlib's
// streams became real classes there (nodejs/node#64849). Its streaming parser
// only calls zlib.createInflate, which works on every Node, so screenshots are
// decoded through that instead.
function readPng(file) {
return new Promise((resolve, reject) => {
const png = new PNG();
// The first error rejects; a later one must not become an unhandled
// 'error' event that kills the crawl.
png.on('error', () => {});
// The streaming parser never listens for errors on its own row filter,
// which raises one when the pixel data is shorter than the header says or
// a row has a bad filter byte; unhandled, that crashes the whole crawl.
// Hand them to the parser's own error path, which cleans up and rejects
// here. This reaches into pngjs internals (_parser, _filter,
// _handleError), so package.json pins pngjs at exactly 7.0.0; the
// short-data and bad-filter cases in test/toolkit.test.mjs fail if an
// upgrade changes them.
png.once('metadata', () => {
const parser = png._parser;
parser?._filter?.on('error', (e) => parser._handleError(e));
});
png.parse(fs.readFileSync(file), (err, img) => (err ? reject(err) : resolve(img)));
});
}

async function diff(name) {
if (!BASE_SCREENS) return null;
const before = path.join(BASE_SCREENS, `${name}.png`);
const after = path.join(SCREENS, `${name}.png`);
if (!fs.existsSync(before) || !fs.existsSync(after)) return null;
const a = PNG.sync.read(fs.readFileSync(before));
const b = PNG.sync.read(fs.readFileSync(after));
const a = await readPng(before);
const b = await readPng(after);
const width = Math.min(a.width, b.width);
const height = Math.min(a.height, b.height);
const crop = (img) => {
Expand All @@ -348,9 +376,7 @@ function diff(name) {
const ratio = changed / (width * height);
const resized = a.width !== b.width || a.height !== b.height;
if (ratio <= DIFF_THRESHOLD && !resized) return null;
ensureDir(DIFFS);
fs.writeFileSync(path.join(DIFFS, `${name}.png`), PNG.sync.write(d));
return { name, ratio, resized, before: [a.width, a.height], after: [b.width, b.height] };
return { name, ratio, resized, before: [a.width, a.height], after: [b.width, b.height], image: d };
}

// How much of the app's own JavaScript actually ran, from V8 block coverage
Expand Down Expand Up @@ -757,8 +783,28 @@ async function main() {
}
if (BASE_SCREENS) {
for (const f of fs.readdirSync(SCREENS)) {
const d = diff(f.replace(/\.png$/, ''));
if (d) visual.push({ ...d, url: urlByShot.get(d.name) || '' });
const name = f.replace(/\.png$/, '');
const where = urlByShot.get(name) || name;
// Visual changes are advisory. A screenshot that cannot be compared is
// a warning, and must never stop the crawl from writing its report.
let d;
try {
d = await diff(name);
} catch (err) {
collector.add('visual-diff-failed', `could not compare ${f} with the baseline: ${String(err.message || err).split('\n')[0]}`, { blocking: false, page: where });
continue;
}
if (!d) continue;
const { image, ...change } = d;
visual.push({ ...change, url: urlByShot.get(name) || '' });
// The change was found; failing to save the picture of it must not
// turn it into "could not compare".
try {
ensureDir(DIFFS);
fs.writeFileSync(path.join(DIFFS, f), PNG.sync.write(image));
} catch (err) {
collector.add('visual-diff-image-failed', `found a visual change in ${f} but could not save the diff image: ${String(err.message || err).split('\n')[0]}`, { blocking: false, page: where });
}
}
}

Expand Down Expand Up @@ -901,14 +947,16 @@ export function renderMarkdown(r) {
lines.push('');
}
if (r.baseline === 'compared') {
const unreadable = r.findings.filter((f) => f.kind === 'visual-diff-failed').length;
if (r.visual.length) {
lines.push(`**Visual changes vs the default branch** (advisory, ${r.visual.length}):`);
for (const v of r.visual.slice(0, 20)) {
lines.push(`- \`${v.url || v.name}\`: ${(v.ratio * 100).toFixed(1)}% of pixels differ${v.resized ? `, size ${v.before.join('×')} → ${v.after.join('×')}` : ''}`);
}
if (unreadable) lines.push(`- ${unreadable} more screenshot(s) could not be compared with the baseline (see the warnings above).`);
lines.push('');
} else {
lines.push('No visual changes against the last default-branch run.');
lines.push(unreadable ? `No visual changes found, but ${unreadable} screenshot(s) could not be compared with the baseline (see the warnings above).` : 'No visual changes against the last default-branch run.');
lines.push('');
}
}
Expand Down
58 changes: 58 additions & 0 deletions .github/actions/runtime-gate/test/toolkit.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,21 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { PNG } from 'pngjs';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '..');
const servers = [];
let GOOD = '';
let BROKEN = '';

// Two well-formed PNGs (valid signature, IHDR and CRCs, a complete zlib
// stream) whose pixel data is wrong: 50×50 RGBA with only 10 rows of data,
// and 50 rows that all use the unknown filter type 9. pngjs's streaming
// parser reports both from its internal row filter, not from the parser.
const SHORT_ROWS_PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAJElEQVR4nGNoGCaAYaAdQC0w6pHBBkY9MtjAqEcGGxj1yGADALXk6C5Ft45LAAAAAElFTkSuQmCC', 'base64');
const BAD_FILTER_PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAVElEQVR4nO3PQQ0AIAzAwPdcIx0TS2jInYJ2zifmdcAWIzVGaozUGKkxUmOkxkiNkRojNUZqjNQYqTFSY6TGSI2RGiM1RmqM1BipMVJjpMZIjZGaC1rziuAkV/agAAAAAElFTkSuQmCC', 'base64');

// Starts the static server on a free port (port 0) and resolves with its base
// URL once it is listening, so a test can never reach some other process that
// happens to hold a fixed port. Fails fast if the server exits first.
Expand Down Expand Up @@ -65,6 +73,56 @@ test('healthy site passes', () => {
assert.ok(report.findings.some((f) => !f.blocking && /404 POST .*\/api\/login .*after submitting a form/.test(f.message)), 'a 4xx answering a dummy sign-in is a warning, not a failure');
});

test('a baseline screenshot that cannot be decoded is a warning, not a crash', () => {
// The visual diff is advisory: an unreadable baseline (or a PNG decoder
// that breaks on a new Node) must not stop the crawl or lose its report.
// Not a PNG at all fails at the signature; the other two get past the
// header and fail while the rows are decoded.
const baseline = fs.mkdtempSync(path.join(os.tmpdir(), 'rg-baseline-'));
const screens = path.join(baseline, 'screens');
fs.mkdirSync(screens);
fs.writeFileSync(path.join(screens, 'desktop-root.png'), 'not a png');
fs.writeFileSync(path.join(screens, 'desktop-about.png'), SHORT_ROWS_PNG);
fs.writeFileSync(path.join(screens, 'desktop-hidden_from_nav.png'), BAD_FILTER_PNG);
const r = run('crawl.mjs', { RG_URL: GOOD, RG_BASELINE_DIR: baseline, RG_ROUTES: '/about\n/hidden-from-nav', RG_MAX_PAGES: '3', RG_INTERACT: 'false', RG_FORMS: 'false' });
assert.equal(r.status, 0, r.stdout + r.stderr);
assert.ok(fs.existsSync(path.join(r.out, 'crawl.md')), 'the summary is written');
const report = JSON.parse(fs.readFileSync(path.join(r.out, 'crawl.json'), 'utf8'));
assert.equal(report.baseline, 'compared');
const failed = report.findings.filter((x) => x.kind === 'visual-diff-failed');
for (const file of ['desktop-root.png', 'desktop-about.png', 'desktop-hidden_from_nav.png']) {
const f = failed.find((x) => x.message.includes(file));
assert.ok(f && !f.blocking, `${file}: ${JSON.stringify(report.findings, null, 1)}`);
}
assert.match(fs.readFileSync(path.join(r.out, 'crawl.md'), 'utf8'), /could not be compared with the baseline/);
});

test('a real visual change against the baseline is still reported, with its diff image', () => {
// Guards the path a passing self-baseline never reaches: comparing two
// different screenshots and saving the picture of the difference.
const first = run('crawl.mjs', { RG_URL: GOOD, RG_MAX_PAGES: '1', RG_INTERACT: 'false', RG_FORMS: 'false', RG_RETRY: 'false' });
assert.equal(first.status, 0, first.stdout + first.stderr);
const shot = path.join(first.out, 'screens', 'desktop-root.png');
const header = fs.readFileSync(shot);
// Width and height straight from IHDR, so this test does not depend on
// the decoder it is checking.
const width = header.readUInt32BE(16);
const height = header.readUInt32BE(20);
// Solid opaque black: pixelmatch blends transparency onto white, so a
// transparent image would look like the white page.
const black = new PNG({ width, height });
for (let i = 0; i < black.data.length; i += 4) black.data.writeUInt32BE(0x000000ff, i);
fs.writeFileSync(shot, PNG.sync.write(black));
const r = run('crawl.mjs', { RG_URL: GOOD, RG_BASELINE_DIR: first.out, RG_MAX_PAGES: '1', RG_INTERACT: 'false', RG_FORMS: 'false', RG_RETRY: 'false' });
assert.equal(r.status, 0, r.stdout + r.stderr);
const report = JSON.parse(fs.readFileSync(path.join(r.out, 'crawl.json'), 'utf8'));
assert.deepEqual(report.findings.filter((x) => /^visual-diff/.test(x.kind)), [], 'the screenshots were compared and the diff saved');
const v = report.visual.find((x) => x.name === 'desktop-root');
assert.ok(v && v.ratio > 0.5, JSON.stringify(report.visual));
assert.ok(fs.existsSync(path.join(r.out, 'diffs', 'desktop-root.png')), 'the diff image is saved');
assert.match(fs.readFileSync(path.join(r.out, 'crawl.md'), 'utf8'), /Visual changes vs the default branch/);
});

test('broken site fails with every kind of breakage', () => {
const r = run('crawl.mjs', { RG_URL: BROKEN, RG_ROUTES: '/items/3\n/signin', RG_PER_PATTERN: '5' });
assert.equal(r.status, 1, r.stdout + r.stderr);
Expand Down
7 changes: 6 additions & 1 deletion .github/actions/runtime-gate/test/upgrades.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,14 @@ test('signs up, signs in and crawls behind the login; coverage is reported', ()
assert.ok(c.js && c.js.percent > 0 && c.js.percent < 100, `JS coverage between 0 and 100: ${JSON.stringify(c.js)}`);
assert.match(fs.readFileSync(path.join(r.out, 'crawl.md'), 'utf8'), /\*\*Coverage:\*\*.*signed in as tester@example.com/);

// Against itself as the baseline: coverage delta is computed and is zero.
// Against itself as the baseline: every screenshot is decoded and compared,
// and the coverage delta is computed and is zero. The status check comes
// first so a crash shows its own stack, not a missing report.
const again = run('crawl.mjs', { RG_URL: GOOD, ...LOGIN, RG_BASELINE_DIR: r.out, RG_INTERACT: 'false', RG_FORMS: 'false' });
assert.equal(again.status, 0, again.log);
assert.equal(again.report.baseline, 'compared');
const unreadable = again.report.findings.filter((f) => f.kind === 'visual-diff-failed');
assert.deepEqual(unreadable, [], 'baseline screenshots can be decoded');
assert.ok(again.report.coverageDelta, 'coverage delta against the baseline');
assert.equal(again.report.coverageDelta.routesVisited, 0, JSON.stringify(again.report.coverageDelta));
});
Expand Down
Loading