Files
faunosteo/apps/app/tests/unit/routes.HomeRoute.rescueCopy.test.tsx
T
bchanot 9bd9acaf58 fix(app): rescue copy importable, trapping draft held, replace confirmed
The JSON rescue copy could not be restored in the app, a draft that traps
the engine left the tab on a reload screen and spent a recovery on every
read, and an unsaved or in-progress report could be lost by a reload
outside the editor or by New report / Import without warning.

Home import reads the copy (content-sniffed, 16 MiB cap, strict UTF-8)
through the core's draft.restore before any session change; a trapping
(draft, archive) pair is held in the resolution panel and only re-read
on Retry; ReplaceSessionDialog guards New report and Import; the
beforeunload guard is app-wide while unsaved. Supersedes BDR-055's
"never held" for `internal` only.
2026-10-17 12:58:57 +02:00

151 lines
5.6 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 by the core's draft restore, 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_ATTACHMENT_BYTES } from '@/pdf/import'
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 { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
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())
})
afterEach(() => {
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()
})
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_ATTACHMENT_BYTES + 1 })
const read = vi.spyOn(file, 'arrayBuffer')
await pick(file)
await expectUntouched()
expect(read).not.toHaveBeenCalled()
})
it.each(['internal', 'rebase_failed'])(
'the core kind %s takes the engine message path, not the copy message',
async (kind) => {
vi.spyOn(sheet.ops, 'restoreDraft').mockReturnValue({ ok: false, kind } as never)
await pick(copyFile(JSON.stringify(minimalReport(sheet))))
await screen.findByText(fr['home.import.error_core_unavailable']!)
expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
},
)
})