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: { id: string; name: 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({ id: sound.id, name: sound.names.fr }) const altered = await seedOfficialSheet( sameName(`R4 ${tag} altérée`), 'listed', { storedFingerprint: '0'.repeat(64) }, ) ownSheets.push({ id: altered.id, name: altered.names.fr }) 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, name } of ownSheets.splice(0)) { const status = await archiveOwnSheet(id, name).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')}` } /** Board 30: « Réessayer » and « Consulter » side by side, on one row. */ async function expectOneRow(first: Locator, second: Locator) { const [a, b] = [await first.boundingBox(), await second.boundingBox()] expect(a && b, 'both buttons laid out').toBeTruthy() expect(Math.abs(a!.y - b!.y), 'same row').toBeLessThan(1) expect(b!.x, 'side by side').toBeGreaterThanOrEqual(a!.x + a!.width) } 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 expectOneRow(retry, consultOf(soundCard, dict, sound)) 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() }) })