Files
quality_analyse/web/verification/analysis_report_png.test.mjs
T
lyun ff7bbe3e46 同步:完善质量分析工作台并更新主题字体
同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。
补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。
统一午夜黑及其他主题的控件细节、中文和业务数字字体。
排除本地业务数据、凭据、预览、发布与验收产物。

验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
2026-10-30 22:40:58 +08:00

247 lines
12 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { inflateSync } from 'node:zlib';
import { encodeRgbaStripsToPng, reportLongImagePixelLimit } from '../src/analysisReportPng.ts';
import { requiresFullResolutionStripCapture } from '../src/analysisReportFiles.ts';
import {
assertReportFooterAfterLastRecord,
assertReportMeasurementAtOneX,
createReportSvgStripMarkupFactory,
findReportTailMarkerTop,
isDocumentNodeFollowing,
normalizeReportRectOffset,
requiresMeasuredReportSnapshot,
reportSvgDataUrl,
resolveReportCanvasPixelRatio,
resolveReportSnapshotHeight,
} from '../src/analysisReportCapture.ts';
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
const captureSource = readFileSync(new URL('../src/analysisReportCapture.ts', import.meta.url), 'utf8');
function crc32(bytes) {
let crc = 0xffffffff;
for (const byte of bytes) {
crc ^= byte;
for (let bit = 0; bit < 8; bit += 1) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
}
return (crc ^ 0xffffffff) >>> 0;
}
function parsePng(bytes) {
assert.deepEqual(bytes.subarray(0, 8), signature);
const chunks = [];
let offset = 8;
while (offset < bytes.length) {
const length = bytes.readUInt32BE(offset);
const type = bytes.toString('ascii', offset + 4, offset + 8);
const data = bytes.subarray(offset + 8, offset + 8 + length);
const expectedCrc = bytes.readUInt32BE(offset + 8 + length);
assert.equal(crc32(bytes.subarray(offset + 4, offset + 8 + length)), expectedCrc, `${type} CRC`);
chunks.push({ type, data });
offset += length + 12;
if (type === 'IEND') break;
}
assert.equal(offset, bytes.length, 'no bytes after IEND');
return chunks;
}
function makePixels(width, height) {
const pixels = new Uint8Array(width * height * 4);
for (let y = 0; y < height; y += 1) {
for (let x = 0; x < width; x += 1) {
const offset = (y * width + x) * 4;
pixels[offset] = (x * 31 + y * 13) & 0xff;
pixels[offset + 1] = (x * 7 + y * 47) & 0xff;
pixels[offset + 2] = (x * 73 + y * 3) & 0xff;
pixels[offset + 3] = (x + y * 19) & 0xff;
}
}
return pixels;
}
async function* splitPixels(pixels, width, height, stripHeight) {
for (let y = 0; y < height; y += stripHeight) {
const rows = Math.min(stripHeight, height - y);
const start = y * width * 4;
yield { y, height: rows, data: pixels.subarray(start, start + rows * width * 4) };
}
}
test('full-resolution strip capture is limited to reports the legacy canvas would shrink', () => {
assert.equal(requiresFullResolutionStripCapture(900, 11912), false);
assert.equal(requiresFullResolutionStripCapture(900, 91800), true);
assert.equal(reportLongImagePixelLimit, 100_000_000);
});
test('raw-record reports always use measured snapshot layout while unrelated short reports keep the fast path', () => {
assert.equal(requiresMeasuredReportSnapshot(true, false), true, 'short raw appendices also reflow after cloning');
assert.equal(requiresMeasuredReportSnapshot(true, true), true);
assert.equal(requiresMeasuredReportSnapshot(false, true), true, 'overlong reports still use bounded strips');
assert.equal(requiresMeasuredReportSnapshot(false, false), false, 'unrelated short reports retain the old canvas path');
});
test('raw-record output matches the 1x tail probe while other reports retain their normal canvas scale', () => {
assert.equal(resolveReportCanvasPixelRatio(true, 1.2567), 1);
assert.equal(resolveReportCanvasPixelRatio(true, 1), 1);
assert.equal(resolveReportCanvasPixelRatio(true, 0.8), 0.8, 'long raw reports continue through the 1x strip path');
assert.equal(resolveReportCanvasPixelRatio(false, 1.2567), 1.2567);
assert.match(captureSource, /resolveReportCanvasPixelRatio\(hasSourceRecordList, measuredSize\.pixelRatio\)/);
});
test('SVG strip viewports crop one full-height foreignObject without changing report content', () => {
const fullReport = '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="92000" viewBox="0 0 900 92000">'
+ '<foreignObject width="100%" height="100%" x="0" y="0"><div xmlns="http://www.w3.org/1999/xhtml" style="height:92000px">'
+ '<p>首行内容</p><p>末行内容</p></div></foreignObject></svg>';
const source = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(fullReport)}`;
const viewportFor = createReportSvgStripMarkupFactory(source, 900, 92000);
const first = viewportFor(0, 2048);
assert.match(first, /<svg[^>]*width="900" height="2048" viewBox="0 0 900 2048"/);
assert.match(first, /<foreignObject width="900" height="92000"/);
assert.match(first, /首行内容/);
assert.match(first, /末行内容/);
const last = viewportFor(90112, 1888);
assert.match(last, /<svg[^>]*width="900" height="1888" viewBox="0 90112 900 1888"/);
assert.match(last, /<foreignObject width="900" height="92000"/);
assert.throws(() => viewportFor(91000, 2048), /条带范围无效/);
});
test('SVG strip rasterization uses html-to-image compatible encoded data URLs, never Blob URLs', () => {
const source = '<svg xmlns="http://www.w3.org/2000/svg"><foreignObject/></svg>';
const dataUrl = reportSvgDataUrl(source);
assert.equal(dataUrl, `data:image/svg+xml;charset=utf-8,${encodeURIComponent(source)}`);
assert.equal(decodeURIComponent(dataUrl.slice(dataUrl.indexOf(',') + 1)), source);
assert.match(captureSource, /image\.src = reportSvgDataUrl\(template\.viewportMarkup\(top, stripHeight, finalHeight\)\)/);
assert.doesNotMatch(captureSource, /createObjectURL|revokeObjectURL/);
});
test('final snapshot height uses logical layout metrics and rejects a footer before the last record', () => {
assert.equal(resolveReportSnapshotHeight({
layoutOffsetHeight: 91596,
layoutScrollHeight: 91700,
footerBottom: 91720,
footerTextBottom: 91712,
lastRecordBottom: 91684,
}), 91720);
assert.equal(resolveReportSnapshotHeight({
layoutOffsetHeight: 300,
layoutScrollHeight: 300,
footerBottom: 0,
footerTextBottom: 0,
lastRecordBottom: 620,
}), 620, 'a body-level raw appendix contributes to the measured full height');
assert.equal(resolveReportSnapshotHeight({
layoutOffsetHeight: 100,
layoutScrollHeight: 100,
footerBottom: 130,
footerTextBottom: 155,
lastRecordBottom: 0,
}), 155, 'the end of footer text can extend beyond its reported box height');
assert.equal(normalizeReportRectOffset(400, 1000, 500), 800, 'bounding-box positions are scaled back to logical layout units');
assert.doesNotThrow(() => assertReportMeasurementAtOneX(900.5, 900));
assert.doesNotThrow(() => assertReportMeasurementAtOneX(900, 900));
assert.throws(() => assertReportMeasurementAtOneX(901.01, 900), /原始比例下测量/);
assert.throws(() => assertReportMeasurementAtOneX(720, 900), /原始比例下测量/);
assert.equal(isDocumentNodeFollowing(4), true);
assert.equal(isDocumentNodeFollowing(2), false);
assert.doesNotThrow(() => assertReportFooterAfterLastRecord(91720, 91684));
assert.throws(() => assertReportFooterAfterLastRecord(91558, 91570), /末行与报告页脚排版重叠/);
assert.match(captureSource, /style\.setProperty\('height', 'auto', 'important'\)/);
assert.match(captureSource, /\.q-source-record-set,table,thead,tbody,tr,th,td/);
assert.match(captureSource, /await measurementDocument\.fonts\?\.ready/);
assert.match(captureSource, /image\.decode\?\.\(\)\.catch/);
assert.match(captureSource, /measurementFrame\.setAttribute\('sandbox', 'allow-same-origin'\)/);
assert.match(captureSource, /measurementFrame\.srcdoc = .*zoom:1!important/);
assert.match(captureSource, /border:0;margin:0;padding:0;box-sizing:border-box/);
assert.match(captureSource, /assertReportMeasurementAtOneX\(clonedRoot\.getBoundingClientRect\(\)\.width, clonedRoot\.offsetWidth\)/);
assert.doesNotMatch(captureSource, /clonedRoot\.style\.height/);
assert.match(captureSource, /measurementFrame\.remove\(\)/);
assert.match(captureSource, /const layoutRoot = clonedRoot/);
assert.match(captureSource, /layoutRoot\.querySelectorAll<HTMLElement>\('\.q-source-record-list tbody tr,tr\[data-record-provenance\]'\)/);
assert.match(captureSource, /isDocumentNodeFollowing\(lastRecordRow\.compareDocumentPosition\(candidate\)\)/);
assert.match(captureSource, /layoutOffsetHeight: layoutRoot\.offsetHeight/);
assert.match(captureSource, /await measurementDocument\.fonts\?\.ready/);
assert.match(captureSource, /range\.getBoundingClientRect\(\)/);
assert.match(captureSource, /footerTextBottom: footerTextRangeBottom/);
assert.doesNotMatch(captureSource, /DEBUG-source-record-tail/);
assert.match(captureSource, /:root,:root>body\{/);
assert.match(captureSource, /:root>body\{min-height:0!important\}/);
assert.match(captureSource, /canvas\.width = width \* capturePixelRatio/);
assert.match(captureSource, /foreignObject\.append\(marker\)/);
assert.match(captureSource, /return findReportTailMarkerTop\(pixels, width, probeHeight, probeTop\)/);
assert.match(captureSource, /const finalHeight = await calibrateReportTailHeight/);
assert.match(captureSource, /REPORT_TAIL_MARKER_HEIGHT \+ 1/);
});
test('raster tail probe finds a full 2-color marker row without treating antialiased edges as its top', async () => {
const width = 64, height = 24, markerTop = 8, probeTop = 23_000;
const pixels = new Uint8ClampedArray(width * height * 4);
for (let i = 0; i < pixels.length; i += 4) pixels.set([255, 255, 255, 255], i);
for (let y = markerTop; y < markerTop + 8; y += 1) {
for (let x = 0; x < 32; x += 1) {
pixels.set(x < 16 ? [255, 0, 255, 255] : [0, 255, 255, 255], (y * width + x) * 4);
}
}
// A partial magenta row above the marker is deliberately insufficient by itself.
for (let x = 0; x < 32; x += 1) pixels.set([255, 80, 255, 255], ((markerTop - 1) * width + x) * 4);
assert.equal(findReportTailMarkerTop(pixels, width, height, probeTop), probeTop + markerTop + 1,
'the output boundary includes the first marker pixel to avoid clipping from subpixel antialiasing');
const oneRow = pixels.slice();
for (let y = markerTop + 1; y < markerTop + 8; y += 1) {
for (let x = 0; x < 32; x += 1) oneRow.set([255, 255, 255, 255], (y * width + x) * 4);
}
await assert.rejects(async () => findReportTailMarkerTop(oneRow, width, height, probeTop), /未能确认报告长图尾部位置/);
});
test('strip encoder keeps full dimensions and row order in one valid multi-IDAT PNG', async () => {
const width = 300, height = 300;
const expected = makePixels(width, height);
const blob = await encodeRgbaStripsToPng(width, height, splitPixels(expected, width, height, 37));
assert.equal(blob.type, 'image/png');
const chunks = parsePng(Buffer.from(await blob.arrayBuffer()));
assert.equal(chunks[0].type, 'IHDR');
assert.equal(chunks.at(-1).type, 'IEND');
assert.ok(chunks.slice(1, -1).length > 1);
assert.ok(chunks.slice(1, -1).every(chunk => chunk.type === 'IDAT'));
assert.ok(chunks.slice(1, -1).every(chunk => chunk.data.length <= 64 * 1024));
const header = chunks[0].data;
assert.equal(header.readUInt32BE(0), width);
assert.equal(header.readUInt32BE(4), height);
assert.equal(header[8], 8);
assert.equal(header[9], 6);
const compressed = Buffer.concat(chunks.slice(1, -1).map(chunk => chunk.data));
const raw = inflateSync(compressed);
const scanlineLength = width * 4 + 1;
assert.equal(raw.length, scanlineLength * height);
const decoded = new Uint8Array(width * height * 4);
for (let row = 0; row < height; row += 1) {
const source = row * scanlineLength;
assert.equal(raw[source], 0, `filter for row ${row}`);
decoded.set(raw.subarray(source + 1, source + scanlineLength), row * width * 4);
}
assert.deepEqual(decoded, expected);
});
test('strip encoder rejects canceled exports instead of returning a partial PNG', async () => {
let cancelled = false;
async function* strips() {
yield { y: 0, height: 1, data: new Uint8Array([1, 2, 3, 4]) };
cancelled = true;
yield { y: 1, height: 1, data: new Uint8Array([5, 6, 7, 8]) };
}
await assert.rejects(encodeRgbaStripsToPng(1, 2, strips(), () => cancelled), /已取消长图准备/);
});
test('strip encoder rejects missing rows and reports over the total-pixel safety limit', async () => {
async function* incomplete() { yield { y: 0, height: 1, data: new Uint8Array(4) }; }
await assert.rejects(encodeRgbaStripsToPng(1, 2, incomplete()), /未完整栅格化/);
async function* empty() { /* no rows */ }
await assert.rejects(encodeRgbaStripsToPng(10_000, 10_001, empty()), /安全尺寸上限/);
});