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)
})
})
@@ -0,0 +1,119 @@
/**
* Step 6 Phase 0 characterisation of the export flow on the editor route,
* with `exportReportToPdf` mocked: the call shape (store report, loaded
* index, locale), the download name and the failure alert. Phase 4 adapts
* only the mocked module path and the call-shape assertion.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
beforeEach,
afterEach,
} from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import EditorRoute from '@/app/routes/EditorRoute'
import { exportReportToPdf } from '@/pdf/export'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() }))
const exportMock = vi.mocked(exportReportToPdf)
let sheet: SheetIndex
const downloads: string[] = []
const realCreateObjectURL = URL.createObjectURL
const realRevokeObjectURL = URL.revokeObjectURL
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
sessionStorage.setItem('osteo:disclaimer-shown', '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.getState().hydrateReport(minimalReport(sheet))
exportMock.mockReset()
downloads.length = 0
URL.createObjectURL = vi.fn(() => 'blob:faunosteo-test')
URL.revokeObjectURL = vi.fn()
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
this: HTMLAnchorElement,
) {
downloads.push(this.download)
})
vi.stubGlobal('alert', vi.fn())
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
vi.unstubAllGlobals()
URL.createObjectURL = realCreateObjectURL
URL.revokeObjectURL = realRevokeObjectURL
})
async function mountAndExport(label: string): Promise<void> {
render(
<MemoryRouter initialEntries={['/editor']}>
<EditorRoute />
</MemoryRouter>,
)
const button = await screen.findByRole('button', { name: label })
await userEvent.setup().click(button)
}
describe('EditorRoute export', () => {
it('calls exportReportToPdf with the store report, the loaded index and the FR locale', async () => {
exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70]))
await mountAndExport(fr['editor.export']!)
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
const [report, index, options] = exportMock.mock.calls[0]!
expect(report).toBe(useReportStore.getState().report)
expect(index).toBe(sheet)
expect(options).toEqual({ locale: 'fr' })
})
it('passes the active locale (EN)', async () => {
useLocaleStore.setState({ locale: 'en' })
exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70]))
await mountAndExport(en['editor.export']!)
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
expect(exportMock.mock.calls[0]![2]).toEqual({ locale: 'en' })
})
it('downloads bilan-<animal>-<date>.pdf through a blob URL it then revokes', async () => {
exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70]))
await mountAndExport(fr['editor.export']!)
await waitFor(() => expect(downloads).toHaveLength(1))
expect(downloads[0]).toBe('bilan-Mistral-2026-10-10.pdf')
expect(URL.createObjectURL).toHaveBeenCalledTimes(1)
const blob = vi.mocked(URL.createObjectURL).mock.calls[0]![0] as Blob
expect(blob.type).toBe('application/pdf')
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:faunosteo-test')
expect(window.alert).not.toHaveBeenCalled()
})
it('alerts editor.export_failed when the export rejects', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
exportMock.mockRejectedValue(new Error('render exploded'))
await mountAndExport(fr['editor.export']!)
await waitFor(() => expect(window.alert).toHaveBeenCalledTimes(1))
expect(window.alert).toHaveBeenCalledWith(fr['editor.export_failed'])
expect(downloads).toHaveLength(0)
await waitFor(() =>
expect(
screen.getByRole('button', { name: fr['editor.export'] }),
).toBeEnabled(),
)
})
})
@@ -0,0 +1,155 @@
/**
* Step 6 Phase 0 characterisation of the import flow on the home route, with
* `importReportFromPdf` mocked: the migration alert with its count, the three
* ImportError kinds plus the generic error mapped to the FR messages, and
* the navigation to /editor on success. Kept green unchanged by Step 6.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
beforeEach,
afterEach,
} from 'vitest'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import HomeRoute from '@/app/routes/HomeRoute'
import { ImportError, importReportFromPdf } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
importReportFromPdf: vi.fn(),
}))
const importMock = vi.mocked(importReportFromPdf)
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useReportStore.setState({ report: null, activeObservationIndex: 0 })
vi.stubGlobal('alert', vi.fn())
importMock.mockReset()
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
})
/** The outcome shape importReportFromPdf resolves with. */
function outcome(patch: {
migrated: boolean
unresolvedZones?: number
unresolvedFindings?: number
}) {
return {
report: minimalReport(sheet),
unresolvedZones: 0,
unresolvedFindings: 0,
...patch,
}
}
async function mountAndPickPdf(): Promise<void> {
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route path="/" element={<HomeRoute />} />
<Route path="/editor" element={<p data-testid="editor-route" />} />
</Routes>
</MemoryRouter>,
)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
const input = document.querySelector('input[type="file"]')!
const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', {
type: 'application/pdf',
})
fireEvent.change(input, { target: { files: [file] } })
}
const alertMock = () => vi.mocked(window.alert)
const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' })
describe('HomeRoute import: success paths', () => {
it('passes the file bytes and the sheet migration map, hydrates, navigates to /editor', async () => {
importMock.mockResolvedValue(outcome({ migrated: false }))
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(importMock).toHaveBeenCalledTimes(1)
const [bytes, map] = importMock.mock.calls[0]!
expect(bytes).toBeInstanceOf(Uint8Array)
expect(map).toBe(sheet.sheet.migrationMap)
expect(useReportStore.getState().report?.id).toBe('r1')
expect(alertMock()).not.toHaveBeenCalled()
})
it('alerts with the unresolved count (zones + findings) after a lossy migration', async () => {
importMock.mockResolvedValue(
outcome({ migrated: true, unresolvedZones: 1, unresolvedFindings: 1 }),
)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(alertMock()).toHaveBeenCalledTimes(1)
const message = alertMock().mock.calls[0]![0] as string
expect(message).toBe(fr['home.import.migrated']!.replace('{count}', '2'))
expect(message).toContain('2')
})
it('stays silent on a migration that lost nothing', async () => {
importMock.mockResolvedValue(outcome({ migrated: true }))
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(alertMock()).not.toHaveBeenCalled()
})
})
describe('HomeRoute import: error paths', () => {
const cases: Array<[string, Error, string]> = [
[
'incompatible_version → message with the found version',
new ImportError('incompatible_version', 7),
fr['home.import.error_incompatible_version']!.replace('{version}', '7'),
],
[
'invalid_pdf → unreadable PDF message',
new ImportError('invalid_pdf'),
fr['home.import.error_invalid_pdf']!,
],
[
'no_attachment → not a Faunosteo PDF message',
new ImportError('no_attachment'),
fr['home.import.error_no_attachment']!,
],
[
'generic Error → generic message',
new Error('disk on fire'),
fr['home.import.error_generic']!,
],
]
it.each(cases)('%s', async (_label, error, expected) => {
importMock.mockRejectedValue(error)
await mountAndPickPdf()
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(expected)
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
expect(alertMock()).not.toHaveBeenCalled()
})
})