feat(app): catalogue cards say an integrity or load failure (board 30)

This commit is contained in:
bchanot committed 2026-11-17 00:14:14 +01:00
1 parent f061111e25
commit 6ad8d8347c
8 files changed
+564 -63

No files matched your search

+269 -2
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { PreviewState } from '@faunosteo/core-wasm/types'
@@ -16,11 +16,12 @@ import CatalogRoute from '@/app/routes/app/anatomy/CatalogRoute'
import SheetRoute from '@/app/routes/app/anatomy/SheetRoute'
import { coreRuntime } from '@/core/runtime'
import { CataloguePreview } from '@/catalogue/preview'
import { coreFailure, serverFailure } from '@/catalogue/failure'
import { cardFailure, coreFailure, serverFailure, type CatalogueFailure } from '@/catalogue/failure'
import { SheetFailure } from '@faunosteo/supabase'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
/**
* The catalogue screens (V1-2.5 slice I, boards 01 to 03) on a fake client and
@@ -139,6 +140,8 @@ describe('/app/anatomy', () => {
// The card whose version cannot be read keeps its name, version and link.
const dog = screen.getByRole('heading', { level: 2, name: 'Chien, rachis' }).closest('article')!
expect(within(dog).getByText('Version 1')).toBeInTheDocument()
// Its refused read is said in the card (F7).
expect(await within(dog).findByText(fr['access_denied.title'])).toBeInTheDocument()
})
it('searches by sheet name in either language and filters by species', async () => {
@@ -347,3 +350,267 @@ describe('failures', () => {
expect(preview.canvas('main')).toEqual({ ok: false, kind: 'core_unavailable' })
})
})
describe('catalogue cards (R4, board 30)', () => {
type Rpc = { rpc: (name: string, args?: unknown) => Promise<unknown> }
afterEach(() => vi.restoreAllMocks())
async function card(name: string): Promise<HTMLElement> {
return (await screen.findByRole('heading', { level: 2, name })).closest('article')!
}
/** The element carrying the notice's tone classes around a line of text. */
function noticeOf(text: HTMLElement): HTMLElement {
return text.closest('div.rounded-lg')!
}
function versionCalls(id: string): number {
return fake.rpcCalls.filter(
([n, a]) => n === 'get_sheet_version' && (a as { version_id: string }).version_id === id,
).length
}
/** Every `get_sheet_version` fails as a dropped request would. */
function failNetwork() {
fake.rpcResults.get_sheet_version = () => ({ error: { message: 'network' } })
}
/** Holds every later `get_sheet_version` answer until the returned release is called. */
function holdVersions(): () => void {
let release!: () => void
const gate = new Promise<void>((resolve) => (release = resolve))
const target = fake.client as unknown as Rpc
const original = target.rpc
target.rpc = async (name, args) => {
if (name === 'get_sheet_version') await gate
return original(name, args)
}
return release
}
async function failedCheval(text: string): Promise<HTMLElement> {
const cheval = await card('Cheval')
await within(cheval).findByText(text)
return cheval
}
it.each([
[
'a drawing whose bytes do not hash to its row',
() => {
const altered = bytes.slice()
altered[200] ^= 1
fake.storage.download.mockImplementation(async () => ({ data: new Blob([altered]), error: null }))
},
],
[
'a stored fingerprint the core does not recompute',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) }),
],
[
'a drawing Storage answers 400 for',
() =>
fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 400, name: 'StorageApiError' } })),
],
[
'a drawing Storage answers 404 for',
() =>
fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 404, name: 'StorageApiError' } })),
],
[
'an unreadable document',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { document: { schema_version: 2 } }) }),
],
])('says the integrity failure of %s, without retry or live region', async (_case, arrange) => {
arrange()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.card.integrity_failed'])
expect(noticeOf(within(cheval).getByText(fr['catalogue.card.integrity_failed'])).className).toMatch(
/color-danger/,
)
expect(within(cheval).queryByRole('alert')).toBeNull()
expect(within(cheval).queryByRole('status')).toBeNull()
expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toHaveAttribute('href', `/app/anatomy/${SHEET}`)
expect(within(cheval).getByText(fr['catalogue.status.published'])).toBeInTheDocument()
expect(cheval.querySelector('img')).toBeNull()
})
it('says a network failure, retries that card and moves the focus to « Consulter »', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
expect(noticeOf(within(cheval).getByText(fr['catalogue.failure.network'])).className).toMatch(
/severity-moderate/,
)
const retries = within(cheval).getAllByRole('button', { name: fr['common.retry'] })
expect(retries).toHaveLength(1)
serveVersions({ [V3]: versionAnswer(V3, 'published') })
await userEvent.click(retries[0])
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(within(cheval).queryByText(fr['catalogue.failure.network'])).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toHaveFocus()
})
it('keeps « Réessayer » focused during an attempt that fails again, then says the line politely', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const polite = cheval.querySelector('[aria-live="polite"]')!
expect(polite).toHaveTextContent('')
const release = holdVersions()
const retry = within(cheval).getByRole('button', { name: fr['common.retry'] })
await userEvent.click(retry)
expect(retry).toHaveFocus()
expect(retry).toHaveAttribute('aria-disabled', 'true')
expect(cheval).toHaveAttribute('aria-busy', 'true')
expect(polite).toHaveTextContent('')
await act(async () => release())
await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.failure.network']))
expect(retry).toBeInTheDocument()
expect(retry).toHaveFocus()
expect(retry).not.toHaveAttribute('aria-disabled', 'true')
expect(cheval).not.toHaveAttribute('aria-busy', 'true')
})
it('reloads only the card whose « Réessayer » was pressed, with no burst of announcements', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const dog = await card('Chien, rachis')
await within(dog).findByText(fr['catalogue.failure.network'])
expect(screen.queryAllByRole('alert')).toHaveLength(0)
expect(within(cheval).queryByRole('status')).toBeNull()
expect(within(dog).queryByRole('status')).toBeNull()
const before = versionCalls(DOG)
const chevalBefore = versionCalls(V3)
await userEvent.click(within(cheval).getByRole('button', { name: fr['common.retry'] }))
const polite = cheval.querySelector('[aria-live="polite"]')!
await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.failure.network']))
expect(versionCalls(V3)).toBe(chevalBefore + 1)
expect(versionCalls(DOG)).toBe(before)
})
it('ignores a second click while the attempt runs', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const release = holdVersions()
const before = versionCalls(V3)
const retry = within(cheval).getByRole('button', { name: fr['common.retry'] })
await userEvent.click(retry)
await userEvent.click(retry)
await act(async () => release())
const polite = cheval.querySelector('[aria-live="polite"]')!
await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.failure.network']))
expect(versionCalls(V3)).toBe(before + 1)
})
it('drops a retry still running when the card leaves: no update, URLs and previews balanced', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const created = vi.spyOn(URL, 'createObjectURL')
const revoked = vi.spyOn(URL, 'revokeObjectURL')
const built = vi.spyOn(CataloguePreview.prototype, 'state')
const freed = vi.spyOn(CataloguePreview.prototype, 'free')
const errors = vi.spyOn(console, 'error')
const release = holdVersions()
serveVersions({ [V3]: versionAnswer(V3, 'published') })
await userEvent.click(within(cheval).getByRole('button', { name: fr['common.retry'] }))
await userEvent.type(screen.getByRole('searchbox', { name: fr['catalogue.search'] }), 'dog')
expect(screen.queryByRole('heading', { level: 2, name: 'Cheval' })).toBeNull()
await act(async () => release())
await waitFor(() => expect(freed).toHaveBeenCalled())
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)))
expect(built.mock.calls.length).toBeGreaterThan(0)
expect(freed).toHaveBeenCalledTimes(built.mock.calls.length)
expect(created).toHaveBeenCalledTimes(revoked.mock.calls.length)
expect(errors).not.toHaveBeenCalled()
})
it('says the core failed to load and restarts it on « Réessayer »', async () => {
vi.spyOn(coreRuntime(), 'ready').mockResolvedValueOnce(false)
const restart = vi.spyOn(coreRuntime(), 'retry')
mount('/app/anatomy')
const cheval = await failedCheval(fr['sheet.core_unavailable'])
await userEvent.click(within(cheval).getByRole('button', { name: fr['sheet.core_retry'] }))
expect(restart).toHaveBeenCalledTimes(1)
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(within(cheval).queryByText(fr['sheet.core_unavailable'])).toBeNull()
})
it('says an expired session with « Réessayer »', async () => {
fake.rpcResults.get_sheet_version = () => ({ error: { message: 'session_expired' } })
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.session_expired'])
expect(within(cheval).getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument()
})
it('says a refused version read with « Réessayer »', async () => {
mount('/app/anatomy')
const dog = await card('Chien, rachis')
expect(await within(dog).findByText(fr['access_denied.title'])).toBeInTheDocument()
expect(within(dog).getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument()
})
it('says a version over the size limits apart from integrity, without retry (D1)', async () => {
vi.spyOn(CataloguePreview.prototype, 'state').mockReturnValueOnce({ ok: false, kind: 'caps' })
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.caps'])
expect(noticeOf(within(cheval).getByText(fr['catalogue.failure.caps'])).className).toMatch(/color-danger/)
expect(within(cheval).queryByText(fr['catalogue.card.integrity_failed'])).toBeNull()
expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toBeInTheDocument()
})
it('says the integrity failure in English', async () => {
useLocaleStore.setState({ locale: 'en' })
serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) })
mount('/app/anatomy')
const horse = await card('Horse')
expect(await within(horse).findByText(en['catalogue.card.integrity_failed'])).toBeInTheDocument()
})
it('classes every failure kind', () => {
const expected: Record<CatalogueFailure, [integrity: boolean, refused: boolean]> = {
fingerprint_mismatch: [true, true],
drawing_hash_mismatch: [true, true],
drawing_missing: [true, true],
invalid_document: [true, true],
caps: [false, true],
denied: [false, false],
network: [false, false],
session_expired: [false, false],
rate_limited: [false, false],
unavailable: [false, false],
core_unavailable: [false, false],
}
for (const [kind, [integrity, refused]] of Object.entries(expected)) {
const failure = kind as CatalogueFailure
expect(cardFailure(failure, false)).toEqual({ integrity, refused, retry: !refused })
const stoppedRetry = !refused && failure !== 'core_unavailable'
expect(cardFailure(failure, true)).toEqual({ integrity, refused, retry: stoppedRetry })
}
})
it('says a main view the core refuses to compose, with the counts (D2)', async () => {
vi.spyOn(CataloguePreview.prototype, 'canvas').mockReturnValueOnce({ ok: false, kind: 'view_refused' })
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.view'])
const line = noticeOf(within(cheval).getByText(fr['catalogue.failure.view']))
expect(line.className).toMatch(/surface-strong/)
expect(within(cheval).queryByRole('status')).toBeNull()
expect(within(cheval).getByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull()
expect(cheval.querySelector('img')).toBeNull()
})
it('says the engine failed while composing the main view, with its retry (D2)', async () => {
vi.spyOn(CataloguePreview.prototype, 'canvas').mockReturnValueOnce({ ok: false, kind: 'core_unavailable' })
mount('/app/anatomy')
const cheval = await failedCheval(fr['sheet.core_unavailable'])
expect(within(cheval).getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument()
})
})