test(app): catalogue card integrity and retry on the sandbox

This commit is contained in:
bchanot committed 2026-11-17 00:24:14 +01:00
1 parent 6ad8d8347c
commit dadd8e5d29
3 files changed
+357 -8

No files matched your search

@@ -0,0 +1,300 @@
import { randomUUID } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { en } from '@/i18n/en'
import { fr } from '@/i18n/fr'
import type { Dict } from '@/i18n/types'
import type { Locator, Page, Route, TestInfo } from '@playwright/test'
import {
expect,
expectAccessible,
expectNoHorizontalOverflow,
test,
} from '../support/browser'
import { seedGrant } from '../support/admin'
import {
archiveOwnSheet,
revokeOwnGrant,
seedOfficialSheet,
type FixtureSheet,
} from '../support/catalogue'
import {
createAccount,
dropLateReplays,
routeToSandbox,
type SandboxAccount,
} from '../support/sandbox'
import { signIn } from '../support/shell'
// R4 (V1-2.6, board 30) on the isolated stack: a catalogue card whose stored
// fingerprint does not match says the integrity failure in the card, its
// « Consulter » still opening the sheet page and its unchanged notice; a card
// whose version read fails on the network says so with « Réessayer », which
// reloads that card only. Fixtures are SQL prior owner actions, one set per
// worker; the cleanup (D4) archives the run's own sheets and revokes its own
// grant, each by the id captured at seed, and reads every change back.
// One worker per project runs this file in order: one fixture set each.
test.describe.configure({ mode: 'default' })
const LANGUAGES = [
['fr', fr],
['en', en],
] as const
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const VERSION_RPC = '**/rest/v1/rpc/get_sheet_version'
const DOCUMENT = join(
__dirname,
'../../../../supabase/seed/anatomical-sheets/equine/draft/document.json',
)
interface RunFixtures {
tag: string
sound: FixtureSheet
altered: FixtureSheet
reader: SandboxAccount
grantId: string
views: number
zones: number
}
let run: RunFixtures | null = null
const ownSheets: string[] = []
const ownGrants: { id: string; account: string }[] = []
const fixtures = (): RunFixtures => {
if (!run) throw new Error('fixtures not seeded')
return run
}
const sameName = (name: string) => ({ fr: name, en: name })
test.beforeAll(async () => {
test.setTimeout(120_000)
const tag = randomUUID().slice(0, 8)
const sound = await seedOfficialSheet(sameName(`R4 ${tag} saine`), 'listed')
ownSheets.push(sound.id)
const altered = await seedOfficialSheet(
sameName(`R4 ${tag} altérée`),
'listed',
{ storedFingerprint: '0'.repeat(64) },
)
ownSheets.push(altered.id)
const reader = await createAccount('fr', false)
const grantId = await seedGrant(reader, 'catalog_reader')
ownGrants.push({ id: grantId, account: reader.id })
const document = JSON.parse(readFileSync(DOCUMENT, 'utf8')) as {
views: unknown[]
finding_zones: unknown[]
}
run = {
tag,
sound,
altered,
reader,
grantId,
views: document.views.length,
zones: document.finding_zones.length,
}
})
test.afterAll(async () => {
const failures: string[] = []
for (const id of ownSheets.splice(0)) {
const status = await archiveOwnSheet(id).catch((e: Error) => e.message)
if (status !== 'archived') failures.push(`sheet ${id}: ${status}`)
}
for (const grant of ownGrants.splice(0)) {
const result = await revokeOwnGrant(grant.id, grant.account).catch(
(e: Error) => ({ returned: e.message, readBack: '' }),
)
if (result.returned !== grant.id || result.readBack !== grant.id)
failures.push(`grant ${grant.id}: ${JSON.stringify(result)}`)
}
expect(failures, 'cleanup of the run (D4)').toEqual([])
})
const heading = (page: Page, name: string) =>
page.getByRole('main').getByRole('heading', { level: 1, name })
/** Signs in, then sets the language of the test (the account's own wins at sign-in). */
async function signInAs(page: Page, locale: 'fr' | 'en', dict: Dict) {
await signIn(page, fixtures().reader, dict)
const switcher = page.getByRole('button', {
name: dict[`lang.switch_to_${locale}`],
})
await switcher.click()
await expect(switcher).toHaveAttribute('aria-pressed', 'true')
}
/** Follows the catalogue entry: the sidebar, or the drawer on a phone. */
async function openCatalogue(page: Page, dict: Dict, info: TestInfo) {
if (isPhone(info)) {
await page.getByRole('button', { name: dict['shell.open_menu'] }).click()
const drawer = page.getByRole('dialog', { name: dict['shell.nav_label'] })
await drawer
.getByRole('navigation')
.getByRole('link', { name: dict['shell.nav.anatomy'] })
.click()
// The drawer keeps the page inert until its exit animation ends.
await expect(drawer).toHaveCount(0)
} else {
await page
.getByRole('navigation', { name: dict['shell.nav_label'] })
.getByRole('link', { name: dict['shell.nav.anatomy'] })
.click()
}
await expect(heading(page, dict['shell.nav.anatomy'])).toBeVisible()
await expect(cards(page, dict).first()).toBeVisible()
}
const cards = (page: Page, dict: Dict) =>
page
.getByRole('list', { name: dict['catalogue.results'] })
.getByRole('listitem')
const cardOf = (page: Page, dict: Dict, sheet: FixtureSheet) =>
cards(page, dict).filter({
has: page.getByRole('heading', { level: 2, name: sheet.names.fr }),
})
const consultOf = (card: Locator, dict: Dict, sheet: FixtureSheet) =>
card.getByRole('link', {
name: dict['catalogue.view_sheet'].replace('{name}', sheet.names.fr),
})
async function search(page: Page, dict: Dict, term: string) {
await page
.getByRole('searchbox', { name: dict['catalogue.search'] })
.fill(term)
}
/** The counts of the version line, as the card words them. */
function countsText(dict: Dict): string {
const { views, zones } = fixtures()
const counted = (count: number, key: string) =>
dict[`${key}_${count === 1 ? 'one' : 'other'}`].replace(
'{count}',
String(count),
)
return `${counted(views, 'catalogue.card.views')}, ${counted(zones, 'catalogue.card.zones')}`
}
async function expectAtLeast44High(target: Locator, what: string) {
const box = await target.boundingBox()
expect(box, `${what} box`).not.toBeNull()
expect(box!.height, `${what} height`).toBeGreaterThanOrEqual(44)
}
/** The searched list at the project's width: axe and no sideways scroll. */
async function expectListLayout(page: Page, state: string) {
const width = page.viewportSize()!.width
await expectAccessible(page, `${state} at ${width} px`)
await expectNoHorizontalOverflow(page, `${state} at ${width} px`)
}
for (const [locale, dict] of LANGUAGES) {
test.describe(`catalogue card integrity (${locale})`, () => {
test.use({ locale: locale === 'fr' ? 'fr-FR' : 'en-GB' })
test.beforeEach(async ({ context }) => {
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('an altered version says the integrity failure in its card; « Consulter » opens the sheet notice', async ({
page,
requests,
}, info) => {
const { tag, sound, altered, reader } = fixtures()
requests.forbid(reader.email, reader.password, reader.displayName, tag)
await signInAs(page, locale, dict)
await openCatalogue(page, dict, info)
await search(page, dict, tag)
await expect(cards(page, dict)).toHaveCount(2)
const soundCard = cardOf(page, dict, sound)
await expect(soundCard).toContainText(countsText(dict))
const alteredCard = cardOf(page, dict, altered)
await expect(
alteredCard.getByText(dict['catalogue.card.integrity_failed']),
).toBeVisible()
await expect(
alteredCard.getByText(dict['catalogue.status.published']),
).toBeVisible()
await expect(
alteredCard.getByRole('button', { name: dict['common.retry'] }),
).toHaveCount(0)
const consult = consultOf(alteredCard, dict, altered)
await expectAtLeast44High(consult, '« Consulter » of the altered card')
await expectListLayout(page, 'the integrity line')
await consult.focus()
await expect(consult).toBeFocused()
await page.keyboard.press('Enter')
await expect(page).toHaveURL(new RegExp(`/app/anatomy/${altered.id}$`))
await expect(
page
.getByRole('main')
.getByText(dict['catalogue.failure.fingerprint_mismatch']),
).toBeVisible()
})
})
}
test.describe('catalogue card network failure (fr)', () => {
const dict = fr
test.use({ locale: 'fr-FR' })
test.beforeEach(async ({ context }) => {
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('a version read lost on the network says so; « Réessayer » reloads that card and focuses its « Consulter »', async ({
context,
page,
requests,
}, info) => {
const { tag, sound, altered, reader } = fixtures()
requests.forbid(reader.email, reader.password, reader.displayName, tag)
await signInAs(page, 'fr', dict)
await openCatalogue(page, dict, info)
await search(page, dict, tag)
const soundCard = cardOf(page, dict, sound)
await expect(soundCard).toContainText(countsText(dict))
// The sound version's read fails; every other request goes on to the sandbox.
const versionId = sound.currentVersionId!
const lose = (route: Route) =>
(route.request().postData() ?? '').includes(versionId)
? route.abort('internetdisconnected')
: route.fallback()
await context.route(VERSION_RPC, lose)
// Remounted by a search that hides it, then the tag again (never a reload).
await search(page, dict, altered.names.fr)
await expect(cards(page, dict)).toHaveCount(1)
await search(page, dict, tag)
await expect(
soundCard.getByText(dict['catalogue.failure.network']),
).toBeVisible()
const retry = soundCard.getByRole('button', { name: dict['common.retry'] })
await expect(retry).toBeVisible()
await expectAtLeast44High(retry, '« Réessayer »')
await expectAtLeast44High(
consultOf(soundCard, dict, sound),
'« Consulter » beside « Réessayer »',
)
await expectListLayout(page, 'the network line')
await context.unroute(VERSION_RPC, lose)
await retry.click()
await expect(soundCard).toContainText(countsText(dict))
await expect(retry).toHaveCount(0)
await expect(consultOf(soundCard, dict, sound)).toBeFocused()
})
})
+4 -4
View File
@@ -34,14 +34,14 @@ export async function assignRole(
)
}
/** A right granted earlier by the owner (a prior action, written as postgres). */
/** A right granted earlier by the owner (a prior action, written as postgres); resolves with its id. */
export async function seedGrant(
account: SandboxAccount,
kind: GrantKind,
): Promise<void> {
): Promise<string> {
const note = kind === 'catalog_reader' ? 'null' : "'sandbox'"
await sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by)
values ('${account.id}', '${kind}', 'sandbox', ${note}, '${account.id}')`)
return sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by)
values ('${account.id}', '${kind}', 'sandbox', ${note}, '${account.id}') returning id`)
}
/** A password session of the account on GoTrue: always aal1. */
+53 -4
View File
@@ -37,6 +37,13 @@ export interface SheetNames {
export interface FixtureSheet {
id: string
names: SheetNames
/** The version the catalogue lists (v2 of a listed sheet), null for a draft-only one. */
currentVersionId: string | null
}
export interface SeedOptions {
/** Stored on the published and retired versions in place of the core's (an altered record). */
storedFingerprint?: string
}
/**
@@ -141,6 +148,7 @@ export type SheetShape =
export async function seedOfficialSheet(
names: SheetNames,
shape: SheetShape,
options: SeedOptions = {},
): Promise<FixtureSheet> {
const { drawing, document: text, sha } = await seedFiles()
await storeDrawing(sha, drawing)
@@ -151,7 +159,8 @@ export async function seedOfficialSheet(
const fingerprint =
shape === 'draft'
? null
: await fingerprintOf(document, asset, sha, drawing)
: (options.storedFingerprint ??
(await fingerprintOf(document, asset, sha, drawing)))
const slug = `e2e-${id.slice(0, 12)}`
const archived = shape === 'archived'
const content = `${literal(document)}::jsonb`
@@ -162,8 +171,9 @@ export async function seedOfficialSheet(
: shape === 'archived'
? `('${v1}', '${id}', 1, 'published', 2, ${content}, now(), null, ${literal(fingerprint)})`
: `('${v1}', '${id}', 1, 'draft', 2, ${content}, null, null, null)`
const current =
shape === 'listed' ? `'${v2}'` : shape === 'archived' ? `'${v1}'` : 'null'
const currentVersionId =
shape === 'listed' ? v2 : shape === 'archived' ? v1 : null
const current = literal(currentVersionId)
await sql(`begin;
select set_config('request.jwt.claims', '{"sub":"${SEED_OWNER}"}', true);
insert into public.anatomical_sheets (id, species_id, name, slug, is_official, visibility, status, archived_at)
@@ -177,5 +187,44 @@ export async function seedOfficialSheet(
update public.anatomical_sheets set current_version_id = ${current},
last_version_number = ${shape === 'listed' ? 2 : 1} where id = '${id}';
commit;`)
return { id, names }
return { id, names, currentVersionId }
}
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
/** An id a run captured, checked before it is written into a statement. */
function capturedId(id: string): string {
if (!UUID.test(id)) throw new Error(`cleanup: not a captured id (${id})`)
return id
}
/**
* Cleanup of a run (D4): one sheet the run seeded archived through the
* migrations' own path as the seed owner (audit row included), then its status
* read back; resolves with that status. Names that one id, nothing by pattern.
*/
export async function archiveOwnSheet(sheetId: string): Promise<string> {
const id = capturedId(sheetId)
await sql(`select private.set_sheet_status('${SEED_OWNER}', '${id}', 'active', 'archived',
'anatomical_sheet.archived')`)
return sql(`select status from public.anatomical_sheets where id = '${id}'`)
}
/**
* Cleanup of a run (D4): the catalogue grant the run seeded revoked by its id,
* as its account (the single change the grant guard allows); resolves with the
* id the update returned and the id read back as revoked (empty when none).
*/
export async function revokeOwnGrant(
grantId: string,
accountId: string,
): Promise<{ returned: string; readBack: string }> {
const [id, account] = [capturedId(grantId), capturedId(accountId)]
const returned =
await sql(`update public.anatomical_catalog_grants set revoked_at = now(),
revoked_by = '${account}', revocation_reason = 'e2e cleanup'
where id = '${id}' and revoked_at is null returning id`)
const readBack = await sql(`select id from public.anatomical_catalog_grants
where id = '${id}' and revoked_at is not null and revocation_reason = 'e2e cleanup'`)
return { returned, readBack }
}