diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 8789f3ef6..9102e7568 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -79,6 +79,16 @@ jobs: - name: Set up the frontend uses: ./.github/actions/setup-frontend + # Builds while the backend is set up; "Wait for the frontend build" checks it. + - name: Start the frontend build + run: | + ( + npm run build > "$RUNNER_TEMP/frontend-build.log" 2>&1 + echo $? > "$RUNNER_TEMP/frontend-build.tmp" + mv "$RUNNER_TEMP/frontend-build.tmp" "$RUNNER_TEMP/frontend-build.exit" + ) & + working-directory: frontend + # Headless runs use only the headless shell, so skip the full Chrome build. - name: Install Playwright browser run: npx playwright install --with-deps --only-shell chromium @@ -129,7 +139,13 @@ jobs: exit 1 working-directory: backend - # Starts the Vite dev server and waits for port 3000. + - name: Wait for the frontend build + run: | + while [ ! -f "$RUNNER_TEMP/frontend-build.exit" ]; do sleep 2; done + cat "$RUNNER_TEMP/frontend-build.log" + exit "$(cat "$RUNNER_TEMP/frontend-build.exit")" + + # Serves that build through playwright.config.ts's webServer. - name: Run Playwright tests run: npm run test:e2e working-directory: frontend @@ -140,8 +156,7 @@ jobs: with: name: playwright-report path: | - frontend/playwright-report/ - frontend/test-results/ + frontend/e2e/.output/specs/ retention-days: 7 - name: Dump backend log diff --git a/.gitignore b/.gitignore index f6ffb4853..59f67e780 100644 --- a/.gitignore +++ b/.gitignore @@ -93,10 +93,9 @@ switch_product_ids.json # Local dev scripts /dev.sh -# Playwright (e2e) artifacts -frontend/playwright/.auth/ -frontend/test-results/ -frontend/playwright-report/ +# Playwright (e2e) artifacts and local settings +frontend/e2e/.output/ +frontend/e2e/.env frontend/blob-report/ frontend/.last-run.json diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 09fba8837..454bfed10 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -61,6 +61,8 @@ lint: - .claude/skills/humanizer/** # Intentionally malformed YAML, used as a test fixture - backend/tests/config/fixtures/config/malformed_config.yml + # Playwright reports, traces and saved sessions (also gitignored) + - frontend/e2e/.output/** # The v1 UI is frozen and the freeze check blocks changes to these paths, # so ESLint findings in its templates cannot lead to fixes. Its TypeScript # stays covered, since that was already linted before .vue was. diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..7b3f8bdae --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["ms-playwright.playwright"] +} diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md index 73736f2fd..09b750ad9 100644 --- a/frontend/AGENTS.md +++ b/frontend/AGENTS.md @@ -12,10 +12,10 @@ v2 has a detailed constitution, split across the `frontend-v2-*` skills in `.cla ```bash npm install # install (Node 24) npm run dev # dev server :3000 -npm run typecheck # vue-tsc --build: the app and the Node tooling -npm run typecheck:scripts # Node tooling only: scripts/, eslint-plugin-romm/, tool configs +npm run typecheck # vue-tsc --build: the app, the Node tooling and the e2e suite +npm run typecheck:scripts # Node only: scripts/, eslint-plugin-romm/, tool configs, the e2e suite npm run test # vitest (+ Storybook play() tests) -npm run test:e2e # playwright (needs a running app + seeded e2e users) +npm run test:e2e # playwright, see e2e/README.md npm run build # production build npm run generate # regenerate types from backend OpenAPI (backend must be running) npm run build:tokens # regenerate v2 tokens.css (auto on predev/prebuild) diff --git a/frontend/e2e/.env.example b/frontend/e2e/.env.example new file mode 100644 index 000000000..ffaecd179 --- /dev/null +++ b/frontend/e2e/.env.example @@ -0,0 +1,15 @@ +# Optional: copy to e2e/.env to override the defaults below. The shell wins +# over this file. + +# The site under test, as an origin with no path. Unset, the suite serves this +# checkout on http://127.0.0.1:3000 (or reuses the server already there). +# E2E_BASE_URL=http://127.0.0.1:4173 + +# An admin, and a non-admin in the "Viewer (legacy)" group. The defaults are +# the accounts .github/scripts/seed_e2e_users.py creates. E2E_PASSWORD is the +# password it seeds both with, and the fallback for the two below. +# E2E_PASSWORD=e2e-Passw0rd! +# E2E_ADMIN_USERNAME=e2e_admin +# E2E_ADMIN_PASSWORD=e2e-Passw0rd! +# E2E_VIEWER_USERNAME=e2e_viewer +# E2E_VIEWER_PASSWORD=e2e-Passw0rd! diff --git a/frontend/e2e/AGENTS.md b/frontend/e2e/AGENTS.md new file mode 100644 index 000000000..8614af513 --- /dev/null +++ b/frontend/e2e/AGENTS.md @@ -0,0 +1,21 @@ +# E2E suite rules + +- **Layout:** tests go in `specs/` and nothing else does, one folder per page named after its route name in `src/plugins/routeNames.ts` (`specs/rom/`), each file named after what it checks. Specs that aren't about one page go in a folder named for their area, such as `specs/auth/`. Setup projects go in `setup/`, fixtures and helpers in `support/`, and every generated file under `.output/`, through the paths in `support/output.ts`. +- **Every route is in `PAGES` in `specs/loads.spec.ts`,** keyed by route name, so a new route fails the typecheck until it gets an entry: a page to open, which must load for each role allowed on it with every response 2xx (and give a viewer the 404 page when its route is in `ROUTE_SCOPES` but not `VIEWER_OPENS`), or a `skip` with the reason. Tag each top-level `describe` of a page's other specs with its route name, `{ tag: "@page:rom" }`. +- **Each variable has one home.** `playwright.config.ts` loads `e2e/.env` and reads `E2E_BASE_URL`; `support/auth.ts` reads the account variables into `ACCOUNTS`. Specs read neither `process.env` nor `.env`: they take `ACCOUNTS`, or Playwright's `baseURL` fixture. A new variable gets a default that works against a seeded dev backend, and a line in `.env.example`. +- **One site, one URL.** The suite tests whatever `E2E_BASE_URL` serves. Unset, the config's `webServer` starts the app (the dev server locally, the static build in CI); that is the only server it starts. Don't add Docker or a second target. +- **Import `test` and `expect` from `support/test.ts`,** so the app-error guard applies. ESLint enforces it. +- **Prefer Playwright's own tools over custom scripts.** Recording, debugging, reports and traces come from the Playwright CLI and the VS Code extension; document the native way in the README. +- **Select by role and label** (`getByRole`, `getByLabel`), then by ARIA or `data-*` attributes. A CSS class only where the app offers neither. +- **Recorded code is a draft.** Before committing, give it real assertions, replace CSS-path and `nth()` selectors with roles and labels, and run it. +- **Timeouts:** don't add hard-coded ones that would outlive a debug session; the config sets every timeout to 0 when a debugger is attached. A test that genuinely needs longer calls `test.slow()`, which leaves a debug session's 0 alone, as `auth.setup.ts` does. +- **Fail on the cause, not on a timeout.** + - The automatic guard in `support/test.ts` fails a test the moment an `/api` call returns 5xx or the app throws. + - When a helper waits for a response, accept any status, then check it and throw a message naming the method, path and status, as `gotoHydrated()` does. Never filter on `status() === 200` inside `waitForResponse`. + - Retry only what's transient, with Playwright's own `retries`: the `setup` project retries sign-in, which a dev-server reload can interrupt. + - Don't paper over slowness with longer timeouts or `waitForTimeout`; find the event to wait for. + - Observe the app's own traffic; don't call the API from tests (ESLint enforces it). +- **Every run signs in afresh.** `auth.setup.ts` saves each account's session to `e2e/.output/auth/` for that run's specs. +- **Pick a theme with `colorScheme`** (`page.emulateMedia()` or `test.use()`), never by writing `settings.theme`: the app syncs UI settings to the account, so a written theme leaks into every later sign-in. The suite's stored theme is always "auto". +- **`login.spec.ts` must start signed out,** via its explicit empty `storageState`. +- **Lint rules for e2e live in `frontend/eslint.e2e.config.js`,** never inline in `eslint.config.js`. A rule that's wrong for tests gets a named exception there with a one-line reason and the narrowest `files` glob, not an `eslint-disable` comment. diff --git a/frontend/e2e/README.md b/frontend/e2e/README.md index 32cf3fca7..763e95d66 100644 --- a/frontend/e2e/README.md +++ b/frontend/e2e/README.md @@ -1,26 +1,150 @@ # End-to-end tests (Playwright) -These drive a **real running RomM instance**, unlike the Vitest specs, which mount components in isolation. They exist to cover behaviour that only shows up in the assembled app. They live in `e2e/` rather than `src/` or `test/` because Vitest's globs (`src/**/*.{test,spec}.ts`, `test/**/*.{test,spec}.ts`) would otherwise try to run them in jsdom. +These tests drive the app in a real browser against a real backend, for behaviour that only shows up once everything is assembled. Vitest covers components in isolation. -## Running tests +## Run it -1. Have the app up and reachable (default `http://localhost:3000`, override with `E2E_BASE_URL`), with a populated library; the specs pick the first ROM they find. +You need a backend with games in its library and two accounts: an admin, and a non-admin in the Viewer group. On a throwaway dev backend, the seed script creates both (run it from the repo root). Never run it against a real server; it resets those accounts' passwords. -2. Seed the two fixture users, from the repo root: +```bash +uv run python .github/scripts/seed_e2e_users.py +``` - ```bash - uv run python .github/scripts/seed_e2e_users.py # --remove to clean up afterwards - ``` +Then, from `frontend/`: -3. Run, from `frontend/`: +```bash +npm run test:e2e +``` - ```bash - npm run test:e2e # headless - npm run test:e2e:ui # interactive, for debugging a failure - ``` +That starts `npm run dev` (or reuses the one already running on 3000), which proxies to the backend named by `DEV_PORT` or `DEV_PROXY_TARGET` in `.env`. To point the suite at another site or other accounts, set the variables from `e2e/.env.example` in your shell or in `e2e/.env`. For more or fewer parallel workers than the default 2, pass `--workers N`. -## Authentication +Install the recommended VS Code extension, **Playwright Test for VS Code**. Most recipes below start from its panel in the Testing sidebar. -`auth.setup.ts` runs first as its own project, logs each fixture user in once and saves the session to `playwright/.auth/` (gitignored). Specs pick an identity with `test.use({ storageState: STORAGE_STATE.viewer })` and start signed in, so the form is driven twice per run rather than once per test. +## Recipes -`login.spec.ts` is the only spec that drives the form, using the default unauthenticated page. If auth breaks, diagnose there. +### Write a new test by clicking + +Create the file, leave the cursor inside the test, and click **Record at cursor** in the Playwright panel: + +```ts +// e2e/specs/home/favorite-a-game.spec.ts +import { STORAGE_STATE } from "../../support/auth"; +import { expect, test } from "../../support/test"; + +test.describe("Favorites", { tag: "@page:home" }, () => { + test.use({ storageState: STORAGE_STATE.admin }); + + test("favorites a game", async ({ page }) => { + await page.goto("/"); + // cursor here + }); +}); +``` + +A browser opens, already signed in, and every click is written into the file. Use the recorder's assert buttons for what should be true afterwards, then replace any `nth()` or CSS-path selectors with roles and labels. + +### Watch a test run + +Tick **Show browser** in the Playwright panel and run any test. From a terminal: + +```bash +npx playwright test --headed --workers 1 +``` + +### Find out why a test failed + +```bash +npx playwright test --ui # click a step to see the page, network and console at that moment +npm run test:e2e:report # the last run's failures, with traces +``` + +For a CI failure, download the `playwright-report` artifact from the workflow run, unzip it, and run `npx playwright show-report /report`. + +### Stop on a line + +Set a breakpoint, right-click the test's gutter arrow, and choose **Debug Test**. Timeouts switch off while a debugger is attached, so take your time. + +### Poke at the page mid-test + +```ts +await page.pause(); +``` + +```bash +npx playwright test --debug e2e/specs/rom/actions-menu.spec.ts +``` + +The Inspector steps one action at a time, tries locators live, and records more steps. ESLint refuses a committed `page.pause()`. + +### Find a selector + +**Pick locator** in the Playwright panel, then click the element. The locator is copied for you. + +### Debug the Vue app itself + +Run headed, press F12 in the test browser, and put `debugger;` in any `.vue` file. It pauses there, with the real source files. + +### Test as the viewer + +```ts +test.use({ storageState: STORAGE_STATE.viewer }); +``` + +Need the credentials themselves? Take them from `ACCOUNTS`: + +```ts +const { username } = ACCOUNTS.viewer; +``` + +### Test Explorer shows no tests + +The extension lists tests by loading `playwright.config.ts`. If that fails, the panel stays empty. See why: + +```bash +npx playwright test --list +``` + +Fix what it reports, then click **Refresh Tests** in the Testing sidebar. + +### Run one file, one test, or one page + +```bash +npm run test:e2e -- e2e/specs/auth/login.spec.ts +npm run test:e2e -- -g "rejects a wrong password" +npm run test:e2e -- --grep "@page:rom( |$)" # every test for one page, by its route name +``` + +### Test another site + +Set `E2E_BASE_URL` (in the shell or `e2e/.env`), and use accounts that exist there: + +```ini +E2E_BASE_URL=https://romm.example.com +``` + +The specs follow this branch's UI, so a site on another version fails where the two differ. A released site (5.3.1, say) lacks endpoints added on master since, and `loads.spec.ts` reports each as a 404. For a full pass, run a backend from this checkout (`uv run main.py`) and leave `E2E_BASE_URL` unset. + +To test a production build of this branch, serve it first: `npm run build && npm run preview` (preview also serves `frontend/assets`, as the Docker image does), then set `E2E_BASE_URL=http://localhost:4173`. + +## How it's wired + +```text +e2e/ + specs/ the tests, and only tests, one folder per page + loads.spec.ts every page opens with every response 2xx + setup/ sign-in and the first game, run before the specs + support/ fixtures, helpers, environment and output paths + .output/ generated and gitignored; delete it to reset + auth/ saved sessions + specs/ results/ (traces, screenshots) and report/ (HTML) +``` + +- **Environment:** every `E2E_*` variable comes from the shell, then `e2e/.env`, then a default that matches the seed script. CI uses the defaults. +- **Server:** with `E2E_BASE_URL` unset, the config's `webServer` starts one: `npm run dev` locally (reusing one already running), the static build under `vite preview` in CI. Otherwise it tests that URL as served. +- **Sign-in:** `setup/auth.setup.ts` signs each account in at the start of every run and saves the session for the specs. `login.spec.ts` is the only spec that drives the login form. +- **Library:** `setup/library.setup.ts` then finds the first game once, and specs open it by URL with `gotoFirstRom()`. +- **Timeouts:** the same locally and in CI (45s per test), so a test passes or fails the same way in both. They switch off while debugging. +- **App errors:** if an `/api` call returns 5xx or the app throws, the test fails at once and names the request (for example `GET /api/roms returned 500`) instead of timing out on an element. +- **Output:** everything the suite writes goes under `.output/`, through the paths in `support/output.ts`. +- **Checks:** `npm run typecheck` covers the suite through `tsconfig.node.json` (`typecheck:scripts` checks just that project), and lint rules live in `eslint.e2e.config.js`. +- **Changing the suite itself:** see [AGENTS.md](AGENTS.md). diff --git a/frontend/e2e/auth.setup.ts b/frontend/e2e/auth.setup.ts deleted file mode 100644 index 8e3e1cddb..000000000 --- a/frontend/e2e/auth.setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test as setup } from "@playwright/test"; -import { login, seedUiState, STORAGE_STATE, USERS } from "./fixtures/auth"; - -// Runs once per role before the suite, as its own Playwright project (see -// `dependencies` in playwright.config.ts). Each saves the authenticated session -// -- cookies plus localStorage -- so the specs can start already logged in -// instead of driving the form 15 times over. -// -// The login FLOW itself is covered by login.spec.ts, which deliberately uses a -// fresh unauthenticated page. This file is plumbing: if it breaks, that spec is -// where the real diagnosis lives. -for (const role of Object.keys(USERS) as (keyof typeof USERS)[]) { - setup(`authenticate as ${role}`, async ({ page }) => { - // Bake the v2 flag into the saved state so every spec inherits it. - await seedUiState(page, "dark"); - await login(page, role); - await page.context().storageState({ path: STORAGE_STATE[role] }); - }); -} diff --git a/frontend/e2e/fixtures/auth.ts b/frontend/e2e/fixtures/auth.ts deleted file mode 100644 index e71baf558..000000000 --- a/frontend/e2e/fixtures/auth.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { expect, type Page } from "@playwright/test"; - -// Fixture accounts seeded by `.github/scripts/seed_e2e_users.py`. -export const USERS = { - admin: process.env.E2E_ADMIN_USERNAME ?? "e2e_admin", - viewer: process.env.E2E_VIEWER_USERNAME ?? "e2e_viewer", -} as const; - -export const PASSWORD = process.env.E2E_PASSWORD ?? "e2e-Passw0rd!"; - -export type Role = keyof typeof USERS; - -/** Where auth.setup.ts parks each role's authenticated session. Gitignored -- - * they hold live session cookies and are regenerated on every run. */ -export const STORAGE_STATE: Record = { - admin: "playwright/.auth/admin.json", - viewer: "playwright/.auth/viewer.json", -}; - -/** Log in through the real form and wait for the app shell to take over. - * - * Everything is scoped to `form.r-v2-login-form`. The reset-password form is - * rendered alongside it (collapsed, not unmounted) and has its own submit - * button and fields, so unscoped `button[type="submit"]` / `input[name=...]` - * selectors match two elements and blow up on strict mode. */ -export async function login( - page: Page, - role: Role, - { - timeout = 25_000, - attempts = 3, - }: { timeout?: number; attempts?: number } = {}, -) { - // Retried because the Vite dev server force-reloads the page when it - // discovers a new dependency to pre-bundle ("optimized dependencies changed. - // reloading"). - let lastError: unknown; - for (let attempt = 1; attempt <= attempts; attempt++) { - try { - await page.goto("/login"); - const form = page.locator("form.r-v2-login-form"); - await form.locator('input[name="username"]').fill(USERS[role]); - await form.locator('input[name="password"]').fill(PASSWORD); - await form.locator('button[type="submit"]').click(); - // Assert a marker that only exists once authenticated (the app bar's user - // name) rather than just "the URL is no longer /login" -- the latter goes - // true mid-transition and says nothing about the session. - await expect(page.locator(".r-v2-user__name")).toHaveText(USERS[role], { - timeout, - }); - await expect(page).not.toHaveURL(/\/login/); - return; - } catch (error) { - lastError = error; - } - } - throw lastError; -} - -/** Navigate to the logged-in user's own profile page (route `/user/:user`). */ -export async function gotoOwnProfile(page: Page) { - const res = await page.request.get("/api/users/me"); - expect(res.ok(), "could not resolve the current user").toBe(true); - const me = await res.json(); - await gotoHydrated(page, `/user/${me.id}`); - return me; -} - -/** Navigate to the first ROM of the first non-empty platform. - * - * Waits for the permission grants to land before returning. `useCan` reads a - * store hydrated from `/permissions/me` AFTER the app mounts, so until that - * response arrives even an admin has no grants and every gated control is - * hidden. Asserting before then reads the pre-hydration menu -- which looks - * exactly like a permissions bug and is not one. */ -export async function gotoFirstRom(page: Page) { - const res = await page.request.get("/api/roms?limit=1&order_by=name"); - expect(res.ok(), "could not list ROMs -- is the dev library populated?").toBe( - true, - ); - const body = await res.json(); - const rom = body.items?.[0]; - expect(rom, "the dev library has no ROMs to test against").toBeTruthy(); - await gotoHydrated(page, `/rom/${rom.id}`); - return rom; -} - -/** `page.goto` that also waits for the permissions store to hydrate. The - * listener is armed BEFORE navigating, or the response can land first and the - * wait hangs until it times out. */ -export async function gotoHydrated(page: Page, path: string) { - const hydrated = page - .waitForResponse( - (r) => r.url().includes("/api/permissions/me") && r.status() === 200, - // Short: hydration normally lands well under a second. A long timeout - // here is actively harmful -- when the request doesn't fire, the catch - // below still waits it out first, eating the test's own budget. - { timeout: 10_000 }, - ) - // A cached/absent refetch shouldn't fail the navigation; the assertions - // that follow are auto-waiting anyway. - .catch(() => null); - await page.goto(path); - await hydrated; - // The app bar's user name renders only once the auth store holds a user, so - // it doubles as an "app shell is ready" signal. Without it, assertions can - // run against a view still showing its loading skeleton -- which fails as a - // missing element and reads like the element was removed on purpose. - await expect(page.locator(".r-v2-user__name")).toBeVisible({ - timeout: 30_000, - }); -} - -/** Open the ⋯ more-actions menu and return the teleported panel locator. */ -export async function openMoreMenu(page: Page) { - await page.getByRole("button", { name: "More actions" }).first().click(); - const panel = page.locator('[role="menu"]'); - await expect(panel).toBeVisible(); - return panel; -} - -/** Visible labels of every item in an open menu panel, in DOM order. */ -export async function menuLabels(page: Page): Promise { - return page.locator('[role="menu"] .r-menu-item__label').allInnerTexts(); -} - -/** Force the v2 UI and a known theme before the app boots. */ -export async function seedUiState(page: Page, theme: "dark" | "light") { - await page.addInitScript((t) => { - localStorage.setItem("settings.uiVersion", "v2"); - localStorage.setItem("settings.theme", t); - }, theme); -} diff --git a/frontend/e2e/game-media-files.spec.ts b/frontend/e2e/game-media-files.spec.ts deleted file mode 100644 index ac91d0832..000000000 --- a/frontend/e2e/game-media-files.spec.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { expect, type Locator, type Page, test } from "@playwright/test"; -import { gotoFirstRom, seedUiState, STORAGE_STATE } from "./fixtures/auth"; - -// The Media and Files tabs write to the ROM (manuals, soundtracks, shared -// screenshots, ROM files) and every one of those endpoints gates on ROMS_WRITE. -// A read-only user must not be offered upload/delete there -- same 403-to-logout -// trap as the ⋯ menu. -// -// The per-user "My screenshots" section is the deliberate exception: it writes -// user assets, which every authenticated user may do. -// -// NOTE: MediaTab keeps every subtab panel mounted (v-show, not v-if) so the -// heavy async panels don't re-mount on each switch. Assertions must therefore -// scope to the VISIBLE panel -- a document-wide locator would also match the -// hidden panels and pass or fail for the wrong reason. -// -// Sessions come from auth.setup.ts; see login.spec.ts for the form itself. - -async function openTab(page: Page, tab: string) { - await page.getByRole("tab", { name: tab }).click(); -} - -// Media subtabs are a sidebar list of role=tab buttons, distinct from the -// top-level RTabNav tabs. -async function openSubtab(page: Page, subtab: string) { - await page.locator(".r-v2-subtab-nav__btn", { hasText: subtab }).click(); -} - -/** The one Media panel currently on screen. */ -function visiblePanel(page: Page): Locator { - return page.locator(".r-v2-media__panel:visible"); -} - -// Both panels whose upload path is ROM-scoped, so both must be inert. -const ROM_SCOPED_SUBTABS = [ - ["Manual", "No manual yet"], - ["Soundtrack", "No soundtrack yet"], -] as const; - -test.describe("Media tab write affordances (read-only user)", () => { - test.use({ storageState: STORAGE_STATE.viewer }); - - for (const [subtab, emptyText] of ROM_SCOPED_SUBTABS) { - test(`${subtab}: gets the empty state, not a dropzone`, async ({ - page, - }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - await openTab(page, "Media"); - await openSubtab(page, subtab); - - const panel = visiblePanel(page); - // The plain REmptyState replaces the dropzone: same message, no CTA, - // no drag-and-drop hint, no Upload button. - await expect(panel.getByText(emptyText)).toBeVisible(); - await expect(panel.locator(".r-dropzone__cta")).toHaveCount(0); - await expect( - panel.getByText("Drag and drop, or click to browse"), - ).toHaveCount(0); - await expect( - panel.getByRole("button", { name: "Upload", exact: true }), - ).toHaveCount(0); - }); - } - - test("Screenshots: the shared ROM section is hidden but the per-user one stays writable", async ({ - page, - }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - await openTab(page, "Media"); - await openSubtab(page, "Screenshots"); - - const panel = visiblePanel(page); - // Shared section writes to the ROM: gone for a read-only user with nothing - // to show. - await expect(panel.getByText("ROM screenshots")).toHaveCount(0); - // Per-user section writes user assets: must survive, dropzone included. - // Hiding this would be the regression in the opposite direction. - await expect(panel.getByText("My screenshots")).toBeVisible(); - await expect(panel.locator(".r-dropzone__cta")).not.toHaveCount(0); - }); -}); - -test.describe("Media tab write affordances (admin)", () => { - test.use({ storageState: STORAGE_STATE.admin }); - - for (const [subtab] of ROM_SCOPED_SUBTABS) { - test(`${subtab}: still gets the dropzone`, async ({ page }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - await openTab(page, "Media"); - await openSubtab(page, subtab); - - const panel = visiblePanel(page); - // Empty ROM => CTA dropzone; populated ROM => Upload button. Either is a - // write affordance, and a read-only user gets neither. `.or()` keeps this - // auto-waiting: a bare `count()` reads 0 before the async panel mounts. - const writeAffordance = panel - .locator(".r-dropzone__cta") - .or(panel.getByRole("button", { name: "Upload", exact: true })); - await expect(writeAffordance.first()).toBeVisible(); - }); - } - - test("Screenshots: sees the shared ROM section", async ({ page }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - await openTab(page, "Media"); - await openSubtab(page, "Screenshots"); - - await expect(visiblePanel(page).getByText("ROM screenshots")).toBeVisible(); - }); -}); - -// "All files" has no destination of its own, so it offers "Upload to folder"; -// a folder subtab offers Upload straight into that folder. -function uploadButton(page: Page): Locator { - return page.getByRole("button", { name: "Upload", exact: true }); -} - -function uploadToFolderButton(page: Page): Locator { - return page.getByRole("button", { name: "Upload to folder", exact: true }); -} - -test.describe("Files tab write affordances", () => { - test.describe("read-only user", () => { - test.use({ storageState: STORAGE_STATE.viewer }); - - test("gets no upload button", async ({ page }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - await openTab(page, "Files"); - - await expect(page.locator(".r-v2-subtab-nav__btn").first()).toBeVisible(); - await expect(uploadButton(page)).toHaveCount(0); - await expect(uploadToFolderButton(page)).toHaveCount(0); - }); - }); - - test.describe("admin", () => { - test.use({ storageState: STORAGE_STATE.admin }); - - test("gets Upload to folder from All files", async ({ page }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - await openTab(page, "Files"); - - await expect(uploadToFolderButton(page)).toBeVisible(); - await expect(uploadButton(page)).toHaveCount(0); - }); - - test("gets Upload from a folder subtab", async ({ page }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - await openTab(page, "Files"); - await page - .locator(".r-v2-subtab-nav__btn:not(.r-v2-subtab-nav__btn--active)") - .first() - .click(); - - await expect(uploadButton(page)).toBeVisible(); - await expect(uploadToFolderButton(page)).toHaveCount(0); - }); - }); -}); diff --git a/frontend/e2e/login.spec.ts b/frontend/e2e/login.spec.ts deleted file mode 100644 index 687d92325..000000000 --- a/frontend/e2e/login.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { expect, test } from "@playwright/test"; -import { PASSWORD, seedUiState, USERS } from "./fixtures/auth"; - -// The only spec that drives the login form. Every other spec starts from a -// session saved by auth.setup.ts, so this is the single place the form, the -// session cookie and the post-login redirect are actually exercised. -// -// It uses the default (unauthenticated) `page` fixture -- no -// `test.use({ storageState })` here, which is the whole point. -test.describe("Login", () => { - test("signs in and lands on the app", async ({ page }) => { - await seedUiState(page, "dark"); - await page.goto("/login"); - - const form = page.locator("form.r-v2-login-form"); - await form.locator('input[name="username"]').fill(USERS.viewer); - await form.locator('input[name="password"]').fill(PASSWORD); - await form.locator('button[type="submit"]').click(); - - // The app bar's user name only renders once the session is established and - // the auth store holds a user -- a stronger signal than "the URL changed". - await expect(page.locator(".r-v2-user__name")).toHaveText(USERS.viewer); - await expect(page).not.toHaveURL(/\/login/); - }); - - test("rejects a wrong password and stays put", async ({ page }) => { - await seedUiState(page, "dark"); - await page.goto("/login"); - - const form = page.locator("form.r-v2-login-form"); - await form.locator('input[name="username"]').fill(USERS.viewer); - await form.locator('input[name="password"]').fill("definitely-not-it"); - await form.locator('button[type="submit"]').click(); - - // Stays on /login with no session. Asserted via the app bar's absence - // rather than a snackbar, so the test doesn't depend on toast copy. - await expect(page.locator(".r-v2-user__name")).toHaveCount(0); - await expect(page).toHaveURL(/\/login/); - }); - - test("an unauthenticated visitor is redirected to login", async ({ - page, - }) => { - await seedUiState(page, "dark"); - await page.goto("/"); - - await expect(page).toHaveURL(/\/login/); - await expect(page.locator("form.r-v2-login-form")).toBeVisible(); - }); -}); diff --git a/frontend/e2e/profile-role.spec.ts b/frontend/e2e/profile-role.spec.ts deleted file mode 100644 index 923f9c646..000000000 --- a/frontend/e2e/profile-role.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { expect, test } from "@playwright/test"; -import { gotoOwnProfile, seedUiState, STORAGE_STATE } from "./fixtures/auth"; - -// Regression cover for #3954: the profile page shipped an editable role picker, -// but `update_user` ignores `role` on a self-edit. Saving reported success and -// then silently reverted on reload -- for admins as much as for regular users. -// The role is display-only now: the chip in the identity row. -// -// Sessions come from auth.setup.ts; see login.spec.ts for the form itself. -for (const role of ["viewer", "admin"] as const) { - test.describe(`Profile page role field (${role})`, () => { - test.use({ storageState: STORAGE_STATE[role] }); - - test("gets no editable role control", async ({ page }) => { - await seedUiState(page, "dark"); - await gotoOwnProfile(page); - - // The editable rows that SHOULD be there, so a blank page can't pass. - await expect(page.locator('input[type="email"]')).toBeVisible(); - - // No role row in the Account Details form. - const form = page.locator(".r-v2-section-stack"); - await expect(form.getByText("Role", { exact: true })).toHaveCount(0); - // And no select rendered anywhere on the page. - await expect(page.locator(".r-select")).toHaveCount(0); - }); - }); -} - -test.describe("Profile page role chip", () => { - test.use({ storageState: STORAGE_STATE.viewer }); - - test("still shows the role read-only", async ({ page }) => { - await seedUiState(page, "dark"); - await gotoOwnProfile(page); - - // Identity row keeps the role visible -- removing the picker must not - // remove the information. - const chip = page.locator(".r-v2-profile__role-tag"); - await expect(chip).toBeVisible(); - await expect(chip).toHaveText(/user/i); - }); -}); diff --git a/frontend/e2e/rom-actions.spec.ts b/frontend/e2e/rom-actions.spec.ts deleted file mode 100644 index 7f85e1a6c..000000000 --- a/frontend/e2e/rom-actions.spec.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { expect, test } from "@playwright/test"; -import { - gotoFirstRom, - menuLabels, - openMoreMenu, - seedUiState, - STORAGE_STATE, -} from "./fixtures/auth"; - -// Regression cover for #3954: the ⋯ menu offered Match / Refresh metadata / -// Edit / Delete to users with no ROM write grant. Those endpoints gate on -// ROMS_WRITE, so the click 403'd and the axios interceptor turned that into a -// logout -- the "page reloads back to the login page" in the bug report. -// -// Sessions come from auth.setup.ts; see login.spec.ts for the form itself. -const WRITE_ACTIONS = [ - "Match ROM", - "Refresh metadata", - "Edit", - "Delete", -] as const; - -test.describe("ROM more-actions menu (read-only user)", () => { - test.use({ storageState: STORAGE_STATE.viewer }); - - test("is offered no write or destructive action", async ({ page }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - await openMoreMenu(page); - - const labels = await menuLabels(page); - for (const action of WRITE_ACTIONS) { - expect(labels, `"${action}" must not be offered`).not.toContain(action); - } - // The actions they CAN perform are still there -- otherwise this spec would - // also pass against a menu that failed to render at all. - expect(labels).toContain("Download"); - expect(labels).toContain("Add to favorites"); - }); - - test("has no trailing separator", async ({ page }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - const panel = await openMoreMenu(page); - - // Hiding the metadata + destructive groups must hide their leading dividers - // too, or the menu ends in stray rules. One divider survives: the split - // between the primary and per-user groups. - await expect(panel.locator('[role="separator"]')).toHaveCount(1); - - // And the last thing in the panel is an item, not a rule. - const lastChildIsSeparator = await panel.evaluate((el) => { - const body = el.querySelector(".r-menu__body") ?? el; - const kids = Array.from(body.children).filter( - (c) => (c as HTMLElement).offsetParent !== null || c.clientHeight > 0, - ); - const last = kids[kids.length - 1]; - return last?.getAttribute("role") === "separator"; - }); - expect(lastChildIsSeparator).toBe(false); - }); - - test("renders in light theme too", async ({ page }) => { - await seedUiState(page, "light"); - await gotoFirstRom(page); - const panel = await openMoreMenu(page); - - await expect(panel).toBeVisible(); - const labels = await menuLabels(page); - expect(labels).not.toContain("Delete"); - expect(labels.length).toBeGreaterThan(0); - }); -}); - -test.describe("ROM more-actions menu (admin)", () => { - test.use({ storageState: STORAGE_STATE.admin }); - - test("still gets every action", async ({ page }) => { - await seedUiState(page, "dark"); - await gotoFirstRom(page); - const panel = await openMoreMenu(page); - - // `expect.poll` rather than a one-shot `menuLabels()` read: the menu is - // reactive, so items appear as grants resolve. Snapshotting the array once - // can capture the pre-grant menu and report a permissions bug that isn't. - for (const action of WRITE_ACTIONS) { - await expect - .poll(() => menuLabels(page), { - message: `"${action}" must still be offered to admins`, - }) - .toContain(action); - } - // Primary | per-user | metadata | destructive => three dividers. - await expect(panel.locator('[role="separator"]')).toHaveCount(3); - }); -}); diff --git a/frontend/e2e/setup/auth.setup.ts b/frontend/e2e/setup/auth.setup.ts new file mode 100644 index 000000000..f39a5a7bd --- /dev/null +++ b/frontend/e2e/setup/auth.setup.ts @@ -0,0 +1,32 @@ +import { + ACCOUNTS, + accountMenu, + fillLoginForm, + ROLES, + seedUiState, + STORAGE_STATE, +} from "../support/auth"; +import { expect, test as setup } from "../support/test"; + +// Signs each account in and saves its session, so specs start authenticated +// with `test.use({ storageState })`. login.spec.ts tests the form itself. +for (const role of ROLES) { + setup(`authenticate as ${role}`, async ({ page }) => { + // The first load can compile the app on a cold dev server. + setup.slow(); + const { username, password } = ACCOUNTS[role]; + + await seedUiState(page); + await page.goto("/login"); + const answered = page.waitForResponse( + (r) => r.url().endsWith("/api/login") && r.request().method() === "POST", + ); + await fillLoginForm(page, username, password); + const response = await answered; + expect(response.status(), `POST /api/login for ${username}`).toBe(200); + // The account menu takes the user's name once the session is established. + await expect(accountMenu(page, username)).toBeVisible(); + + await page.context().storageState({ path: STORAGE_STATE[role] }); + }); +} diff --git a/frontend/e2e/setup/library.setup.ts b/frontend/e2e/setup/library.setup.ts new file mode 100644 index 000000000..70ca4a50c --- /dev/null +++ b/frontend/e2e/setup/library.setup.ts @@ -0,0 +1,16 @@ +import { writeFileSync } from "node:fs"; +import { STORAGE_STATE } from "../support/auth"; +import { clickThroughToFirstRom, type Library } from "../support/navigation"; +import { LIBRARY_FILE } from "../support/output"; +import { expect, test as setup } from "../support/test"; + +// Finds the first game once, so specs open it by URL instead of each clicking +// through the platforms to reach it. +setup.use({ storageState: STORAGE_STATE.admin }); + +setup("find the first game", async ({ page }) => { + await clickThroughToFirstRom(page); + const library: Library = { firstRom: new URL(page.url()).pathname }; + expect(library.firstRom).toMatch(/^\/rom\/\d+$/); + writeFileSync(LIBRARY_FILE, JSON.stringify(library)); +}); diff --git a/frontend/e2e/specs/auth/login.spec.ts b/frontend/e2e/specs/auth/login.spec.ts new file mode 100644 index 000000000..fae786a58 --- /dev/null +++ b/frontend/e2e/specs/auth/login.spec.ts @@ -0,0 +1,51 @@ +import { + ACCOUNTS, + accountMenu, + fillLoginForm, + loginButton, + seedUiState, +} from "../../support/auth"; +import { expect, test } from "../../support/test"; + +// The only spec that drives the login form; the others reuse auth.setup.ts's +// sessions. It starts signed out, whatever sessions are saved. +test.use({ storageState: { cookies: [], origins: [] } }); + +test.describe("Login", () => { + test.beforeEach(async ({ page }) => { + await seedUiState(page); + }); + + test("signs in and lands on the app", async ({ page }) => { + const { username, password } = ACCOUNTS.viewer; + await page.goto("/login"); + + await fillLoginForm(page, username, password); + + // The account menu takes the user's name once the auth store holds one, + // which a URL change alone doesn't prove. + await expect(accountMenu(page, username)).toBeVisible(); + await expect(page).not.toHaveURL(/\/login/); + }); + + test("rejects a wrong password and stays put", async ({ page }) => { + const { username } = ACCOUNTS.viewer; + await page.goto("/login"); + + await fillLoginForm(page, username, "definitely-not-it"); + + // Stays on /login with no session. Asserted via the app bar's absence + // rather than a snackbar, so the test doesn't depend on toast copy. + await expect(accountMenu(page)).toHaveCount(0); + await expect(page).toHaveURL(/\/login/); + }); + + test("an unauthenticated visitor is redirected to login", async ({ + page, + }) => { + await page.goto("/"); + + await expect(page).toHaveURL(/\/login/); + await expect(loginButton(page)).toBeVisible(); + }); +}); diff --git a/frontend/e2e/specs/loads.spec.ts b/frontend/e2e/specs/loads.spec.ts new file mode 100644 index 000000000..a6a8c1a17 --- /dev/null +++ b/frontend/e2e/specs/loads.spec.ts @@ -0,0 +1,164 @@ +import type { Locator, Page, Request } from "@playwright/test"; +import { + ROUTE_SCOPES, + ROUTES, + type RouteName, +} from "../../src/plugins/routeNames"; +import { ROLES, STORAGE_STATE } from "../support/auth"; +import { + clickThroughToFirstRom, + gotoFirstPlatform, + gotoHydrated, + gotoOwnProfile, +} from "../support/navigation"; +import { expect, test } from "../support/test"; + +// Every page opens for each role allowed on it with each document and API +// response 2xx, and a viewer gets the 404 page on admin-only ones. + +/** Opened by URL, or by clicking through when the URL holds an id. */ +type Opener = string | ((page: Page) => Promise); + +type PageDef = { open: Opener } | { skip: string }; + +// Scope-gated routes the seeded Viewer group still opens. Every other route in +// ROUTE_SCOPES is admin-only, so a newly gated route gets the viewer 404 check. +const VIEWER_OPENS: ReadonlySet = new Set([ + ROUTES.CLIENT_API_TOKENS, + ROUTES.DEVICES, +]); + +function isAdminOnly(name: RouteName): boolean { + return name in ROUTE_SCOPES && !VIEWER_OPENS.has(name); +} + +// Keyed by every route the router knows, so a new route fails the typecheck +// until it is listed here or skipped with a reason. +const PAGES: Record = { + [ROUTES.HOME]: { open: "/" }, + [ROUTES.PLATFORMS_INDEX]: { open: "/platforms" }, + [ROUTES.PLATFORM]: { open: gotoFirstPlatform }, + [ROUTES.COLLECTIONS_INDEX]: { open: "/collections" }, + [ROUTES.SEARCH]: { open: "/search" }, + [ROUTES.MUSIC]: { open: "/music" }, + [ROUTES.ROM]: { open: clickThroughToFirstRom }, + [ROUTES.SCAN]: { open: "/scan" }, + [ROUTES.UPLOAD]: { open: "/upload" }, + [ROUTES.ACTIVITY]: { open: "/activity" }, + [ROUTES.NOTIFICATIONS]: { open: "/notifications" }, + [ROUTES.USER_PROFILE]: { open: gotoOwnProfile }, + [ROUTES.USER_INTERFACE]: { open: "/user-interface" }, + [ROUTES.LIBRARY_MANAGEMENT]: { open: "/library-management" }, + [ROUTES.SCAN_SETTINGS]: { open: "/scan-settings" }, + [ROUTES.CONVERSION_SETTINGS]: { open: "/conversion-settings" }, + [ROUTES.METADATA_SOURCES]: { open: "/metadata-sources" }, + [ROUTES.CLIENT_API_TOKENS]: { open: "/client-api-tokens" }, + [ROUTES.DEVICES]: { open: "/devices" }, + [ROUTES.ADMINISTRATION]: { open: "/administration" }, + [ROUTES.SERVER_STATS]: { open: "/server-stats" }, + [ROUTES.LOGS]: { open: "/logs" }, + [ROUTES.CONTROLLER_DEBUG]: { open: "/controller-debug" }, + + [ROUTES.MAIN]: { skip: "the layout around the pages listed here" }, + [ROUTES.SETUP]: { skip: "only reachable before the first account exists" }, + [ROUTES.LOGIN]: { skip: "signed out; login.spec.ts covers it" }, + [ROUTES.RESET_PASSWORD]: { skip: "signed out, and needs a reset token" }, + [ROUTES.REGISTER]: { skip: "signed out, and needs an invite token" }, + [ROUTES.COLLECTION]: { skip: "needs a collection the library may lack" }, + [ROUTES.VIRTUAL_COLLECTION]: { skip: "needs a virtual collection" }, + [ROUTES.SMART_COLLECTION]: { skip: "needs a smart collection" }, + [ROUTES.EMULATORJS]: { skip: "a player: needs a game it can run" }, + [ROUTES.JSDOS]: { skip: "a player: needs a game it can run" }, + [ROUTES.PICO8]: { skip: "a player: needs a game it can run" }, + [ROUTES.EASYRPG]: { skip: "a player: needs a game it can run" }, + [ROUTES.RUFFLE]: { skip: "a player: needs a game it can run" }, + [ROUTES.STREAM]: { skip: "needs a streaming host" }, + [ROUTES.STREAM_DESKTOP]: { skip: "needs a streaming host" }, + [ROUTES.PAIR]: { skip: "needs a second device" }, + [ROUTES.PAIR_DEVICE]: { skip: "needs a second device" }, + [ROUTES.APRIL_FOOLS]: { skip: "an easter egg" }, + [ROUTES.CONSOLE_HOME]: { skip: "console mode, part of the frozen v1 UI" }, + [ROUTES.CONSOLE_PLATFORM]: { skip: "console mode, part of the v1 UI" }, + [ROUTES.CONSOLE_COLLECTION]: { skip: "console mode, part of the v1 UI" }, + [ROUTES.CONSOLE_SMART_COLLECTION]: { skip: "console mode, part of v1" }, + [ROUTES.CONSOLE_VIRTUAL_COLLECTION]: { skip: "console mode, part of v1" }, + [ROUTES.CONSOLE_ROM]: { skip: "console mode, part of the v1 UI" }, + [ROUTES.CONSOLE_PLAY]: { skip: "console mode, part of the v1 UI" }, + [ROUTES.NOT_FOUND]: { skip: "the viewer checks on admin-only pages" }, +}; + +/** A request the page's load depends on: a document or an API call. */ +function isLoadRequest(request: Request) { + return ( + request.isNavigationRequest() || + new URL(request.url()).pathname.startsWith("/api/") + ); +} + +function notFoundHeading(page: Page): Locator { + return page.getByRole("heading", { name: "Page not found" }); +} + +async function expectPageLoads(page: Page, name: string, open: Opener) { + const failed: string[] = []; + page.on("response", (response) => { + if (isLoadRequest(response.request()) && !response.ok()) { + const { pathname } = new URL(response.url()); + failed.push( + `${response.request().method()} ${pathname} returned ${response.status()}`, + ); + } + }); + + if (typeof open === "string") { + await gotoHydrated(page, open); + // A route guard that bounced us elsewhere (home, login) fails here. + await expect(page).toHaveURL( + (url) => url.pathname === open || url.pathname.startsWith(`${open}/`), + ); + } else { + await open(page); + } + + // The router-view's content, which exists only once the lazy view resolves. + await expect( + page.getByRole("main").locator(":scope > *").first(), + ).toBeVisible(); + await expect(notFoundHeading(page)).toHaveCount(0); + expect( + failed, + `Responses that failed while loading ${name} (a 404 from /api usually means the site's backend is older than this branch)`, + ).toEqual([]); +} + +for (const [name, def] of Object.entries(PAGES) as [RouteName, PageDef][]) { + if ("skip" in def) continue; + const { open } = def; + const adminOnly = isAdminOnly(name); + if (adminOnly && typeof open !== "string") { + throw new Error(`${name} is admin-only, so it needs a URL for the viewer.`); + } + + test.describe(name, { tag: `@page:${name}` }, () => { + for (const role of adminOnly ? (["admin"] as const) : ROLES) { + test.describe(role, () => { + test.use({ storageState: STORAGE_STATE[role] }); + + test("loads", async ({ page }) => { + await expectPageLoads(page, name, open); + }); + }); + } + + if (adminOnly && typeof open === "string") { + test.describe("viewer", () => { + test.use({ storageState: STORAGE_STATE.viewer }); + + test("gets the 404 page", async ({ page }) => { + await gotoHydrated(page, open); + await expect(notFoundHeading(page)).toBeVisible(); + }); + }); + } + }); +} diff --git a/frontend/e2e/specs/rom/actions-menu.spec.ts b/frontend/e2e/specs/rom/actions-menu.spec.ts new file mode 100644 index 000000000..fbe42d182 --- /dev/null +++ b/frontend/e2e/specs/rom/actions-menu.spec.ts @@ -0,0 +1,99 @@ +import type { Locator, Page } from "@playwright/test"; +import { STORAGE_STATE } from "../../support/auth"; +import { gotoFirstRom } from "../../support/navigation"; +import { expect, test } from "../../support/test"; + +// A viewer's ⋯ menu offers no ROMS_WRITE action: the 403 it would hit logs +// them out (#3954). +const WRITE_ACTIONS = [ + "Match ROM", + "Refresh metadata", + "Edit", + "Delete", +] as const; + +/** Open the ⋯ more-actions menu and return its teleported panel. */ +async function openMoreMenu(page: Page) { + await page.getByRole("button", { name: "More actions" }).first().click(); + const panel = page.getByRole("menu"); + await expect(panel).toBeVisible(); + return panel; +} + +/** Labels of the open menu's items, in DOM order. */ +function menuLabels(panel: Locator): Promise { + return panel.getByRole("menuitem").allInnerTexts(); +} + +test.describe( + "ROM more-actions menu (read-only user)", + { tag: "@page:rom" }, + () => { + test.use({ storageState: STORAGE_STATE.viewer }); + + test("is offered no write or destructive action", async ({ page }) => { + await gotoFirstRom(page); + const panel = await openMoreMenu(page); + + const labels = await menuLabels(panel); + for (const action of WRITE_ACTIONS) { + expect(labels, `"${action}" must not be offered`).not.toContain(action); + } + // Their own actions stay, so a menu that failed to render can't pass. + expect(labels).toContain("Download"); + expect(labels).toContain("Add to favorites"); + }); + + test("has no trailing separator", async ({ page }) => { + await gotoFirstRom(page); + const panel = await openMoreMenu(page); + + // Hidden groups take their leading dividers with them; only the one + // between the primary and per-user groups remains. + await expect(panel.getByRole("separator")).toHaveCount(1); + + // And the last thing in the panel is an item, not a rule. + const lastChildIsSeparator = await panel.evaluate((el) => { + const body = el.querySelector(".r-menu__body") ?? el; + const kids = Array.from(body.children).filter( + (c) => (c as HTMLElement).offsetParent !== null || c.clientHeight > 0, + ); + const last = kids[kids.length - 1]; + return last?.getAttribute("role") === "separator"; + }); + expect(lastChildIsSeparator).toBe(false); + }); + + test("renders in light theme too", async ({ page }) => { + await page.emulateMedia({ colorScheme: "light" }); + await gotoFirstRom(page); + await expect(page.locator("html")).toHaveClass(/\br-v2-light\b/); + const panel = await openMoreMenu(page); + + const labels = await menuLabels(panel); + expect(labels).not.toContain("Delete"); + expect(labels.length).toBeGreaterThan(0); + }); + }, +); + +test.describe("ROM more-actions menu (admin)", { tag: "@page:rom" }, () => { + test.use({ storageState: STORAGE_STATE.admin }); + + test("still gets every action", async ({ page }) => { + await gotoFirstRom(page); + const panel = await openMoreMenu(page); + + // Polled: items appear as grants resolve, so a single read can catch the + // menu before they do. + for (const action of WRITE_ACTIONS) { + await expect + .poll(() => menuLabels(panel), { + message: `"${action}" must still be offered to admins`, + }) + .toContain(action); + } + // Primary | per-user | metadata | destructive => three dividers. + await expect(panel.getByRole("separator")).toHaveCount(3); + }); +}); diff --git a/frontend/e2e/specs/rom/media-and-files.spec.ts b/frontend/e2e/specs/rom/media-and-files.spec.ts new file mode 100644 index 000000000..7cc16d1d5 --- /dev/null +++ b/frontend/e2e/specs/rom/media-and-files.spec.ts @@ -0,0 +1,139 @@ +import type { Locator, Page } from "@playwright/test"; +import { STORAGE_STATE } from "../../support/auth"; +import { gotoFirstRom } from "../../support/navigation"; +import { expect, test } from "../../support/test"; + +// A viewer gets no ROMS_WRITE upload or delete on the Media and Files tabs. +// "My screenshots" writes the user's own assets, so it stays. + +async function openTab(page: Page, tab: string) { + await page.getByRole("tab", { name: tab }).click(); +} + +/** The tab's vertical subtab rail, apart from the page's top-level tabs. */ +function subtabs(page: Page): Locator { + return page.locator('[role="tablist"][aria-orientation="vertical"]'); +} + +/** Open a Media subtab of the first game and return its panel. */ +async function openMediaSubtab(page: Page, subtab: string): Promise { + await gotoFirstRom(page); + await openTab(page, "Media"); + await subtabs(page).getByRole("tab", { name: subtab }).click(); + return page.getByRole("tabpanel", { name: subtab }); +} + +function uploadButton(scope: Page | Locator): Locator { + return scope.getByRole("button", { name: "Upload", exact: true }); +} + +function uploadToFolderButton(scope: Page | Locator): Locator { + return scope.getByRole("button", { name: "Upload to folder", exact: true }); +} + +// Both panels whose upload path is ROM-scoped, so both must be inert. +const ROM_SCOPED_SUBTABS = [ + ["Manual", "No manual yet"], + ["Soundtrack", "No soundtrack yet"], +] as const; + +test.describe( + "Media tab write affordances (read-only user)", + { tag: "@page:rom" }, + () => { + test.use({ storageState: STORAGE_STATE.viewer }); + + for (const [subtab, emptyText] of ROM_SCOPED_SUBTABS) { + test(`${subtab}: gets the empty state, not a dropzone`, async ({ + page, + }) => { + const panel = await openMediaSubtab(page, subtab); + // The plain REmptyState replaces the dropzone: same message, no CTA, + // no drag-and-drop hint, no Upload button. + await expect(panel.getByText(emptyText)).toBeVisible(); + await expect(panel.locator(".r-dropzone__cta")).toHaveCount(0); + await expect( + panel.getByText("Drag and drop, or click to browse"), + ).toHaveCount(0); + await expect(uploadButton(panel)).toHaveCount(0); + }); + } + + test("Screenshots: the shared ROM section is hidden but the per-user one stays writable", async ({ + page, + }) => { + const panel = await openMediaSubtab(page, "Screenshots"); + // Shared section writes to the ROM: gone for a read-only user with nothing + // to show. + await expect(panel.getByText("ROM screenshots")).toHaveCount(0); + // Per-user section writes user assets: must survive, dropzone included. + // Hiding this would be the regression in the opposite direction. + await expect(panel.getByText("My screenshots")).toBeVisible(); + await expect(panel.locator(".r-dropzone__cta")).not.toHaveCount(0); + }); + }, +); + +test.describe( + "Media tab write affordances (admin)", + { tag: "@page:rom" }, + () => { + test.use({ storageState: STORAGE_STATE.admin }); + + for (const [subtab] of ROM_SCOPED_SUBTABS) { + test(`${subtab}: still gets the dropzone`, async ({ page }) => { + const panel = await openMediaSubtab(page, subtab); + // Empty ROM shows the dropzone, a populated one the Upload button. + // `.or()` auto-waits; `count()` reads 0 before the async panel mounts. + const writeAffordance = panel + .locator(".r-dropzone__cta") + .or(uploadButton(panel)); + await expect(writeAffordance.first()).toBeVisible(); + }); + } + + test("Screenshots: sees the shared ROM section", async ({ page }) => { + const panel = await openMediaSubtab(page, "Screenshots"); + + await expect(panel.getByText("ROM screenshots")).toBeVisible(); + }); + }, +); + +// "All files" has no destination of its own, so it offers "Upload to folder"; +// a folder subtab offers Upload straight into that folder. +test.describe("Files tab write affordances", { tag: "@page:rom" }, () => { + test.describe("read-only user", () => { + test.use({ storageState: STORAGE_STATE.viewer }); + + test("gets no upload button", async ({ page }) => { + await gotoFirstRom(page); + await openTab(page, "Files"); + + await expect(subtabs(page).getByRole("tab").first()).toBeVisible(); + await expect(uploadButton(page)).toHaveCount(0); + await expect(uploadToFolderButton(page)).toHaveCount(0); + }); + }); + + test.describe("admin", () => { + test.use({ storageState: STORAGE_STATE.admin }); + + test("gets Upload to folder from All files", async ({ page }) => { + await gotoFirstRom(page); + await openTab(page, "Files"); + + await expect(uploadToFolderButton(page)).toBeVisible(); + await expect(uploadButton(page)).toHaveCount(0); + }); + + test("gets Upload from a folder subtab", async ({ page }) => { + await gotoFirstRom(page); + await openTab(page, "Files"); + await subtabs(page).getByRole("tab", { selected: false }).first().click(); + + await expect(uploadButton(page)).toBeVisible(); + await expect(uploadToFolderButton(page)).toHaveCount(0); + }); + }); +}); diff --git a/frontend/e2e/specs/user-profile/role.spec.ts b/frontend/e2e/specs/user-profile/role.spec.ts new file mode 100644 index 000000000..ccb05b3db --- /dev/null +++ b/frontend/e2e/specs/user-profile/role.spec.ts @@ -0,0 +1,41 @@ +import { ROLES, STORAGE_STATE } from "../../support/auth"; +import { gotoOwnProfile } from "../../support/navigation"; +import { expect, test } from "../../support/test"; + +// A self-edit can't change the role, so the profile shows it read-only (#3954). +for (const role of ROLES) { + test.describe( + `Profile page role field (${role})`, + { tag: "@page:user-profile" }, + () => { + test.use({ storageState: STORAGE_STATE[role] }); + + test("gets no editable role control", async ({ page }) => { + await gotoOwnProfile(page); + + // The editable rows that SHOULD be there, so a blank page can't pass. + await expect( + page.getByRole("textbox", { name: "Email" }), + ).toBeVisible(); + + // No role row, and no select (RSelect's listbox trigger) on the page. + const main = page.getByRole("main"); + await expect(main.getByText("Role", { exact: true })).toHaveCount(0); + await expect(main.locator('[aria-haspopup="listbox"]')).toHaveCount(0); + }); + }, + ); +} + +test.describe("Profile page role chip", { tag: "@page:user-profile" }, () => { + test.use({ storageState: STORAGE_STATE.viewer }); + + test("still shows the role read-only", async ({ page }) => { + await gotoOwnProfile(page); + + // The identity row still shows the role the picker no longer edits. + const chip = page.locator(".r-v2-profile__role-tag"); + await expect(chip).toBeVisible(); + await expect(chip).toHaveText(/user/i); + }); +}); diff --git a/frontend/e2e/support/auth.ts b/frontend/e2e/support/auth.ts new file mode 100644 index 000000000..4cb99d4c4 --- /dev/null +++ b/frontend/e2e/support/auth.ts @@ -0,0 +1,74 @@ +import type { Locator, Page } from "@playwright/test"; +import { AUTH_DIR } from "./output"; + +const { env } = process; + +// The seed script sets both accounts' password from E2E_PASSWORD. +const SEEDED_PASSWORD = env.E2E_PASSWORD || "e2e-Passw0rd!"; + +// The accounts every permission assertion is made against. The defaults are +// the ones .github/scripts/seed_e2e_users.py creates. +export const ACCOUNTS = { + admin: { + username: env.E2E_ADMIN_USERNAME || "e2e_admin", + password: env.E2E_ADMIN_PASSWORD || SEEDED_PASSWORD, + }, + viewer: { + username: env.E2E_VIEWER_USERNAME || "e2e_viewer", + password: env.E2E_VIEWER_PASSWORD || SEEDED_PASSWORD, + }, +}; + +export type Role = keyof typeof ACCOUNTS; + +export const ROLES = Object.keys(ACCOUNTS) as Role[]; + +/** Where auth.setup.ts saves each role's session (gitignored: live cookies). */ +export const STORAGE_STATE = Object.fromEntries( + ROLES.map((role) => [role, `${AUTH_DIR}/${role}.json`]), +) as Record; + +/** The login form's submit button. Roles skip the hidden reset-password form, + * which has a Username field of its own. */ +export function loginButton(page: Page): Locator { + return page.getByRole("button", { name: "Login", exact: true }); +} + +/** The app bar's account menu, labelled with the signed-in user's name (any + * user's when none is given). It reads "Guest" until the session loads. */ +export function accountMenu(page: Page, username?: string): Locator { + const user = username ? RegExp.escape(username) : "(?!Guest$).+"; + return page.getByRole("button", { + name: new RegExp(`^Account menu for ${user}$`, "i"), + }); +} + +/** Fill and submit the login form. */ +export async function fillLoginForm( + page: Page, + username: string, + password: string, +) { + await page.getByRole("textbox", { name: "Username" }).fill(username); + await page.getByLabel("Password", { exact: true }).fill(password); + await loginButton(page).click(); +} + +/** Force the v2 UI before the app boots, and the "auto" theme, so the + * browser's `colorScheme` picks it and the account never stores another. */ +export async function seedUiState(page: Page) { + await page.addInitScript(() => { + // Init scripts also run in Chrome's own error page, which denies storage. + if (!location.protocol.startsWith("http")) return; + const seeded = { "settings.uiVersion": "v2", "settings.theme": "auto" }; + // The app only adopts an unscoped value when the signed-in user has no + // `user::` copy, and a saved session carries one. + for (const key of Object.keys(localStorage)) { + const scoped = /^user:\d+:(.+)$/.exec(key)?.[1]; + if (scoped && Object.hasOwn(seeded, scoped)) localStorage.removeItem(key); + } + for (const [key, value] of Object.entries(seeded)) { + localStorage.setItem(key, value); + } + }); +} diff --git a/frontend/e2e/support/navigation.ts b/frontend/e2e/support/navigation.ts new file mode 100644 index 000000000..3fe66e0b0 --- /dev/null +++ b/frontend/e2e/support/navigation.ts @@ -0,0 +1,72 @@ +import type { Page } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import { accountMenu, loginButton } from "./auth"; +import { LIBRARY_FILE } from "./output"; +import { expect } from "./test"; + +/** What library.setup.ts finds in the site's library, once per run. */ +export interface Library { + firstRom: string; +} + +/** `page.goto` that also waits for `/api/permissions/me`, before which even an + * admin sees every gated control hidden. */ +export async function gotoHydrated(page: Page, path: string) { + // Armed before page.goto, so the test's timeout bounds these waits: an + // action timeout would count the page load against them. + const hydrated = page.waitForResponse( + (r) => r.url().includes("/api/permissions/me"), + { timeout: 0 }, + ); + await page.goto(path); + // A rejected session lands on /login, which never requests permissions. + const loginShown = loginButton(page).waitFor({ timeout: 0 }); + const response = await Promise.race([hydrated, loginShown.then(() => null)]); + if (!response) { + throw new Error( + `Opened ${path} but landed on the login page: the backend rejected this test's saved session.`, + ); + } + if (!response.ok()) { + throw new Error( + `Permissions didn't load (GET /api/permissions/me returned ${response.status()}). The backend most likely rejected this test's saved session.`, + ); + } + // Named after the user once the auth store holds one: the app shell is ready. + await expect(accountMenu(page)).toBeVisible(); +} + +/** Open the first platform on the platforms index. */ +export async function gotoFirstPlatform(page: Page) { + await gotoHydrated(page, "/platforms"); + const platform = page.locator('a[href^="/platform/"]').first(); + await expect( + platform, + "No platform with games on /platforms: the site's library is empty or unscanned", + ).toBeVisible(); + await platform.click(); + await expect(page).toHaveURL(/\/platform\/\d+/); +} + +/** Click through to the first game of the first platform. */ +export async function clickThroughToFirstRom(page: Page) { + await gotoFirstPlatform(page); + const game = page.locator("a[data-rom-id]").first(); + await expect(game, "The first platform shows no games").toBeVisible(); + await game.click(); + await expect(page).toHaveURL(/\/rom\/\d+/); +} + +/** Open the game library.setup.ts found, by its URL. */ +export async function gotoFirstRom(page: Page) { + const library = JSON.parse(readFileSync(LIBRARY_FILE, "utf8")) as Library; + await gotoHydrated(page, library.firstRom); +} + +/** Open the account menu and follow its Profile link (route `/user/:user`). */ +export async function gotoOwnProfile(page: Page) { + await gotoHydrated(page, "/"); + await accountMenu(page).click(); + await page.getByRole("menuitem", { name: "Profile" }).click(); + await expect(page).toHaveURL(/\/user\/\d+/); +} diff --git a/frontend/e2e/support/output.ts b/frontend/e2e/support/output.ts new file mode 100644 index 000000000..9cff8499f --- /dev/null +++ b/frontend/e2e/support/output.ts @@ -0,0 +1,17 @@ +import { fileURLToPath } from "node:url"; + +// Everything the Playwright suite writes lives under e2e/.output/ (gitignored), +// so deleting that one folder resets every run. +const OUTPUT_DIR = fileURLToPath(new URL("../.output/", import.meta.url)); + +/** Per-test traces and screenshots. */ +export const RESULTS_DIR = `${OUTPUT_DIR}specs/results`; + +/** The HTML report: `npm run test:e2e:report`. */ +export const REPORT_DIR = `${OUTPUT_DIR}specs/report`; + +/** Saved sign-in sessions (live cookies). */ +export const AUTH_DIR = `${OUTPUT_DIR}auth`; + +/** The library facts library.setup.ts resolves for the specs. */ +export const LIBRARY_FILE = `${OUTPUT_DIR}library.json`; diff --git a/frontend/e2e/support/test.ts b/frontend/e2e/support/test.ts new file mode 100644 index 000000000..167bcdb10 --- /dev/null +++ b/frontend/e2e/support/test.ts @@ -0,0 +1,37 @@ +import { test as base, expect } from "@playwright/test"; + +// Browser noise that isn't an app failure. +const BENIGN_PAGE_ERRORS = [/ResizeObserver loop/]; + +/** `test` with a guard that fails any test the moment the app itself fails. */ +export const test = base.extend<{ appErrorGuard: void }>({ + // An /api 5xx or an uncaught exception otherwise surfaces as a locator + // timeout later, blaming an element. Closing the page fails the wait at once. + appErrorGuard: [ + async ({ page }, use) => { + const errors: string[] = []; + const fail = (message: string) => { + errors.push(message); + void page.close(); + }; + page.on("response", (response) => { + const { pathname } = new URL(response.url()); + if (pathname.startsWith("/api/") && response.status() >= 500) { + const method = response.request().method(); + fail(`${method} ${pathname} returned ${response.status()}`); + } + }); + page.on("pageerror", (error) => { + if (BENIGN_PAGE_ERRORS.some((re) => re.test(error.message))) return; + fail(`Uncaught error in the app: ${error.message}`); + }); + + await use(); + + expect(errors, "The app failed while this test ran").toEqual([]); + }, + { auto: true }, + ], +}); + +export { expect }; diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js index 2e2d77bbc..c4bd32a68 100644 --- a/frontend/eslint.config.js +++ b/frontend/eslint.config.js @@ -7,6 +7,7 @@ import vuea11y from "eslint-plugin-vuejs-accessibility"; import globals from "globals"; import tseslint from "typescript-eslint"; import romm from "./eslint-plugin-romm/index.js"; +import e2eConfig from "./eslint.e2e.config.js"; // Heavy modules that belong in a lazy chunk; add the next one here. const heavyImports = [ @@ -82,6 +83,7 @@ export default tseslint.config( "dev-dist/**", "storybook-static/**", "coverage/**", + "e2e/.output/**", ], }, { @@ -369,6 +371,8 @@ export default tseslint.config( ], }, }, + // After the base configs, so its exceptions win. + ...e2eConfig, // Keep last: Prettier owns formatting, so this switches off every // stylistic rule the two tools would otherwise fight over. prettierConfig, diff --git a/frontend/eslint.e2e.config.js b/frontend/eslint.e2e.config.js new file mode 100644 index 000000000..d9722cf10 --- /dev/null +++ b/frontend/eslint.e2e.config.js @@ -0,0 +1,69 @@ +// ESLint rules for the Playwright suite, each with a one-line reason. +import playwright from "eslint-plugin-playwright"; + +const TEST_FILES = ["e2e/**/*.ts"]; + +/** @type {import("eslint").Linter.Config[]} */ +export default [ + { + // Missing awaits, focused tests, page.pause(), fixed sleeps, non-retrying + // assertions, and the rest of the plugin's recommended set. + name: "e2e/playwright", + ...playwright.configs["flat/recommended"], + files: TEST_FILES, + }, + { + name: "e2e/rules", + files: TEST_FILES, + languageOptions: { + // Type info for no-floating-promises. Resolves to tsconfig.node.json, so + // the app's lint stays untyped. + parserOptions: { projectService: true }, + }, + rules: { + // An `expectSomething()` helper asserts on the test's behalf. + "playwright/expect-expect": [ + "warn", + { assertFunctionPatterns: ["^expect[A-Z]"] }, + ], + // An un-awaited helper lets a test pass without checking; the plugin's + // own await rule only knows Playwright's calls. + "@typescript-eslint/no-floating-promises": "error", + // Tests act through the UI and observe the app's own traffic. + "no-restricted-syntax": [ + "error", + { + // fetch, or any `.request` that isn't called (page.request, + // page.context().request); response.request() reads one the app made. + selector: + "CallExpression[callee.name='fetch'], MemberExpression[property.name='request']:not(CallExpression > MemberExpression.callee), ObjectPattern > Property[key.name='request'], ImportDeclaration[source.value='@playwright/test'] > ImportSpecifier[imported.name='request']", + message: + "Tests don't call the API: drive the UI, and observe the app's traffic with page.waitForResponse().", + }, + ], + }, + }, + { + name: "e2e/imports", + files: TEST_FILES, + // test.ts builds the suite's `test` from the stock one. + ignores: ["e2e/support/test.ts"], + rules: { + // The stock `test` lacks the app-error guard. + "@typescript-eslint/no-restricted-imports": [ + "error", + { + paths: [ + { + name: "@playwright/test", + importNames: ["test", "expect"], + allowTypeImports: true, + message: + "Import `test` and `expect` from e2e/support/test.ts, so the app-error guard applies.", + }, + ], + }, + ], + }, + }, +]; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index ca857127d..ae30e18db 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -61,6 +61,7 @@ "eslint-config-prettier": "^10.1.8", "eslint-import-resolver-typescript": "^4.4.5", "eslint-plugin-import-x": "^4.17.1", + "eslint-plugin-playwright": "^2.12.0", "eslint-plugin-vue": "^10.8.0", "eslint-plugin-vuejs-accessibility": "^2.5.0", "fake-indexeddb": "^6.2.5", @@ -68,6 +69,7 @@ "happy-dom": "^20.9.0", "openapi-typescript-codegen": "^0.29.0", "postcss": "^8.5.23", + "sirv": "^3.0.2", "storybook": "^10.2.19", "tsx": "^4.21.0", "typescript": "^6.0.3", @@ -8307,6 +8309,22 @@ } } }, + "node_modules/eslint-plugin-playwright": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-playwright/-/eslint-plugin-playwright-2.12.0.tgz", + "integrity": "sha512-7HpSKR/D2oCH4RKRauFskcrnDrHvLQKopW7Nen8lqrFZtx/SB+FgqVaH+zyQd32noZSZy9Lrsa+DsYrVUpn6hg==", + "dev": true, + "license": "MIT", + "dependencies": { + "globals": "^17.3.0" + }, + "engines": { + "node": ">=16.9.0" + }, + "peerDependencies": { + "eslint": ">=8.40.0" + } + }, "node_modules/eslint-plugin-vue": { "version": "10.11.1", "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-10.11.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 8308ba52a..37597c263 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -36,7 +36,8 @@ "storybook:build": "storybook build", "storybook:test": "vitest run test/storybook.test.ts", "test:e2e": "playwright test", - "test:e2e:ui": "playwright test --ui" + "test:e2e:ui": "playwright test --ui", + "test:e2e:report": "playwright show-report e2e/.output/specs/report" }, "dependencies": { "@floating-ui/vue": "^2.0.0", @@ -91,6 +92,7 @@ "eslint-config-prettier": "^10.1.8", "eslint-import-resolver-typescript": "^4.4.5", "eslint-plugin-import-x": "^4.17.1", + "eslint-plugin-playwright": "^2.12.0", "eslint-plugin-vue": "^10.8.0", "eslint-plugin-vuejs-accessibility": "^2.5.0", "fake-indexeddb": "^6.2.5", @@ -98,6 +100,7 @@ "happy-dom": "^20.9.0", "openapi-typescript-codegen": "^0.29.0", "postcss": "^8.5.23", + "sirv": "^3.0.2", "storybook": "^10.2.19", "tsx": "^4.21.0", "typescript": "^6.0.3", diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 9a014275b..64ada71c6 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -1,79 +1,98 @@ import { defineConfig, devices } from "@playwright/test"; +import { url as inspectorUrl } from "node:inspector"; +import { REPORT_DIR, RESULTS_DIR } from "./e2e/support/output"; + +// End-to-end suite: `npm run test:e2e`. Variables come from the shell, then +// e2e/.env, which tools like the VS Code extension can't take from a terminal. +try { + process.loadEnvFile(new URL("./e2e/.env", import.meta.url)); +} catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; +} +// Unset or empty, the config serves this checkout itself at SERVED_URL (see +// webServer). +const baseURL = process.env.E2E_BASE_URL || undefined; +const SERVED_PORT = 3000; +const SERVED_URL = `http://127.0.0.1:${SERVED_PORT}`; + +const isCI = !!process.env.CI; +// Playwright lifts timeouts itself for `--debug` (PWDEBUG, where 0 or false +// means off), not for a debugger paused on a breakpoint. +const { PWDEBUG = "" } = process.env; +const debugging = + !["", "0", "false"].includes(PWDEBUG) || inspectorUrl() !== undefined; +// 0 means no timeout. +const TIMEOUTS = debugging + ? { test: 0, expect: 0, action: 0, navigation: 0 } + : { test: 45_000, expect: 10_000, action: 15_000, navigation: 30_000 }; -// End-to-end suite. -// uv run python .github/scripts/seed_e2e_users.py # once, from the repo root -// npm run test:e2e export default defineConfig({ - testDir: "./e2e", + testDir: "./e2e/specs", + outputDir: RESULTS_DIR, // Permission gating is global state on the server (the fixture users' grants), // so the specs read it rather than mutate it and are safe to parallelise. fullyParallel: true, - forbidOnly: !!process.env.CI, - retries: process.env.CI ? 2 : 1, - // Every worker logs in and hammers ONE dev server, whose on-demand Vite - // transforms are the bottleneck. Too many workers turns real passes into - // timeouts, so keep the pool small. - workers: Number(process.env.E2E_WORKERS ?? 2), - reporter: process.env.CI ? "github" : "list", - timeout: 45_000, - expect: { timeout: 10_000 }, + forbidOnly: isCI, + // Locally a failure shows on the first run; retries would hide it. + retries: isCI ? 2 : 0, + // Every worker hammers ONE server, so keep the pool small. + workers: 2, + // The HTML report holds each failure's trace: `npm run test:e2e:report`. + reporter: [ + [isCI ? "github" : "list"], + ["html", { outputFolder: REPORT_DIR, open: "never" }], + ], + // A test that genuinely needs longer calls `test.slow()`. + timeout: TIMEOUTS.test, + expect: { timeout: TIMEOUTS.expect }, use: { - baseURL: process.env.E2E_BASE_URL ?? "http://localhost:3000", + ...devices["Desktop Chrome"], + baseURL: baseURL ?? SERVED_URL, trace: "retain-on-failure", screenshot: "only-on-failure", - actionTimeout: 15_000, - navigationTimeout: 30_000, - // The production build ships a PWA service worker that precaches ~9MB on - // first load. Every test gets a fresh context, so that install would run - // over and over, competing with the app for the first navigation, and its - // cache makes runs non-deterministic. Nothing here tests offline support. + actionTimeout: TIMEOUTS.action, + navigationTimeout: TIMEOUTS.navigation, + // The PWA service worker precaches ~9MB on every fresh context, competing + // with the first navigation. Nothing here tests offline support. serviceWorkers: "block", + // The suite's theme is "auto" (see seedUiState), so this picks it. + colorScheme: "dark", }, projects: [ - // Logs each fixture user in once and saves the session; every spec then - // starts authenticated via `test.use({ storageState })` instead of driving - // the login form again. login.spec.ts is the one place the form itself is - // exercised, and it opts out by using a fresh page. + // Signs each fixture user in and saves the session (auth.setup.ts); specs + // pick one with `test.use({ storageState })`. { name: "setup", - testMatch: /.*\.setup\.ts/, - use: { ...devices["Desktop Chrome"] }, + testDir: "./e2e/setup", + testMatch: "auth.setup.ts", + // A cold dev server can reload the page mid-sign-in. + retries: 2, + }, + // Finds the first game once, with the admin's session (library.setup.ts). + { + name: "library", + testDir: "./e2e/setup", + testMatch: "library.setup.ts", + dependencies: ["setup"], + retries: 2, }, { name: "chromium", - testIgnore: /.*\.setup\.ts/, - use: { ...devices["Desktop Chrome"] }, - dependencies: ["setup"], + dependencies: ["library"], }, ], - // Serve the app unless we were pointed at an instance that is already up - // (E2E_BASE_URL). - // - // CI builds and serves the STATIC bundle. The dev server compiles on demand, - // and force-reloads the page whenever it discovers a new dependency to - // pre-bundle ("optimized dependencies changed. reloading") -- which wipes - // whatever a test was mid-way through. Serving a build removes that entire - // class of failure and is much faster: the build is ~5s and the suite drops - // from ~3.7min to ~35s. `vite preview` inherits `server.proxy`, so /api and - // /ws still reach the backend on DEV_PORT (5000) -- the same default - // `main.py` binds, so neither side needs configuring. - // - // Locally it stays on the dev server: `reuseExistingServer` attaches to the - // `npm run dev` you already have, so a code change is picked up without a - // rebuild. `login()` retries to absorb the reload described above. - ...(process.env.E2E_BASE_URL - ? {} - : { - webServer: { - // Vite skips `assets/`; the Docker image copies it over `dist`, so do the same. - command: process.env.CI - ? "npm run build && cp -R assets/. dist/assets/ && npm run preview -- --port 3000 --strictPort --host 127.0.0.1" - : "npm run dev", - url: "http://127.0.0.1:3000", - reuseExistingServer: !process.env.CI, - timeout: 180_000, - stdout: "pipe" as const, - stderr: "pipe" as const, - }, - }), + // CI serves the build e2e.yml made, which never force-reloads mid-test as the + // dev server does on a new dependency. Locally, the dev server is (re)used. + ...(!baseURL && { + webServer: { + command: isCI + ? `npm run preview -- --port ${SERVED_PORT} --strictPort --host 127.0.0.1` + : "npm run dev", + url: SERVED_URL, + reuseExistingServer: !isCI, + timeout: 180_000, + stdout: "pipe", + stderr: "pipe", + }, + }), }); diff --git a/frontend/scripts/previewAssets.ts b/frontend/scripts/previewAssets.ts new file mode 100644 index 000000000..a7b60b732 --- /dev/null +++ b/frontend/scripts/previewAssets.ts @@ -0,0 +1,18 @@ +// Serves frontend/assets (emulator runtimes, icons) under `vite preview`, as +// the dev server and the Docker image do; the build leaves it out of dist/. +import { fileURLToPath } from "node:url"; +import sirv from "sirv"; +import type { Plugin } from "vite"; + +const ASSETS_DIR = fileURLToPath(new URL("../assets", import.meta.url)); + +export function previewAssets(): Plugin { + return { + name: "romm:preview-assets", + configurePreviewServer(server) { + // `dev` skips indexing the tree up front, since assets/romm can link to a + // whole library. A miss falls through to the build's own dist/assets. + server.middlewares.use("/assets", sirv(ASSETS_DIR, { dev: true })); + }, + }; +} diff --git a/frontend/src/plugins/routeNames.ts b/frontend/src/plugins/routeNames.ts index 5731587e0..ce1958f42 100644 --- a/frontend/src/plugins/routeNames.ts +++ b/frontend/src/plugins/routeNames.ts @@ -52,6 +52,19 @@ export const ROUTES = { export type RouteName = (typeof ROUTES)[keyof typeof ROUTES]; +/** Scopes a route needs; the router sends a user without them to the 404 page. */ +export const ROUTE_SCOPES: Partial> = { + [ROUTES.CLIENT_API_TOKENS]: ["me.write"], + [ROUTES.DEVICES]: ["devices.read"], + [ROUTES.SCAN]: ["platforms.write"], + [ROUTES.UPLOAD]: ["roms.write"], + [ROUTES.LIBRARY_MANAGEMENT]: ["platforms.write"], + [ROUTES.SCAN_SETTINGS]: ["platforms.write"], + [ROUTES.CONVERSION_SETTINGS]: ["platforms.write"], + [ROUTES.ADMINISTRATION]: ["users.write"], + [ROUTES.LOGS]: ["logs.read"], +}; + const authExemptRoutes = [ ROUTES.LOGIN, ROUTES.SETUP, diff --git a/frontend/src/plugins/router.ts b/frontend/src/plugins/router.ts index f1e52e61b..a86b980fb 100644 --- a/frontend/src/plugins/router.ts +++ b/frontend/src/plugins/router.ts @@ -16,6 +16,7 @@ import { useUiVersion } from "@/composables/useUiVersion"; import i18n, { loadLocale } from "@/locales"; import { isAuthExemptRoute, + ROUTE_SCOPES, ROUTES, type RouteName, } from "@/plugins/routeNames"; @@ -598,11 +599,6 @@ const routes = [ }, ]; -interface RoutePermissions { - path: string; - requiredScopes: string[]; -} - const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes, @@ -619,18 +615,6 @@ const router = createRouter({ }, }); -const routePermissions: RoutePermissions[] = [ - { path: ROUTES.CLIENT_API_TOKENS, requiredScopes: ["me.write"] }, - { path: ROUTES.DEVICES, requiredScopes: ["devices.read"] }, - { path: ROUTES.SCAN, requiredScopes: ["platforms.write"] }, - { path: ROUTES.UPLOAD, requiredScopes: ["roms.write"] }, - { path: ROUTES.LIBRARY_MANAGEMENT, requiredScopes: ["platforms.write"] }, - { path: ROUTES.SCAN_SETTINGS, requiredScopes: ["platforms.write"] }, - { path: ROUTES.CONVERSION_SETTINGS, requiredScopes: ["platforms.write"] }, - { path: ROUTES.ADMINISTRATION, requiredScopes: ["users.write"] }, - { path: ROUTES.LOGS, requiredScopes: ["logs.read"] }, -]; - function checkRoutePermissions(route: string, user: User | null): boolean { // No checks needed for login and setup pages if (isAuthExemptRoute(route)) { @@ -640,14 +624,8 @@ function checkRoutePermissions(route: string, user: User | null): boolean { // No user, no access if (!user) return false; - // Check if route has permissions requirements - const routeConfig = routePermissions.find((config) => config.path === route); - if (!routeConfig) return true; - - // Check if user has required scopes - return routeConfig.requiredScopes.every((scope) => - user.oauth_scopes.includes(scope), - ); + const requiredScopes = ROUTE_SCOPES[route as RouteName] ?? []; + return requiredScopes.every((scope) => user.oauth_scopes.includes(scope)); } // `meta.title` holds an i18n key, translated per navigation rather than when diff --git a/frontend/src/v2/components/GameDetails/MediaTab.test.ts b/frontend/src/v2/components/GameDetails/MediaTab.test.ts index 890e83026..5bcfedcfa 100644 --- a/frontend/src/v2/components/GameDetails/MediaTab.test.ts +++ b/frontend/src/v2/components/GameDetails/MediaTab.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import { defineComponent, ref } from "vue"; import { createMemoryHistory, createRouter, type Router } from "vue-router"; import { detailedRomFixture } from "@/utils/rom.fixtures"; +import { tabId, tabPanelId } from "@/v2/utils/tabIds"; import MediaTab from "./MediaTab.vue"; vi.mock("vue-i18n"); @@ -102,3 +103,18 @@ describe("MediaTab PDF viewer ownership", () => { expect(pdfActive(wrapper)).toEqual({ manual: false, walkthrough: false }); }); }); + +describe("MediaTab panels", () => { + it("labels each panel by the rail tab that controls it", async () => { + const wrapper = await mountTab(); + const prefix: string = wrapper + .findComponent({ name: "SubtabNav" }) + .props("idPrefix"); + const panel = wrapper.findComponent({ name: "ManualSubtab" }).element + .parentElement!; + + expect(panel.getAttribute("role")).toBe("tabpanel"); + expect(panel.id).toBe(tabPanelId(prefix, "manual")); + expect(panel.getAttribute("aria-labelledby")).toBe(tabId(prefix, "manual")); + }); +}); diff --git a/frontend/src/v2/components/GameDetails/MediaTab.vue b/frontend/src/v2/components/GameDetails/MediaTab.vue index e5f270d8e..3b9b9cb11 100644 --- a/frontend/src/v2/components/GameDetails/MediaTab.vue +++ b/frontend/src/v2/components/GameDetails/MediaTab.vue @@ -12,7 +12,7 @@ // // The soundtrack player is reused from v1 for now. import { RBtn, RDropzone, REmptyState } from "@v2/lib"; -import { computed, defineAsyncComponent, ref, watch } from "vue"; +import { computed, defineAsyncComponent, ref, useId, watch } from "vue"; import { useI18n } from "vue-i18n"; import type { DetailedRom } from "@/stores/roms"; import SubtabNav, { @@ -29,6 +29,7 @@ import { useRomSync } from "@/v2/composables/useRomSync"; import { useSoundtrackActions } from "@/v2/composables/useSoundtrackActions"; import { useSubtabQuery } from "@/v2/composables/useSubtabQuery"; import { SOUNDTRACK_ACCEPT } from "@/v2/utils/soundtrackTracks"; +import { tabId, tabPanelId } from "@/v2/utils/tabIds"; const ManualSubtab = defineAsyncComponent( () => import("@/v2/components/GameDetails/ManualSubtab.vue"), @@ -80,6 +81,17 @@ const subTab = useSubtabQuery( "manual", ); +// The sheet variant has no tabs to label the panels, so they stay sections. +const tabIdPrefix = useId(); +function panelAttrs(id: Subtab): Record { + if (smAndDown.value) return {}; + return { + id: tabPanelId(tabIdPrefix, id), + role: "tabpanel", + "aria-labelledby": tabId(tabIdPrefix, id), + }; +} + // vue3-pdf-app drives one global pdf.js app, so only the last shown PDF subtab // mounts a PdfViewer. const pdfSubtab = ref<"manual" | "walkthrough" | null>(null); @@ -194,7 +206,11 @@ async function deleteSoundtrack(fileId: number) {
@@ -206,7 +222,11 @@ async function deleteSoundtrack(fileId: number) { CSS toggle (bar the PDF viewer, see `pdfSubtab`). --> -
+
-
+
-
+
-
+
-
+
{ "Speedrun Route", ]); }); + + it("ties each tab to its panel only when given an id prefix", () => { + const items = [{ id: "manual", label: "Manual" }]; + + const tab = nav(items, { idPrefix: "m" }).get('[role="tab"]'); + expect(tab.attributes("id")).toBe(tabId("m", "manual")); + expect(tab.attributes("aria-controls")).toBe(tabPanelId("m", "manual")); + + const bare = nav(items).get('[role="tab"]'); + expect(bare.attributes("id")).toBeUndefined(); + expect(bare.attributes("aria-controls")).toBeUndefined(); + }); }); diff --git a/frontend/src/v2/components/GameDetails/SubtabNav.vue b/frontend/src/v2/components/GameDetails/SubtabNav.vue index 17c5f1f60..57cc54657 100644 --- a/frontend/src/v2/components/GameDetails/SubtabNav.vue +++ b/frontend/src/v2/components/GameDetails/SubtabNav.vue @@ -3,6 +3,7 @@ import { RBtn, RDivider, RIcon, RMenu, RMenuItem } from "@v2/lib"; import { computed, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import { shouldAutofocusSearch } from "@/v2/utils/autofocus"; +import { tabId, tabPanelId } from "@/v2/utils/tabIds"; export interface SubtabNavItem { id: Id; @@ -24,8 +25,10 @@ const props = withDefaults( items: I[]; /** "list" is a side rail; "menu" a one-row trigger opening a sheet. */ variant?: "list" | "menu"; + /** Ties each "list" tab to the panel with id `tabPanelId(idPrefix, id)`. */ + idPrefix?: string | undefined; }>(), - { variant: "list" }, + { variant: "list", idPrefix: undefined }, ); const emit = defineEmits<{ @@ -82,11 +85,13 @@ function select(id: I["id"]) { class="r-v2-subtab-nav__item" >