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

219 lines
7.9 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` now runs the engine 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 asserted as frozen; `MAKE_GOLDEN=1` rewrites
* them, never without a user decision. 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 {
buildSheetSnapshot,
readReportDocument,
ReportSchema,
type Report,
} from '@faunosteo/domain'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import type { Locale } from '@/i18n/types'
import { loadTestSheet } from '../helpers/sheet'
import {
leavesAsV2Report,
legacyLeaves,
loadLegacyBaseline,
} from '../helpers/legacyLeaves'
import {
checkGolden,
FIXTURES_DIR,
ONE_PX_PNG,
readGolden,
readLinks,
recordDrawing,
snapshotViews,
TWO_BY_ONE_PNG,
type ImageEntry,
type LinkEntry,
type LogoMode,
type TextEntry,
type ViewSnapshot,
} from '../helpers/goldens'
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 = ['v2full', 'demo', 'v2unresolved'] as const
type ReportName = (typeof REPORTS)[number]
const MODES: readonly LogoMode[] = ['nologos', 'logos']
const BARE_PDF = resolve(FIXTURES_DIR, 'report-v3.bare.pdf')
const readJson = (name: string): unknown =>
JSON.parse(readFileSync(resolve(FIXTURES_DIR, name), 'utf8'))
let sheet: SheetIndex
let reports: Record<ReportName, Report>
let unresolvedOfV2Unresolved = 0
/** sphenoid + ssb (the families the migration cannot place) plus one leaf that resolves. */
function buildV2Unresolved(): Report {
const leaves = legacyLeaves(loadLegacyBaseline())
const unresolvedFamilies = leaves.filter(
(l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb',
)
const resolved = leaves.find((l) => l.zoneId === 'frontal')!
const outcome = readReportDocument(
leavesAsV2Report([...unresolvedFamilies, resolved]),
sheet.sheet.migrationMap,
)
unresolvedOfV2Unresolved = outcome.unresolvedFindings
return outcome.report
}
beforeAll(async () => {
sheet = await loadTestSheet()
reports = {
v2full: readReportDocument(
readJson('report-v2.full.json'),
sheet.sheet.migrationMap,
).report,
demo: ReportSchema.parse(readJson('report-v3.demo.json')),
v2unresolved: buildV2Unresolved(),
}
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => 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 recording = recordDrawing()
try {
const { pdf: bytes } = await exportReportToPdf(report, sheet, { locale })
const { texts, images } = recording
return { bytes, texts, images, links: await readLinks(bytes) }
} finally {
recording.stop()
}
}
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', 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) {
checkGolden(`text.${name}.${locale}.${mode}.json`, out.texts)
checkGolden(`images.${name}.${locale}.${mode}.json`, out.images)
checkGolden(`links.${name}.${locale}.${mode}.json`, out.links)
}
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 = buildSheetSnapshot(sheet.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 outcome = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
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)
})
})