Files
faunosteo/apps/app/tests/unit/routes.HomeRoute.rescueCopy.test.tsx
T
bchanot 6d1cce6e06 feat(app): R4.3b/c import worker, client, controller; HomeRoute on the disposable worker
Protocol v1 (task → ready → result | failed with phase and kind), the worker entry with
the glue bundled statically and the page's compiled Module posted, the file streamed into
the module's memory; client with start and task timers (paused while hidden), settle-once,
terminate always, error events never masked; module-level controller (one import at a
time, cancel on leaving Home, worker chunk prefetched once the engine is loaded); the
settlement mapped to the B.1.8 messages (OD-5: a trap, a timeout or an unreadable file is
« Erreur de lecture du PDF. », never a corrupt PDF). HomeRoute keeps its routing and size
pre-checks, loads its own index after acceptance, drops a result when the session changed.
Tests: handler and client in-process, the corpus message test (O8 51, O7 stored inputs,
O2/O3/Step 5), the six existing suites migrated to the real worker logic.
2026-10-18 18:10:42 +02:00

205 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* The rescue copy (`JSON.stringify(report)`, the downloaded format) imported from Home:
* routed by content from the first KiB, read in the import worker by the core's copy
* restore (strict UTF-8, one BOM dropped; the real worker logic in-process on the shipped
* module, R4.3), opened as the original report; every refusal leaves the store and the
* tab's slots untouched.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} 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 { MAX_COPY_BYTES } from '@/core/worker/handler'
import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { buildGoldenReports, GOLDEN_REPORTS } from '../helpers/goldenReports'
import {
answeringEngineLoader,
useInProcessImportWorker,
type FakeWorker,
} from '../helpers/importWorker'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
let workers: FakeWorker[]
let restoreSpawn: () => void
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
useReportStore.getState().clearTrapped()
vi.stubGlobal('alert', vi.fn())
;({ workers, restore: restoreSpawn } = useInProcessImportWorker())
})
afterEach(() => {
restoreSpawn()
cleanup()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
async function pick(file: File) {
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())
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [file] },
})
}
const copyFile = (text: string, name = 'faunosteo-brouillon.json') =>
new File([text], name, { type: 'application/json' })
describe('opening a rescue copy', () => {
it.each(GOLDEN_REPORTS)(
'reopens the %s report equal to the original',
async (name) => {
const { reports } = buildGoldenReports(sheet)
await pick(copyFile(JSON.stringify(reports[name])))
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(reports[name])
expect(useReportStore.getState().archive).toBeNull()
},
)
it('routes by content: no .json name, no type, leading blanks and a BOM', async () => {
const report = minimalReport(sheet, { conclusion: 'sniffed' })
const text = ` \n${JSON.stringify(report)}`
await pick(new File([text], 'secours'))
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(report)
})
it('announces a copy rebased on another sheet revision', async () => {
const stale = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
})
await pick(copyFile(JSON.stringify(stale)))
await screen.findByTestId('editor-route')
expect(window.alert).toHaveBeenCalledWith(
fr['editor.draft_rebased']!.replace('{count}', '1'),
)
})
it('still sends a PDF down the PDF path', async () => {
await pick(
new File(['%PDF-1.7 not really'], 'bilan.pdf', {
type: 'application/pdf',
}),
)
await screen.findByText(fr['home.import.error_no_attachment']!)
expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull()
})
})
describe('refusing a file', () => {
const unreadable = JSON.stringify({ version: 7 })
const refused: [string, () => File][] = [
['invalid JSON', () => copyFile('{not json')],
['an unsupported version', () => copyFile(JSON.stringify({ version: 1 }))],
[
'a lone surrogate',
() =>
copyFile(
JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' })),
),
],
[
'invalid UTF-8',
() => new File([new Uint8Array([0x7b, 0xff, 0xfe, 0x7d])], 'copie.json'),
],
]
async function expectUntouched() {
await screen.findByText(fr['home.import.error_invalid_copy']!)
expect(useReportStore.getState().report).toBeNull()
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(unreadable)
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
expect(window.alert).not.toHaveBeenCalled()
expect(screen.queryByTestId('editor-route')).toBeNull()
}
it.each(refused)(
'%s: error line, nothing changed, nothing held',
async (_label, make) => {
sessionStorage.setItem(DRAFT_KEY, unreadable)
await pick(make())
await expectUntouched()
expect(workers).toHaveLength(1)
},
)
it('an over-cap file is refused before any full read', async () => {
sessionStorage.setItem(DRAFT_KEY, unreadable)
const file = copyFile('{"version":3}')
Object.defineProperty(file, 'size', { value: MAX_COPY_BYTES + 1 })
const read = vi.spyOn(file, 'arrayBuffer')
const stream = vi.spyOn(file, 'stream')
await pick(file)
await expectUntouched()
expect(read).not.toHaveBeenCalled()
expect(stream).not.toHaveBeenCalled()
expect(workers).toHaveLength(0)
})
it.each(['internal', 'rebase_failed'])(
'the core kind %s takes the engine message path, not the copy message',
async (kind) => {
// The worker's core answers the kind (the seam replaced; afterEach restores it).
const refusal = JSON.stringify({ ok: false, kind, detail: '' })
;({ workers, restore: restoreSpawn } = useInProcessImportWorker(
answeringEngineLoader(refusal),
))
await pick(copyFile(JSON.stringify(minimalReport(sheet))))
await screen.findByText(fr['home.import.error_core_unavailable']!)
// The worker answered: the line is the core's kind, not a worker failure.
expect(workers[0]!.posted.map((m) => m.type)).toEqual(['ready', 'result'])
expect(
screen.queryByText(fr['home.import.error_invalid_copy']!),
).toBeNull()
expect(useReportStore.getState().report).toBeNull()
},
)
})