Files
faunosteo/apps/app/tests/unit/pdf.goldens.test.ts

243 lines
9.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17) replayed on the
* application export path: `exportReportToPdf` runs the core's session (R4.6)
* with the bundled sheet snapshotted, the bundled branding (mocked to every
* slot empty for the `nologos` mode, the real module for `logos`) and the
* browser rasterizer (mocked to fixed PNGs, as the Phase 0 stub was). Text,
* images and links goldens are read back from the file (`tests/helpers/pdfFile.ts`,
* R4.8: no pdf-lib) and asserted as frozen; `MAKE_GOLDEN=1` rewrites them,
* never without a user decision. The highlighted-view goldens are read from
* the SVGs the core's session asks the rasteriser for. At the fixed export
* time the file's bytes are the R4 digests the cargo suite froze
* (`goldens/r4/pdf.*.sha256`): the app path writes what the native core
* writes. Never regenerate `report-v3.bare.pdf`: it is the Step 5 bare
* export, an import fixture only.
*/
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import type { Report } from '@faunosteo/core-wasm/types'
import { exportReportToPdf } from '@/pdf/export'
import type { SheetIndex } from '@/services/sheetIndex'
import type { Locale } from '@/i18n/types'
import { importReportFromPdf } from '../helpers/pdfImport'
import { PdfFile, numberOf } from '../helpers/pdfFile'
import { loadTestSheet, sheetSnapshot } from '../helpers/sheet'
import {
buildGoldenReports,
GOLDEN_REPORTS,
type GoldenReportName,
} from '../helpers/goldenReports'
import {
checkGolden,
FIXED_EXPORTED_AT,
FIXTURES_DIR,
ONE_PX_PNG,
R4_GOLDEN_DIR,
readGolden,
readLinks,
sha256,
snapshotViews,
TWO_BY_ONE_PNG,
type ImageEntry,
type LinkEntry,
type LogoMode,
type TextEntry,
type ViewSnapshot,
} from '../helpers/goldens'
import { bytesOf, readDrawing } from '../helpers/pdfRead'
// The fixed PNG for every raster; the SVGs the session asks for are kept, in request
// order (the view goldens are read from them).
const raster = vi.hoisted(() => ({
png: new Uint8Array(),
svgs: [] as string[],
}))
vi.mock('@/pdf/browserRasterizer', () => ({
browserRasterizer: vi.fn(async (svg: string) => {
raster.svgs.push(svg)
return raster.png
}),
}))
const logoMode = vi.hoisted(() => ({ current: 'nologos' as LogoMode }))
vi.mock('@/pdf/branding', async () => {
const { brandingOf } = await import('../helpers/goldens')
return { loadBranding: vi.fn(() => brandingOf(logoMode.current)) }
})
const REPORTS = GOLDEN_REPORTS
const MODES: readonly LogoMode[] = ['nologos', 'logos']
const BARE_PDF = resolve(FIXTURES_DIR, 'report-v3.bare.pdf')
let sheet: SheetIndex
let reports: Record<GoldenReportName, Report>
let unresolvedOfV2Unresolved = 0
beforeAll(async () => {
sheet = await loadTestSheet()
;({ reports, unresolvedOfV2Unresolved } = buildGoldenReports(sheet))
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(FIXED_EXPORTED_AT)
})
afterAll(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
interface Exported {
bytes: Uint8Array
texts: TextEntry[]
images: ImageEntry[]
links: LinkEntry[]
}
async function exportWith(
report: Report,
mode: LogoMode,
locale: Locale,
): Promise<Exported> {
raster.png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
raster.svgs = []
logoMode.current = mode
const { pdf, warnings } = await exportReportToPdf(report, sheet, { locale })
expect(warnings).toEqual([])
const bytes = await bytesOf(pdf)
const { texts, images } = await readDrawing(bytes)
return { bytes, texts, images, links: await readLinks(bytes) }
}
/**
* The goldens were recorded in call order: every page's content, then the footers of
* every page (the engine drew them last). Read back from the file, the facts come page
* by page, each page's footer after its content: the golden in page order, stably, is
* the same sequence.
*/
function inPageOrder<T extends { page: number }>(name: string): T[] {
return [...readGolden<T[]>(name)].sort((a, b) => a.page - b.page)
}
/** The R4 digest of this run, frozen by the cargo suite from the native writer. */
function r4Digest(name: string, locale: Locale, mode: LogoMode): string {
return readFileSync(
resolve(R4_GOLDEN_DIR, `pdf.${name}.${locale}.${mode}.sha256`),
'utf8',
).trim()
}
const pagesOf = (entries: readonly { page: number }[]) =>
entries.map((e) => e.page)
/** The size of every image XObject the file's first page draws. */
function imageSizesOf(bytes: Uint8Array): [number, number][] {
const file = PdfFile.parse(bytes)
return [...file.xobjects(file.pages()[0]!).values()].map((image) => [
numberOf(image.dict, 'Width')!,
numberOf(image.dict, 'Height')!,
])
}
describe('golden inputs', () => {
it('the 2×1 PNG decodes as 2×1 and the 1×1 as 1×1', async () => {
// logos: the view and partner rasters are the 2×1 PNG, the bundled PNG logos their own size.
const two = await exportWith(reports.demo, 'logos', 'fr')
expect(imageSizesOf(two.bytes)).toContainEqual([2, 1])
// nologos: every image of the page is a view raster, the 1×1 PNG.
const one = await exportWith(reports.demo, 'nologos', 'fr')
const sizes = imageSizesOf(one.bytes)
expect(sizes.length).toBeGreaterThan(0)
expect(new Set(sizes.map(String))).toEqual(new Set(['1,1']))
})
it('the demo report covers the sheet features the goldens must freeze', () => {
const { demo } = reports
expect(demo.observations).toHaveLength(6)
const zones = demo.observations.flatMap((o) => o.zones)
const findings = demo.observations.flatMap((o) => o.findings)
expect(zones.some((z) => z.viewId === 'head')).toBe(true)
expect(zones.some((z) => z.vertebrae?.length)).toBe(true)
expect(
zones.filter((z) => z.annotationId === 'hip').map((z) => z.side),
).toEqual(['left', 'right'])
expect(findings.some((f) => f.requiresVetReferral)).toBe(true)
expect(findings.some((f) => f.labelFrSnapshot.includes('–'))).toBe(true)
expect(demo.observations.some((o) => o.freeTextFindings.length)).toBe(true)
expect(demo.nextAppointment).toBeDefined()
})
it('the v2unresolved report really carries unresolved findings', () => {
expect(unresolvedOfV2Unresolved).toBeGreaterThan(0)
const findings = reports.v2unresolved.observations.flatMap(
(o) => o.findings,
)
expect(findings.filter((f) => f.unresolved)).toHaveLength(
unresolvedOfV2Unresolved,
)
expect(findings.some((f) => !f.unresolved)).toBe(true)
})
})
describe.each(REPORTS)('goldens of %s', (name) => {
describe.each(MODES)('%s', (mode) => {
// Images and links are recorded per locale too: the footer centres the
// "powered by" block on the label width, so the ZenQuality link (and its
// logo) shift between FR and EN. Only the pagination is locale-free.
it('text, images and links per locale; same pagination across locales; app-path bytes = native digest', async () => {
const fr = await exportWith(reports[name], mode, 'fr')
const en = await exportWith(reports[name], mode, 'en')
for (const [locale, out] of [
['fr', fr],
['en', en],
] as const) {
const id = `${name}.${locale}.${mode}`
expect(out.texts, `text.${id}`).toEqual(inPageOrder(`text.${id}.json`))
expect(out.images, `images.${id}`).toEqual(
inPageOrder(`images.${id}.json`),
)
checkGolden(`links.${id}.json`, out.links)
expect(sha256(out.bytes), id).toBe(r4Digest(name, locale, mode))
}
expect(pagesOf(en.images)).toEqual(pagesOf(fr.images))
expect(pagesOf(en.links)).toEqual(pagesOf(fr.links))
}, 30_000)
})
// Hidden markers are absent in the engine (the browser hid them with
// display="none") and the layer <g> carries no data-* any more: `titles`
// shrinks to the highlighted markers plus the asset's own, and
// `dataAttributes` drops from 2 to 0. Everything else must match.
it('highlighted views: same facts but titles and data attributes', async () => {
const snapshot = sheetSnapshot(sheet, reports[name])
// Every slot empty: the session asks for the view rasters only, in request order.
await exportWith(reports[name], 'nologos', 'fr')
const actual = snapshotViews(snapshot, reports[name], raster.svgs)
const expected = readGolden<ViewSnapshot[]>(`views.${name}.json`)
const comparable = (v: ViewSnapshot) => ({
observationId: v.observationId,
viewId: v.viewId,
viewBox: v.viewBox,
halo: v.halo,
highlighted: v.highlighted,
nonHighlightedVisible: v.nonHighlightedVisible,
})
expect(actual.map(comparable)).toEqual(expected.map(comparable))
for (const view of actual) {
expect(view.dataAttributes).toBe(0)
expect(view.titles).toBeGreaterThanOrEqual(view.highlighted.length)
}
for (const view of expected) expect(view.dataAttributes).toBe(2)
})
})
describe('report-v3.bare.pdf', () => {
it('is the demo report exported bare by Step 5 and imports with no archive', async () => {
const bytes = new Uint8Array(readFileSync(BARE_PDF))
const { read: outcome } = await importReportFromPdf(bytes)
expect(outcome.origin).toBe('bare_v3')
expect(outcome.migrated).toBe(false)
expect(outcome.archive).toBeNull()
expect(outcome.snapshotRejected).toBeUndefined()
expect(outcome.report).toEqual(reports.demo)
})
})