Files
MorphDoc/packages/document-visual-diff/tests/raster.test.ts
T

54 lines
1.7 KiB
TypeScript

import { createHash } from "node:crypto";
import { createCanvas } from "@napi-rs/canvas";
import { describe, expect, it } from "vitest";
import {
comparePageRasters,
type PdfPageRaster,
} from "../src/index.js";
function raster(rectangleX: number): PdfPageRaster {
const canvas = createCanvas(80, 100);
const context = canvas.getContext("2d");
context.fillStyle = "#ffffff";
context.fillRect(0, 0, 80, 100);
context.fillStyle = "#111111";
context.fillRect(rectangleX, 20, 20, 40);
const png = Uint8Array.from(canvas.toBuffer("image/png"));
return {
widthPx: 80,
heightPx: 100,
dpi: 144,
sha256: createHash("sha256").update(png).digest("hex"),
png,
};
}
describe("PDF 栅格差异", () => {
it("相同页面的全部指标为无差异", async () => {
const page = raster(10);
const result = await comparePageRasters(page, page);
expect(result.metrics).toMatchObject({
dimensionsMatch: true,
meanAbsoluteError: 0,
changedPixelRatio: 0,
inkIou: 1,
edgeIou: 1,
});
expect(result.artifacts.overlayPng.subarray(0, 8)).toEqual(
new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]),
);
});
it("量化位移并生成稳定叠加图与热力图", async () => {
const result = await comparePageRasters(raster(10), raster(20));
expect(result.metrics.meanAbsoluteError).toBeGreaterThan(10);
expect(result.metrics.changedPixelRatio).toBeCloseTo(0.1, 2);
expect(result.metrics.inkIou).toBeCloseTo(1 / 3, 2);
expect(result.metrics.edgeIou).toBeLessThan(0.4);
expect(result.artifacts.overlaySha256).toHaveLength(64);
expect(result.artifacts.heatmapSha256).toHaveLength(64);
});
});