test(editor): V1-2.6 browser journeys on the sandbox, touch drag and findings fixes

This commit is contained in:
bchanot committed 2026-11-04 15:27:35 +01:00
1 parent 7bbd096a16
commit 5097fd7484
18 files changed
+3010 -8

No files matched your search

+1 -1
View File
@@ -47,7 +47,7 @@ export async function seedGrant(
}
/** A password session of the account on GoTrue: always aal1. */
async function passwordToken(account: SandboxAccount): Promise<string> {
export async function passwordToken(account: SandboxAccount): Promise<string> {
const response = await fetch(`${stack.authUrl}/token?grant_type=password`, {
method: 'POST',
headers: { apikey: stack.anonKey, 'Content-Type': 'application/json' },
+2 -1
View File
@@ -59,7 +59,8 @@ async function loadCore(): Promise<CoreRuntime> {
}
let runtime: Promise<CoreRuntime> | null = null
const core = () => (runtime ??= loadCore())
/** Loaded once per worker process; also used by the editor fixtures. */
export const core = () => (runtime ??= loadCore())
async function seedFiles() {
const [drawing, document] = await Promise.all([
+498
View File
@@ -0,0 +1,498 @@
/**
* V1-2.6 setup of the editor suites (Lot K): editor accounts with a verified factor and an
* aal2 token of their own, draft sheets written the way the sandbox suites do (RPC with
* that token, the drawing through the Storage policy), and the page-side helpers the
* editor specs share (opening the draft, tabs, drawing coordinates, save). What a test
* proves goes through the page; fixtures only prepare what a person did earlier.
*/
import { createHash, randomUUID } from 'node:crypto'
import type { Dict } from '@/i18n/types'
import type { Browser, BrowserContext, Page } from '@playwright/test'
import {
enrolTotp,
verifyTotp,
} from '../../../../packages/supabase/tests/sandbox/mfa'
import {
rpc,
sql,
stack,
} from '../../../../packages/supabase/tests/sandbox/stack'
import { assignRole, passwordToken, seedGrant, stepUpAdmin } from './admin'
import type { GrantKind } from './admin'
import { expect } from './browser'
import { core } from './catalogue'
import { parseOutcome } from '@faunosteo/core-wasm'
import {
createAccount,
FAKE_SUPABASE_ORIGIN,
routeToSandbox,
type SandboxAccount,
} from './sandbox'
import { signIn } from './shell'
export interface Actor {
account: SandboxAccount
secret: string
/** An aal2 access token for the sandbox REST and Storage calls of fixtures. */
aal2: string
}
/** An account with its role and grants and one verified factor; the secret serves the page. */
export async function makeActor(
locale: 'fr' | 'en',
role: 'owner' | 'admin' | null,
grants: GrantKind[],
): Promise<Actor> {
const account = await createAccount(locale, false)
if (role) await assignRole(account, role)
for (const kind of grants) await seedGrant(account, kind)
const token = await passwordToken(account)
const enrolment = await enrolTotp(token, 'Téléphone')
if (!enrolment.factor) throw new Error('editor fixture: enrol refused')
const verified = await verifyTotp(token, enrolment.factor)
const aal2 = verified.body.access_token
if (typeof aal2 !== 'string') throw new Error('editor fixture: no aal2')
return { account, secret: enrolment.factor.secret, aal2 }
}
export const editorActor = (locale: 'fr' | 'en') =>
makeActor(locale, 'admin', ['sheet_editor'])
/** An admin whose editor grant ends soon (the grant is written by hand, not seeded). */
export async function expiringEditor(
locale: 'fr' | 'en',
seconds: number,
): Promise<Actor> {
const actor = await makeActor(locale, 'admin', [])
await seedExpiringGrant(actor.account, 'sheet_editor', seconds)
return actor
}
/** The drawing of the fixtures: a 1000 × 800 box with a body shape. */
export const DRAWING_SVG =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 800">' +
'<rect x="50" y="50" width="900" height="700" fill="#f4efe6" stroke="#444"/>' +
'<circle cx="500" cy="400" r="200" fill="#d8b98a"/></svg>'
const text = (fr: string) => ({ fr, en: fr })
export interface DraftSeed {
sheetId: string
draftId: string
names: { fr: string; en: string }
assetId: string | null
/** The revision the server holds once seeded (0 for a blank draft). */
revision: number
}
export interface SeedOptions {
/** SVG bytes of the main view's drawing; null leaves the blank starting document. */
drawing?: string | null
species?: string
/** Adjusts the document before it is saved (categories, detail views, findings). */
shape?: (document: Record<string, unknown>) => void
}
const sha256 = (bytes: Buffer) =>
createHash('sha256').update(bytes).digest('hex')
function blankDocument(species: string, name: string) {
return {
schema_version: 2,
species_id: species,
name: text(name),
description: {},
scope_disclaimer: {},
attribution: { authors: [], license: null, notes: null },
vertebral_config: { regions: [] },
references: [],
categories: [],
views: [
{
id: 'main',
kind: 'main',
name: { fr: 'Vue principale', en: 'Main view' },
svg_asset_id: null as string | null,
view_box: null,
},
],
annotations: [],
finding_zones: [],
}
}
function succeeded(result: { status: number; text: string }, what: string) {
if (result.status !== 200)
throw new Error(`editor fixture ${what}: HTTP ${result.status}`)
return result
}
/** The drawing as the core stores it: the form the page uploads after its own cleaning. */
async function storedForm(svg: string): Promise<string> {
const loaded = await core()
const outcome = loaded.invoke<{ stored: string | null }>((glue) =>
parseOutcome<{ stored: string | null }>(
glue.clean_svg(new TextEncoder().encode(svg)),
),
)
if (!outcome.ok || !outcome.value.stored)
throw new Error('editor fixture: the core refused the drawing')
return outcome.value.stored
}
async function attachDrawing(
actor: Actor,
sheetId: string,
svg: string,
): Promise<string> {
const bytes = Buffer.from(await storedForm(svg))
const registered = succeeded(
await rpc(
'register_sheet_asset',
{
sheet_id: sheetId,
sha256: sha256(bytes),
byte_size: bytes.length,
file_name: 'fixture.svg',
},
actor.aal2,
),
'register',
)
const response = await fetch(
`${stack.storageUrl}/object/anatomical-sheet-assets/${sha256(bytes)}.svg`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${actor.aal2}`,
'Content-Type': 'image/svg+xml',
},
body: new Uint8Array(bytes),
},
)
await response.arrayBuffer()
if (response.status !== 200 && response.status !== 400)
throw new Error(`editor fixture upload: HTTP ${response.status}`)
const assetId = JSON.parse(registered.text) as string
succeeded(
await rpc('confirm_sheet_asset_upload', { asset_id: assetId }, actor.aal2),
'confirm',
)
return assetId
}
/** A non-equine draft sheet by `actor`, its drawing and content saved as revision 1. */
export async function seedDraft(
actor: Actor,
options: SeedOptions = {},
): Promise<DraftSeed> {
const tag = randomUUID().slice(0, 8)
const names = { fr: `Fiche e2e ${tag}`, en: `E2E sheet ${tag}` }
const document = blankDocument(options.species ?? 'canine', names.fr)
document.name = names
const created = succeeded(
await rpc(
'create_official_sheet',
{ slug: `e2e-${tag}`, document },
actor.aal2,
),
'create',
)
const sheetId = JSON.parse(created.text) as string
const draftId = await sql(
`select id from public.anatomical_sheet_versions where sheet_id = '${sheetId}' and status = 'draft'`,
)
const drawing = options.drawing === undefined ? DRAWING_SVG : options.drawing
const assetId = drawing ? await attachDrawing(actor, sheetId, drawing) : null
if (assetId) document.views[0].svg_asset_id = assetId
options.shape?.(document as unknown as Record<string, unknown>)
const changed = assetId !== null || options.shape !== undefined
if (changed) {
succeeded(
await rpc(
'save_sheet_draft',
{
version_id: draftId,
expected_revision: 0,
document,
change_note: 'fixture',
},
actor.aal2,
),
'save',
)
}
const revision = changed ? 1 : 0
return { sheetId, draftId, names, assetId, revision }
}
/**
* The categories, zone and detail view most editor specs start from. Every defaulted
* field is written out, as the core writes a document: the page reads the stored text
* as it is (an omitted `reference_ids` breaks the findings tree, see the report).
*/
export function standardShape(document: Record<string, unknown>) {
document.categories = [
{ id: 'cat-a', name: text('Catégorie A'), color: null },
]
document.finding_zones = [
{
id: 'zone-a',
name: text('Zone A'),
categories: [
{
id: 'fcat-a',
kind: 'dysfunction',
name: text('Dysfonction A'),
description: {},
reference_ids: [],
review_status: 'reviewed',
children: [
{
id: 'node-a',
name: text('Constat A'),
description: {},
requires_vet_referral: false,
reference_ids: [],
review_status: 'reviewed',
children: [],
},
],
},
],
},
]
;(document.views as unknown[]).push({
id: 'detail-a',
kind: 'detail',
name: text('Détail A'),
svg_asset_id: null,
view_box: { min_x: 100, min_y: 100, width: 300, height: 240 },
parent_view_id: 'main',
})
}
export const draftPath = (sheetId: string) =>
`/app/admin/sheets/${sheetId}/draft`
export const draftTitle = (dict: Dict, number = 1) =>
dict['editor.draft.title'].replace('{number}', String(number))
/** Signs in, steps up and opens the draft editor of `sheetId`; resolves once it is ready. */
export async function openEditor(
page: Page,
dict: Dict,
actor: Actor,
sheetId: string,
): Promise<void> {
await signIn(page, actor.account, dict)
await page.goto('/app/admin')
await stepUpAdmin(page, dict, actor.secret)
await openDraft(page, dict, sheetId)
}
/** Opens the draft page (already signed in and stepped up). */
export async function openDraft(page: Page, dict: Dict, sheetId: string) {
await page.goto(draftPath(sheetId))
await expect(
page.getByRole('heading', { level: 1, name: draftTitle(dict) }),
).toBeVisible()
await expect(page.getByRole('tablist')).toBeVisible()
}
export async function selectTab(page: Page, dict: Dict, tab: string) {
await page
.getByRole('tab', { name: dict[`editor.tab.${tab}`], exact: true })
.click()
}
/** The revision the server holds for the draft. */
export async function serverRevision(draftId: string): Promise<number> {
return Number(
await sql(
`select revision from public.anatomical_sheet_versions where id = '${draftId}'`,
),
)
}
export async function serverDocument<T = Record<string, unknown>>(
draftId: string,
): Promise<T> {
return JSON.parse(
await sql(
`select content::text from public.anatomical_sheet_versions where id = '${draftId}'`,
),
) as T
}
/** Saves through « Enregistrer » and waits until the server revision line moves. */
export async function saveDraft(page: Page, dict: Dict, revision: number) {
await page.getByRole('button', { name: dict['common.save'] }).click()
await expect(
page.getByText(
dict['editor.draft.status.revision'].replace(
'{revision}',
String(revision),
),
{ exact: true },
),
).toBeVisible()
}
/** Client coordinates of a drawing point, through the overlay's own matrix. */
export async function clientOf(
page: Page,
x: number,
y: number,
): Promise<{ x: number; y: number }> {
return page.getByTestId('annotation-overlay').evaluate(
(svg, at) => {
const root = svg as unknown as SVGSVGElement
const point = root.createSVGPoint()
point.x = at.x
point.y = at.y
const mapped = point.matrixTransform(root.getScreenCTM()!)
return { x: mapped.x, y: mapped.y }
},
{ x, y },
)
}
/** A click at a drawing point on the annotation canvas. */
export async function clickDrawing(page: Page, x: number, y: number) {
const at = await clientOf(page, x, y)
await page.mouse.click(at.x, at.y)
}
/** The geometry fields of the open creation panel or properties panel. */
export const geometryField = (page: Page, dict: Dict, key: string) =>
page.getByLabel(dict[`editor.annotations.geometry.${key}`], { exact: true })
/** A point annotation of the fixtures (a circle in drawing units, reviewed). */
export function pointOf(
id: string,
viewId: string,
circle: { cx: number; cy: number; r: number },
name = id,
) {
return {
id,
kind: 'point',
view_id: viewId,
category_id: 'cat-a',
laterality: 'unpaired',
geometry: { type: 'circle', ...circle },
review_status: 'reviewed',
name: text(name),
finding_zone_id: 'zone-a',
vertebral_region_code: null,
}
}
/** The standard shape plus the given annotations. */
export function shapeWith(...annotations: unknown[]) {
return (document: Record<string, unknown>) => {
standardShape(document)
document.annotations = annotations
}
}
export const creationPanel = (page: Page) =>
page.getByTestId('annotation-creation')
export const annotationList = (page: Page, dict: Dict) =>
page.getByRole('list', { name: dict['editor.annotations.list'] })
export const toolButton = (page: Page, dict: Dict, id: string) =>
page.getByRole('button', {
name: dict[`editor.annotations.tool.${id}`],
exact: true,
})
/** Fills the creation panel; the category keeps its first choice. */
export async function fillCreation(
page: Page,
dict: Dict,
names: { fr: string; en: string },
opens?: string,
) {
const panel = creationPanel(page)
await panel.getByLabel(dict['editor.annotations.name_fr']).fill(names.fr)
await panel.getByLabel(dict['editor.annotations.name_en']).fill(names.en)
await panel
.getByLabel(dict['editor.annotations.laterality'])
.selectOption('unpaired')
if (opens)
await panel.getByLabel(dict['editor.annotations.opens']).selectOption(opens)
}
export async function createFromPanel(page: Page, dict: Dict) {
await creationPanel(page)
.getByRole('button', { name: dict['editor.annotations.create'] })
.click()
await expect(creationPanel(page)).toHaveCount(0)
}
/**
* A second signed-in session of `actor` or another account in a fresh browser context,
* under the same replay and the same request allowlist as the suite's pages.
*/
export async function secondSession(
browser: Browser,
baseURL: string,
locale: string,
): Promise<{ context: BrowserContext; page: Page }> {
const context = await browser.newContext({ baseURL, locale })
await routeToSandbox(context)
const allowed = [new URL(baseURL).origin, FAKE_SUPABASE_ORIGIN]
await context.route(
(url) => !allowed.includes(url.origin),
(route) => route.abort('blockedbyclient'),
)
return { context, page: await context.newPage() }
}
/** The storage key of the tab's recovery copy of a draft (state/recovery.ts). */
export const copyKeyOf = (userId: string, versionId: string) =>
`osteo:sheet-draft:${userId}:${versionId}`
export function storedCopy(page: Page, key: string): Promise<string | null> {
return page.evaluate((name) => sessionStorage.getItem(name), key)
}
/** Reloads with the beforeunload dialog of a page holding unsaved changes accepted. */
export async function reloadAccepting(page: Page): Promise<string[]> {
const kinds: string[] = []
const accept = (dialog: import('@playwright/test').Dialog) => {
kinds.push(dialog.type())
void dialog.accept()
}
page.on('dialog', accept)
await page.reload()
page.off('dialog', accept)
return kinds
}
/** An aal2 owner, for the calls that change another account's rights. */
export const ownerActor = (locale: 'fr' | 'en') =>
makeActor(locale, 'owner', [])
/** The id of the account's active grant of `kind`. */
export function grantIdOf(account: SandboxAccount, kind: string) {
return sql(
`select id from public.anatomical_catalog_grants where user_id = '${account.id}'
and grant_kind = '${kind}' and revoked_at is null`,
)
}
/** A grant that ends `seconds` from now (granted earlier, so the expiry check holds). */
export async function seedExpiringGrant(
account: SandboxAccount,
kind: GrantKind,
seconds: number,
): Promise<void> {
await sql(`insert into public.anatomical_catalog_grants
(user_id, grant_kind, reason, verification_note, granted_by, granted_at, expires_at)
values ('${account.id}', '${kind}', 'sandbox', 'sandbox', '${account.id}',
now() - interval '1 hour', now() + interval '${seconds} seconds')`)
}
+49
View File
@@ -0,0 +1,49 @@
/**
* Global setup of the shell suite (V1-2.6): the Vite dev server discovers some
* dependencies only when a route first loads them and answers with a full page
* reload, which wiped a form a test had begun to fill. One throwaway session
* visits the editor routes and every tab once before the tests start, so the
* reload happens here and not in a test.
*/
import { chromium, type FullConfig } from '@playwright/test'
import { fr } from '@/i18n/fr'
import { stepUpAdmin } from './admin'
import { draftPath, editorActor, seedDraft, standardShape } from './editor'
import { routeToSandbox } from './sandbox'
import { signIn } from './shell'
const TABS = [
'general',
'views',
'annotations',
'findings',
'references',
'vertebrae',
'verification',
] as const
export default async function warmUp(config: FullConfig): Promise<void> {
const baseURL = config.projects[0].use.baseURL ?? ''
const actor = await editorActor('fr')
const seed = await seedDraft(actor, { shape: standardShape })
const browser = await chromium.launch()
const context = await browser.newContext({ baseURL, locale: 'fr-FR' })
await routeToSandbox(context)
const page = await context.newPage()
await signIn(page, actor.account, fr)
await page.goto('/app/admin')
await stepUpAdmin(page, fr, actor.secret)
for (const path of ['/app/admin/sheets/new', draftPath(seed.sheetId)]) {
await page.goto(path)
await page.waitForLoadState('networkidle')
}
for (const tab of TABS) {
await page
.getByRole('tab', { name: fr[`editor.tab.${tab}`], exact: true })
.click()
await page.waitForLoadState('networkidle')
}
await page.goto('/app/admin/sheets/new')
await page.waitForLoadState('networkidle')
await browser.close()
}