341 lines
12 KiB
TypeScript
341 lines
12 KiB
TypeScript
/** Lot G: the upload flow of a drawing (check, clean, register, upload, confirm, attach). */
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import {
|
|
cleanup,
|
|
render,
|
|
screen,
|
|
waitFor,
|
|
within,
|
|
} from '@testing-library/react'
|
|
import userEvent from '@testing-library/user-event'
|
|
import { SheetFailure } from '@faunosteo/supabase'
|
|
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
|
|
import ViewsTab from '@/components/editor/tabs/ViewsTab'
|
|
import { cleanSvg } from '@/editor/core/cleaning'
|
|
import { createHash } from 'node:crypto'
|
|
import { getDict } from '@/i18n'
|
|
import { frameRefusalMessage } from '@/editor/frameRefusal'
|
|
import { uploadErrorMessage } from '@/editor/uploadMessages'
|
|
import { MAX_DRAWING_BYTES, attachToView } from '@/editor/drawingUpload'
|
|
import { useLocaleStore } from '@/state/localeStore'
|
|
import { ASSET } from '../helpers/editorFixtures'
|
|
import { openReady, resetStore, sb, store } from '../helpers/editorHarness'
|
|
|
|
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
|
|
vi.mock('@faunosteo/supabase', async (orig) => ({
|
|
...(await orig<typeof import('@faunosteo/supabase')>()),
|
|
getSheetVersion: vi.fn(),
|
|
downloadSheetDrawing: vi.fn(),
|
|
saveSheetDraft: vi.fn(),
|
|
getOfficialSheetAdmin: vi.fn(),
|
|
submitSheetReview: vi.fn(),
|
|
registerSheetAsset: vi.fn(),
|
|
listSheetAssets: vi.fn(),
|
|
uploadSheetDrawing: vi.fn(),
|
|
confirmSheetAssetUpload: vi.fn(),
|
|
}))
|
|
|
|
const props = { readOnly: false, onSelectTab: vi.fn(), reloadSheet: vi.fn() }
|
|
const NEW_ASSET = '22222222-2222-4222-8222-222222222222'
|
|
const doc = (): AnatomicalSheetDocument =>
|
|
JSON.parse(store.getState().documentText)
|
|
const mainAsset = () => doc().views[0].svg_asset_id
|
|
|
|
const svg = (viewBox: string, inner = '<rect width="4" height="4"/>') =>
|
|
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">${inner}</svg>`
|
|
|
|
/** The stored form the core would keep for a file, as the server would serve it. */
|
|
function storedOf(text: string) {
|
|
const cleaned = cleanSvg(new TextEncoder().encode(text))
|
|
if (!cleaned.ok || !cleaned.value.stored || !cleaned.value.sha256)
|
|
throw new Error('bad')
|
|
return {
|
|
...cleaned.value,
|
|
bytes: new TextEncoder().encode(cleaned.value.stored),
|
|
}
|
|
}
|
|
|
|
function serverGets(text: string, uploadedAt: string | null = null) {
|
|
const stored = storedOf(text)
|
|
sb.registerSheetAsset.mockResolvedValue(NEW_ASSET)
|
|
sb.listSheetAssets.mockResolvedValue([
|
|
{
|
|
id: NEW_ASSET,
|
|
sha256: stored.sha256!,
|
|
byte_size: stored.byte_size!,
|
|
uploaded_at: uploadedAt,
|
|
},
|
|
])
|
|
sb.uploadSheetDrawing.mockResolvedValue('uploaded')
|
|
sb.confirmSheetAssetUpload.mockResolvedValue(NEW_ASSET)
|
|
const fresh = (hash: string) =>
|
|
hash === stored.sha256 ? stored.bytes : undefined
|
|
sb.downloadSheetDrawing.mockImplementation(
|
|
async (_c, hash) => fresh(hash) ?? (await baseBytes()),
|
|
)
|
|
return stored
|
|
}
|
|
|
|
async function baseBytes() {
|
|
const { svgBytes } = await import('../helpers/editorFixtures')
|
|
return svgBytes().bytes
|
|
}
|
|
|
|
async function pick(text: string, name = 'dessin.svg') {
|
|
const user = userEvent.setup()
|
|
const input = screen.getByTestId('view-view-main-file') as HTMLInputElement
|
|
await user.upload(input, new File([text], name, { type: 'image/svg+xml' }))
|
|
return user
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
useLocaleStore.setState({ locale: 'fr' })
|
|
await openReady()
|
|
render(<ViewsTab {...props} />)
|
|
})
|
|
afterEach(() => {
|
|
cleanup()
|
|
resetStore()
|
|
})
|
|
|
|
describe('drawing upload flow', () => {
|
|
it('a clean file goes register, upload, confirm, hold, attach with no dialog', async () => {
|
|
const stored = serverGets(svg('0 0 200 100'))
|
|
await pick(svg('0 0 200 100'))
|
|
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
|
|
expect(screen.queryByRole('dialog')).toBeNull()
|
|
expect(sb.registerSheetAsset).toHaveBeenCalledWith(
|
|
{},
|
|
{
|
|
sheet_id: 'sheet-1',
|
|
sha256: stored.sha256,
|
|
byte_size: stored.byte_size,
|
|
file_name: 'dessin.svg',
|
|
},
|
|
)
|
|
expect(sb.uploadSheetDrawing).toHaveBeenCalledWith(
|
|
{},
|
|
stored.sha256,
|
|
stored.bytes,
|
|
)
|
|
expect(sb.confirmSheetAssetUpload).toHaveBeenCalledWith({}, NEW_ASSET)
|
|
expect(store.getState().drawings.map((d) => d.asset_id)).toContain(
|
|
NEW_ASSET,
|
|
)
|
|
expect(
|
|
await screen.findByText("L'illustration est ajoutée à la vue."),
|
|
).toBeTruthy()
|
|
})
|
|
|
|
it('a download that ends after another draft opened holds nothing in the new session', async () => {
|
|
const stored = serverGets(svg('0 0 200 100'))
|
|
let release: (bytes: Uint8Array) => void = () => {}
|
|
const held = new Promise<Uint8Array>((resolve) => (release = resolve))
|
|
sb.downloadSheetDrawing.mockImplementation(async (_c, hash) =>
|
|
hash === stored.sha256 ? held : await baseBytes(),
|
|
)
|
|
await pick(svg('0 0 200 100'))
|
|
await waitFor(() =>
|
|
expect(sb.downloadSheetDrawing).toHaveBeenCalledWith({}, stored.sha256),
|
|
)
|
|
store.getState().close()
|
|
await openReady()
|
|
const session = store.getState().session
|
|
release(stored.bytes)
|
|
await new Promise((done) => setTimeout(done, 50))
|
|
expect(store.getState().session).toBe(session)
|
|
expect(store.getState().drawings.map((d) => d.asset_id)).not.toContain(
|
|
NEW_ASSET,
|
|
)
|
|
})
|
|
|
|
it('a cleanable file shows the dialog with the core-composed drawing, then uploads on accept', async () => {
|
|
const dirty = svg(
|
|
'0 0 200 100',
|
|
'<style>.a{fill:red}</style><rect class="a" width="4" height="4"/>',
|
|
)
|
|
serverGets(dirty)
|
|
await pick(dirty)
|
|
const dialog = await screen.findByRole('dialog')
|
|
expect(sb.registerSheetAsset).not.toHaveBeenCalled()
|
|
expect(
|
|
within(dialog).getByText(/L'élément <style> a été retiré/),
|
|
).toBeTruthy()
|
|
expect(within(dialog).getByText('style')).toBeTruthy()
|
|
expect(
|
|
within(dialog).getByTestId('cleaning-preview').querySelector('svg'),
|
|
).not.toBeNull()
|
|
await userEvent.setup().click(
|
|
within(dialog).getByRole('button', {
|
|
name: 'Nettoyer et utiliser cette version',
|
|
}),
|
|
)
|
|
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
|
|
expect(sb.uploadSheetDrawing).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('cancelling the cleaning dialog sends nothing', async () => {
|
|
const dirty = svg(
|
|
'0 0 200 100',
|
|
'<style>.a{fill:red}</style><rect class="a" width="4" height="4"/>',
|
|
)
|
|
serverGets(dirty)
|
|
const user = await pick(dirty)
|
|
const dialog = await screen.findByRole('dialog')
|
|
await user.click(within(dialog).getByRole('button', { name: 'Annuler' }))
|
|
expect(sb.registerSheetAsset).not.toHaveBeenCalled()
|
|
expect(mainAsset()).toBe(ASSET)
|
|
})
|
|
|
|
it('a rejected file shows its reason and nothing else happens', async () => {
|
|
await pick(
|
|
'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
|
|
)
|
|
expect(await screen.findByText(/contenu actif ou externe/)).toBeTruthy()
|
|
await pick('pas un svg')
|
|
expect(
|
|
await screen.findByText(/n'est pas un dessin SVG utilisable/),
|
|
).toBeTruthy()
|
|
expect(sb.registerSheetAsset).not.toHaveBeenCalled()
|
|
expect(screen.queryByRole('dialog')).toBeNull()
|
|
})
|
|
|
|
it('a file over 2 MiB is refused before it is read', async () => {
|
|
const user = userEvent.setup()
|
|
const big = new File([new Uint8Array(MAX_DRAWING_BYTES + 1)], 'big.svg', {
|
|
type: 'image/svg+xml',
|
|
})
|
|
await user.upload(
|
|
screen.getByTestId('view-view-main-file') as HTMLInputElement,
|
|
big,
|
|
)
|
|
expect(await screen.findByText('Ce fichier dépasse 2 Mio.')).toBeTruthy()
|
|
expect(sb.registerSheetAsset).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('an object already present is confirmed without a second upload', async () => {
|
|
serverGets(svg('0 0 200 100'))
|
|
sb.uploadSheetDrawing.mockResolvedValue('present')
|
|
await pick(svg('0 0 200 100'))
|
|
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
|
|
expect(sb.confirmSheetAssetUpload).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('a confirmed row is neither uploaded nor confirmed again', async () => {
|
|
serverGets(svg('0 0 200 100'), '2026-11-04T10:00:00Z')
|
|
await pick(svg('0 0 200 100'))
|
|
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
|
|
expect(sb.uploadSheetDrawing).not.toHaveBeenCalled()
|
|
expect(sb.confirmSheetAssetUpload).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('a policy refusal then a confirm that finds the object goes on', async () => {
|
|
serverGets(svg('0 0 200 100'))
|
|
sb.uploadSheetDrawing.mockRejectedValue(
|
|
new SheetFailure('upload.pending_other'),
|
|
)
|
|
await pick(svg('0 0 200 100'))
|
|
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
|
|
expect(sb.confirmSheetAssetUpload).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('a policy refusal then upload_missing is upload.pending_other, view unchanged', async () => {
|
|
serverGets(svg('0 0 200 100'))
|
|
sb.uploadSheetDrawing.mockRejectedValue(
|
|
new SheetFailure('upload.pending_other'),
|
|
)
|
|
sb.confirmSheetAssetUpload.mockRejectedValue(
|
|
new SheetFailure('upload_missing'),
|
|
)
|
|
await pick(svg('0 0 200 100'))
|
|
expect(
|
|
await screen.findByText(/en cours d'envoi par un autre compte/),
|
|
).toBeTruthy()
|
|
expect(mainAsset()).toBe(ASSET)
|
|
expect(store.getState().drawings.map((d) => d.asset_id)).not.toContain(
|
|
NEW_ASSET,
|
|
)
|
|
})
|
|
|
|
it('server kinds are phrased, size_mismatch with its own wording', async () => {
|
|
serverGets(svg('0 0 200 100'))
|
|
sb.confirmSheetAssetUpload.mockRejectedValue(
|
|
new SheetFailure('size_mismatch'),
|
|
)
|
|
await pick(svg('0 0 200 100'))
|
|
expect(await screen.findByText(/diffère de celle enregistrée/)).toBeTruthy()
|
|
expect(mainAsset()).toBe(ASSET)
|
|
})
|
|
|
|
it('a downloaded object that does not match its hash is an object conflict', async () => {
|
|
serverGets(svg('0 0 200 100'))
|
|
sb.downloadSheetDrawing.mockResolvedValue(new TextEncoder().encode('autre'))
|
|
await pick(svg('0 0 200 100'))
|
|
expect(
|
|
await screen.findByText(
|
|
/ne correspond pas à son empreinte SHA-256 enregistrée/,
|
|
),
|
|
).toBeTruthy()
|
|
expect(mainAsset()).toBe(ASSET)
|
|
})
|
|
|
|
it('a held drawing outside the stored form is refused at attach as svg_not_canonical', async () => {
|
|
const bytes = new TextEncoder().encode(
|
|
svg('0 0 200 100', ' <rect width="4" height="4"/>'),
|
|
)
|
|
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
expect(
|
|
store.getState().addDrawing({ assetId: NEW_ASSET, sha256, bytes }).ok,
|
|
).toBe(true)
|
|
expect(attachToView('view-main', NEW_ASSET)).toEqual({
|
|
ok: false,
|
|
error: { code: 'svg_not_canonical' },
|
|
})
|
|
expect(mainAsset()).toBe(ASSET)
|
|
})
|
|
|
|
it('phrases svg_not_canonical and the new reader reasons', () => {
|
|
const t = (key: string) => getDict('fr')[key as never] as string
|
|
const context = { doc: null, locale: 'fr' as const }
|
|
expect(
|
|
uploadErrorMessage(t, { code: 'svg_not_canonical' }, context),
|
|
).toMatch(/pas sous la forme enregistrée/)
|
|
const reason = (value: string) =>
|
|
uploadErrorMessage(t, { code: 'svg_rejected', reason: value }, context)
|
|
expect(reason('processing_instruction')).toMatch(
|
|
/instruction de traitement/,
|
|
)
|
|
expect(reason('removed <script>')).toMatch(/éléments à retirer/)
|
|
})
|
|
|
|
it('a refused frame change leaves the drawing uploaded and held, the view unchanged', async () => {
|
|
serverGets(svg('0 0 20 20'))
|
|
await pick(svg('0 0 20 20'))
|
|
expect(await screen.findByText(/géométrie de : N\./)).toBeTruthy()
|
|
expect(screen.getByText(/L'illustration reste téléversée/)).toBeTruthy()
|
|
expect(mainAsset()).toBe(ASSET)
|
|
expect(store.getState().drawings.map((d) => d.asset_id)).toContain(
|
|
NEW_ASSET,
|
|
)
|
|
})
|
|
})
|
|
|
|
describe('frame refusal for a rejected drawing', () => {
|
|
it('phrases not_canonical and a reader reason as closed messages', () => {
|
|
const t = (key: string) => getDict('fr')[key as never] as string
|
|
const refusal = (drawingDetail: string) => ({
|
|
reason: 'drawing_rejected' as const,
|
|
annotationIds: [],
|
|
issues: [],
|
|
viewIds: [],
|
|
drawingDetail,
|
|
})
|
|
expect(
|
|
frameRefusalMessage(t, refusal('not_canonical'), null, 'fr'),
|
|
).toMatch(/pas sous la forme enregistrée/)
|
|
expect(frameRefusalMessage(t, refusal('doctype'), null, 'fr')).toMatch(
|
|
/DOCTYPE/,
|
|
)
|
|
})
|
|
})
|