0279953 chose the stopped message from CoreRuntime.stopped alone: it
promised the report was kept even when the tab's storage refused the
draft (export, the banner's advice, needs the core), four surfaces still
offered a retry that could not work, and a failed recovery below the cap
was a dead end since nothing called retry().
The runtime restarts a failed recovery on the next call (compiled module
reused, cap still counts traps) and notifies status listeners. One
CoreStoppedNotice on the editor, Home, New report and the full-page
notice: reload when saved, else core.stopped_unsaved with a core-free
copy download (also on the storage-full banner) and a beforeunload
guard. Export, import and new report say the stopped message; a core
failure reading an unread draft is FAILED, not held. ESLint census of
the failure keys; core.stopped says "plusieurs erreurs".
243 lines
8.0 KiB
TypeScript
243 lines
8.0 KiB
TypeScript
/**
|
|
* Step 6 Phase 0 characterisation of the import flow on the home route, with
|
|
* the two import steps mocked (R2: `readAttachment`, the engine's byte scan,
|
|
* then `importAttachment`, the core's layered read and rebase on the loaded
|
|
* sheet): the migration alert (degraded headline, then the count), the three
|
|
* ImportError kinds plus the generic error mapped to the FR messages, and the
|
|
* navigation to /editor on success; `lone_surrogate` (L1) has its own message.
|
|
*/
|
|
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 type { ArchiveImport } from '@faunosteo/core-wasm/types'
|
|
import HomeRoute from '@/app/routes/HomeRoute'
|
|
import {
|
|
ImportError,
|
|
importAttachment,
|
|
MAX_PDF_BYTES,
|
|
readAttachment,
|
|
} 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')>()),
|
|
readAttachment: vi.fn(),
|
|
importAttachment: vi.fn(),
|
|
}))
|
|
const readMock = vi.mocked(readAttachment)
|
|
const importMock = vi.mocked(importAttachment)
|
|
const ATTACHMENT = { version: 3 }
|
|
|
|
let sheet: SheetIndex
|
|
|
|
beforeAll(async () => {
|
|
sheet = await loadTestSheet()
|
|
})
|
|
beforeEach(() => {
|
|
useLocaleStore.setState({ locale: 'fr' })
|
|
useReportStore.setState({
|
|
report: null,
|
|
archive: null,
|
|
activeObservationIndex: 0,
|
|
})
|
|
vi.stubGlobal('alert', vi.fn())
|
|
readMock.mockReset()
|
|
readMock.mockResolvedValue(ATTACHMENT)
|
|
importMock.mockReset()
|
|
})
|
|
afterEach(() => {
|
|
cleanup()
|
|
vi.unstubAllGlobals()
|
|
})
|
|
|
|
/** What the import resolves with: the read (bare report, no archive) and no rebase. */
|
|
function outcome(patch: {
|
|
migrated: boolean
|
|
unresolvedZones?: number
|
|
unresolvedFindings?: number
|
|
}): ArchiveImport {
|
|
const report = minimalReport(sheet)
|
|
return {
|
|
read: {
|
|
report,
|
|
origin: patch.migrated ? 'v2' : 'bare_v3',
|
|
archive: null,
|
|
unresolvedZones: 0,
|
|
unresolvedFindings: 0,
|
|
...patch,
|
|
},
|
|
rebase: {
|
|
report,
|
|
unresolvedZones: 0,
|
|
unresolvedFindings: 0,
|
|
rebased: false,
|
|
},
|
|
}
|
|
}
|
|
|
|
/** A 4-byte "%PDF" file; the import is mocked, the bytes only travel. */
|
|
function pdfFile(): File {
|
|
return new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', {
|
|
type: 'application/pdf',
|
|
})
|
|
}
|
|
|
|
async function mountAndPickPdf(file: File = pdfFile()): 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"]')!
|
|
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 to the scan and the attachment to the loaded sheet, hydrates, navigates to /editor', async () => {
|
|
importMock.mockReturnValue(outcome({ migrated: false }))
|
|
await mountAndPickPdf()
|
|
await screen.findByTestId('editor-route')
|
|
expect(readMock).toHaveBeenCalledTimes(1)
|
|
expect(readMock.mock.calls[0]![0]).toBeInstanceOf(Uint8Array)
|
|
expect(importMock).toHaveBeenCalledTimes(1)
|
|
const [attachment, index] = importMock.mock.calls[0]!
|
|
expect(attachment).toBe(ATTACHMENT)
|
|
expect(index).toBe(sheet)
|
|
expect(useReportStore.getState().report?.id).toBe('r1')
|
|
expect(alertMock()).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('alerts "degraded" then the unresolved count (zones + findings) after a lossy migration', async () => {
|
|
importMock.mockReturnValue(
|
|
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
|
|
const [headline, ...lines] = message.split('\n\n')
|
|
expect(headline).toBe(fr['home.import.degraded'])
|
|
expect(lines).toEqual([fr['home.import.migrated']!.replace('{count}', '2')])
|
|
})
|
|
|
|
it('stays silent on a migration that lost nothing', async () => {
|
|
importMock.mockReturnValue(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']!,
|
|
],
|
|
[
|
|
'lone_surrogate → malformed text message, file untouched',
|
|
new ImportError('lone_surrogate'),
|
|
fr['home.import.error_lone_surrogate']!,
|
|
],
|
|
[
|
|
'generic Error → generic message',
|
|
new Error('disk on fire'),
|
|
fr['home.import.error_generic']!,
|
|
],
|
|
]
|
|
|
|
it.each(cases)('%s', async (_label, error, expected) => {
|
|
importMock.mockImplementation(() => {
|
|
throw 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()
|
|
})
|
|
})
|
|
|
|
describe('HomeRoute import: size gate', () => {
|
|
it('refuses a file over MAX_PDF_BYTES before reading it: unreadable PDF message', async () => {
|
|
const file = pdfFile()
|
|
Object.defineProperty(file, 'size', { value: MAX_PDF_BYTES + 1 })
|
|
const read = vi.spyOn(file, 'arrayBuffer')
|
|
await mountAndPickPdf(file)
|
|
await waitFor(() => expect(errorText()).not.toBeNull())
|
|
expect(errorText()!.textContent).toBe(fr['home.import.error_invalid_pdf'])
|
|
expect(read).not.toHaveBeenCalled()
|
|
expect(readMock).not.toHaveBeenCalled()
|
|
expect(importMock).not.toHaveBeenCalled()
|
|
expect(screen.queryByTestId('editor-route')).toBeNull()
|
|
expect(useReportStore.getState().report).toBeNull()
|
|
})
|
|
})
|
|
|
|
describe('HomeRoute import: a core failure reading the tab draft', () => {
|
|
it('shows the engine error line, not the held-session alert', async () => {
|
|
importMock.mockReturnValue(outcome({ migrated: false }))
|
|
const real = useReportStore.getState().hydrateImport
|
|
useReportStore.setState({ hydrateImport: () => ({ ok: false }) })
|
|
try {
|
|
await mountAndPickPdf()
|
|
await screen.findByText(fr['home.import.error_core_unavailable']!)
|
|
expect(alertMock()).not.toHaveBeenCalled()
|
|
expect(screen.queryByTestId('editor-route')).toBeNull()
|
|
} finally {
|
|
useReportStore.setState({ hydrateImport: real })
|
|
}
|
|
})
|
|
|
|
it('still alerts and opens the editor for a held session text', async () => {
|
|
importMock.mockReturnValue(outcome({ migrated: false }))
|
|
const real = useReportStore.getState().hydrateImport
|
|
useReportStore.setState({ hydrateImport: () => ({ ok: false, reason: 'held' }) })
|
|
try {
|
|
await mountAndPickPdf()
|
|
await screen.findByTestId('editor-route')
|
|
expect(alertMock()).toHaveBeenCalledWith(fr['session.held_blocked'])
|
|
} finally {
|
|
useReportStore.setState({ hydrateImport: real })
|
|
}
|
|
})
|
|
})
|