test(pdf): step 6 phase 0 freeze — demo report, bare v3 PDF, 39 goldens (text, images, links, views) and route characterisation tests

This commit is contained in:
bchanot committed 2026-10-11 12:13:36 +02:00
1 parent 694092610d
commit 8b86b926c8
46 files changed
+18502 -5

No files matched your search

+203
View File
@@ -0,0 +1,203 @@
/**
* Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17): the current PDF
* pipeline recorded as goldens, per report × locale × logo mode. Generated
* once with `MAKE_GOLDEN=1`; without the flag the same file asserts them.
* Never regenerate without a user decision: the Step 6 engine must
* reproduce these files.
*/
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
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,
installLogoFetch,
MAKE_GOLDEN,
readLinks,
recordDrawing,
snapshotViews,
type ImageEntry,
type LinkEntry,
type LogoMode,
type TextEntry,
} from '../helpers/goldens'
/** 1×1 PNG (nologos: the legacy stub) and 2×1 PNG (logos: deterministic partner logo width). */
const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
const TWO_BY_ONE_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGPYEWX///9/AA0PBE/1T7nxAAAAAElFTkSuQmCC',
'base64',
),
)
const raster = vi.hoisted(() => ({ png: new Uint8Array() }))
vi.mock('@/pdf/render/svgToPng', () => ({
rasterizeSvg: vi.fn(async () => raster.png),
}))
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
const restoreFetch = installLogoFetch(mode)
const recording = recordDrawing()
try {
const bytes = await exportReportToPdf(report, sheet, { locale })
const { texts, images } = recording
return { bytes, texts, images, links: await readLinks(bytes) }
} finally {
recording.stop()
restoreFetch()
}
}
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)
})
it('highlighted views', () => {
checkGolden(`views.${name}.json`, snapshotViews(sheet, reports[name]))
})
})
describe('report-v3.bare.pdf', () => {
it('is the demo report exported without logos and imports back unchanged', async () => {
if (MAKE_GOLDEN) {
const { bytes } = await exportWith(reports.demo, 'nologos', 'fr')
writeFileSync(BARE_PDF, bytes)
}
const bytes = new Uint8Array(readFileSync(BARE_PDF))
const outcome = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
expect(outcome.migrated).toBe(false)
expect(outcome.report).toEqual(reports.demo)
})
})