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

218 lines
8.3 KiB
TypeScript
Raw 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's content streams and
* asserted as frozen; `MAKE_GOLDEN=1` rewrites them, never without a user
* decision. 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 { PDFDocument } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import type { Report } from '@faunosteo/core-wasm/types'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import type { Locale } from '@/i18n/types'
import { loadTestSheet, sheetSnapshot } from '../helpers/sheet'
import {
buildGoldenReports,
GOLDEN_REPORTS,
type GoldenReportName,
} from '../helpers/goldenReports'
import {
checkGolden,
FIXTURES_DIR,
ONE_PX_PNG,
readGolden,
readLinks,
snapshotViews,
TWO_BY_ONE_PNG,
type ImageEntry,
type LinkEntry,
type LogoMode,
type TextEntry,
type ViewSnapshot,
} from '../helpers/goldens'
import { bytesOf, readDrawing } from '../helpers/pdfRead'
import { FIXED_EXPORTED_AT, R4_GOLDEN_DIR, sha256 } from '../helpers/r4-draw'
const raster = vi.hoisted(() => ({ png: new Uint8Array() }))
vi.mock('@/pdf/browserRasterizer', () => ({
browserRasterizer: vi.fn(async () => 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
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)
describe('golden inputs', () => {
it('the 2×1 PNG decodes as 2×1 and the 1×1 as 1×1', async () => {
const doc = await PDFDocument.create()
const two = await doc.embedPng(TWO_BY_ONE_PNG)
expect([two.width, two.height]).toEqual([2, 1])
const one = await doc.embedPng(ONE_PX_PNG)
expect([one.width, one.height]).toEqual([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', () => {
const snapshot = sheetSnapshot(sheet, reports[name])
const actual = snapshotViews(snapshot, reports[name])
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, sheet)
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)
})
})