Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
test(e2e): per-worker user isolation + idempotent seeding + de-flake search (refs #44) (#49)
Carter54ae93e09ce3
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 434df48..a221b7a 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -95,6 +95,16 @@ E2E. E2E is reserved for "the user opens the page, does X, and sees Y."web-first assertion (`await expect(locator).toBeVisible()` auto-retries), anavigation (`waitForURL`), or the actual network call(`page.waitForResponse(r => r.url().includes('/api/v1/weight') && r.request().method() === 'POST')`).+- **Isolation: one fresh user per worker + idempotent seeding.** Each worker+ registers its own account (`e2e/fixtures.ts`), so runs are hermetic. Seed via+ `cleanupSeed` (delete your exact seed names, then create) so a `beforeAll` is+ idempotent — it runs once *per project* (chromium + mobile), so on the shared+ workers:1 user it executes twice; idempotent seeding keeps the result to one set.+- **No strict-mode traps on list items.** For "this row is gone after filter/delete"+ use `await expect(page.getByText(name)).toHaveCount(0)` (auto-retries to zero) —+ NOT `.not.toBeVisible()`, which throws a strict-mode error (not retried) if a+ debounced list re-render transiently shows two matching nodes. Use `.first()` on+ "this row appears" checks for the same reason.- **WHY-comments.** Explain non-obvious test setup in the same explanatory style asthe rest of the codebase.diff --git a/web/e2e/auth.setup.ts b/web/e2e/auth.setup.tsdeleted file mode 100644index e668ed5..0000000--- a/web/e2e/auth.setup.ts+++ /dev/null@@ -1,17 +0,0 @@-import { test as setup, expect } from '@playwright/test'-import path from 'path'-import { fileURLToPath } from 'url'-import { TEST_EMAIL, TEST_PASSWORD } from './config'--const __dirname = path.dirname(fileURLToPath(import.meta.url))-const authFile = path.join(__dirname, '.auth/user.json')--setup('authenticate', async ({ page }) => {- await page.goto('/login')- await page.getByPlaceholder('[email protected]').fill(TEST_EMAIL)- await page.locator('input[type="password"]').fill(TEST_PASSWORD)- await page.getByRole('button', { name: /sign in|log in/i }).click()- await page.waitForURL(url => new URL(url).pathname === '/')- await expect(page.locator('h1, h2').first()).toBeVisible()- await page.context().storageState({ path: authFile })-})diff --git a/web/e2e/auth.spec.ts b/web/e2e/auth.spec.tsindex a281c90..c7021d4 100644--- a/web/e2e/auth.spec.ts+++ b/web/e2e/auth.spec.ts@@ -1,4 +1,5 @@import { test, expect } from '@playwright/test'+import { recordCreatedUser } from './userRegistry'// These run logged-out, so override the shared authenticated storage state.test.use({ storageState: { cookies: [], origins: [] } })@@ -12,6 +13,11 @@ test('registers a new user and lands on the dashboard', { tag: '@mobile' }, asynawait page.locator('#password-confirm').fill('password123')await page.getByRole('button', { name: /create account/i }).click()await page.waitForURL(url => new URL(url).pathname === '/')++ // Record for globalTeardown to delete (cascades its data) — keeps register+ // test users from accumulating in the DB across runs.+ const token = await page.evaluate(() => localStorage.getItem('access_token'))+ if (token) recordCreatedUser(token)})test('wrong password shows an error and stays on the login page (no reload)', async ({ page }) => {diff --git a/web/e2e/exercises.spec.ts b/web/e2e/exercises.spec.tsindex e29388c..7d7abd6 100644--- a/web/e2e/exercises.spec.ts+++ b/web/e2e/exercises.spec.ts@@ -1,5 +1,6 @@-import { test, expect } from '@playwright/test'-import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'+import { test, expect } from './fixtures'+import { API_BASE as API } from './config'+import { cleanupSeed } from './seedHelpers'let authToken: stringlet exerciseId: number@@ -7,11 +8,8 @@ let workoutId: numberlet workoutId2: numbertest.describe('Exercise Detail', () => {- test.beforeAll(async ({ request }) => {- const res = await request.post(`${API}/auth/login`, {- data: { email: TEST_EMAIL, password: TEST_PASSWORD }- })- authToken = (await res.json()).data.token+ test.beforeAll(async ({ request, workerAuth }) => {+ authToken = workerAuth.token// Find a real exercise ID to useconst exRes = await request.get(`${API}/exercises?limit=1`, {@@ -20,6 +18,10 @@ test.describe('Exercise Detail', () => {const exBody = await exRes.json()exerciseId = exBody.data[0].id+ // Idempotent seed (defensive — keeps history deterministic across runs).+ await cleanupSeed(request, authToken, `${API}/workouts?limit=100`, `${API}/workouts`,+ w => typeof w.name === 'string' && w.name.startsWith('E2E Exercise History Seed'))+// Seed two workouts on different days so history.length >= 2 (chart requires 2+ points)const yesterday = new Date(Date.now() - 86400000).toISOString()const w1 = await request.post(`${API}/workouts`, {diff --git a/web/e2e/fixtures.ts b/web/e2e/fixtures.tsnew file mode 100644index 0000000..6cc308c--- /dev/null+++ b/web/e2e/fixtures.ts@@ -0,0 +1,63 @@+import { test as base, expect } from '@playwright/test'+import path from 'path'+import { fileURLToPath } from 'url'+import { recordCreatedUser } from './userRegistry'++const __dirname = path.dirname(fileURLToPath(import.meta.url))++export type WorkerAuth = { token: string; email: string }++// One fresh, isolated account per worker — the foundation for test isolation.+// Previously every data spec seeded into the single shared demo user, so state+// accumulated across tests AND across runs, which is why each spec carried+// fragile "wipe ALL E2E-prefixed entries" pre-cleanup. A brand-new account per+// run starts empty, so that pre-cleanup is unnecessary and runs are hermetic.+// (Currently workers:1 — one fresh user per run. The fixture is worker-scoped so+// it already supports workers>1 once the DB layer can take the write concurrency.)+export const test = base.extend<object, { workerAuth: WorkerAuth }>({+ workerAuth: [async ({ browser }, use, workerInfo) => {+ const idx = workerInfo.parallelIndex+ const email = `e2e-w${idx}-${Date.now()}@lyftr.local`+ const password = 'password123'+ const storageStatePath = path.join(__dirname, `.auth/worker-${idx}.json`)++ // Register via the real UI so the browser session + tokens are captured+ // exactly as the app writes them (token lives in localStorage). This manual+ // context needs baseURL + ignoreHTTPSErrors set explicitly — the config+ // `use` options only apply to test-created contexts, not this one. Read the+ // project's RESOLVED baseURL so this works in both dev (https://localhost:5173)+ // and CI docker mode (http://localhost) — don't hardcode.+ const baseURL = (workerInfo.project.use.baseURL as string | undefined) ?? 'https://localhost:5173'+ const context = await browser.newContext({+ baseURL,+ ignoreHTTPSErrors: true,+ storageState: undefined,+ })+ const page = await context.newPage()+ await page.goto('/register')+ await page.getByPlaceholder('[email protected]').fill(email)+ await page.locator('#password').fill(password)+ await page.locator('#password-confirm').fill(password)+ await page.getByRole('button', { name: /create account/i }).click()+ await page.waitForURL(u => new URL(u).pathname === '/')+ await context.storageState({ path: storageStatePath })+ const token = await page.evaluate(() => localStorage.getItem('access_token'))+ await context.close()++ if (!token) throw new Error(`worker ${idx}: failed to obtain access_token after register`)++ // Record for globalTeardown to delete at the end (cascades all its data).+ // Centralized cleanup with retry — robust to transient failures and crashes.+ recordCreatedUser(token)++ await use({ token, email })+ }, { scope: 'worker' }],++ // Logged-in specs get this worker's freshly-registered storage state.+ storageState: async ({ workerAuth }, use, workerInfo) => {+ void workerAuth // ensure the worker account is registered first+ await use(path.join(__dirname, `.auth/worker-${workerInfo.parallelIndex}.json`))+ },+})++export { expect }diff --git a/web/e2e/food.spec.ts b/web/e2e/food.spec.tsindex 0a3a075..6a1dca7 100644--- a/web/e2e/food.spec.ts+++ b/web/e2e/food.spec.ts@@ -1,5 +1,6 @@-import { test, expect } from '@playwright/test'-import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'+import { test, expect } from './fixtures'+import { API_BASE as API } from './config'+import { cleanupSeed } from './seedHelpers'const SEED_PREFIX = 'E2EFood'// Use local calendar date to match what todayStr() returns in the frontend.@@ -14,41 +15,18 @@ let seedFoodIds: number[] = []let seedSavedIds: number[] = []test.describe('Food', () => {- test.beforeAll(async ({ request }) => {- const res = await request.post(`${API}/auth/login`, {- data: { email: TEST_EMAIL, password: TEST_PASSWORD },- })- authToken = (await res.json()).data.token+ test.beforeAll(async ({ request, workerAuth }) => {+ authToken = workerAuth.tokenconst h = { Authorization: `Bearer ${authToken}` }- // Pre-cleanup: wipe ALL E2E-prefixed food log entries from the last 3 days- // (covers timezone edge cases and accumulated state from multiple test runs).- // Deletes are serial — bulk Promise.all against SQLite single-writer can- // drop requests under load and leave entries behind.- for (let d = 0; d < 3; d++) {- const checkDate = new Date(_now)- checkDate.setDate(_now.getDate() - d)- const dateStr = `${checkDate.getFullYear()}-${_pad(checkDate.getMonth() + 1)}-${_pad(checkDate.getDate())}`- const existing = await request.get(`${API}/food?date=${dateStr}`, { headers: h })- const body = await existing.json()- const toDelete = (body.data ?? []).filter((e: any) =>- e.name.startsWith(SEED_PREFIX) ||- e.name.startsWith('E2ELog-') ||- e.name.startsWith('E2ESave-') ||- e.name.startsWith('E2EEdit-')- )- for (const e of toDelete) {- await request.delete(`${API}/food/${e.id}`, { headers: h })- }- }- const existingSaved = await request.get(`${API}/food/saved`, { headers: h })- const es = await existingSaved.json()- const savedToDelete = (es.data ?? []).filter((s: any) =>- s.name.startsWith(SEED_PREFIX) || s.name.startsWith('E2ESave-')- )- for (const s of savedToDelete) {- await request.delete(`${API}/food/saved/${s.id}`, { headers: h })- }+ // Idempotent seed: beforeAll runs once per project (chromium + mobile) on the+ // shared workers:1 user, so clear our own seed names first, then create exactly+ // one set. Reset the module-level id arrays (they persist across both runs).+ seedFoodIds = []+ seedSavedIds = []+ const mealNames = [`${SEED_PREFIX}-breakfast`, `${SEED_PREFIX}-lunch`, `${SEED_PREFIX}-snacks`]+ await cleanupSeed(request, authToken, `${API}/food?date=${today}`, `${API}/food`, e => mealNames.includes(e.name))+ await cleanupSeed(request, authToken, `${API}/food/saved`, `${API}/food/saved`, s => s.name === `${SEED_PREFIX}-saved`)// Seed one entry per meal so meal sections have datafor (const [name, meal] of [diff --git a/web/e2e/globalTeardown.ts b/web/e2e/globalTeardown.tsnew file mode 100644index 0000000..335c27a--- /dev/null+++ b/web/e2e/globalTeardown.ts@@ -0,0 +1,39 @@+import { request } from '@playwright/test'+import { existsSync, readFileSync, rmSync } from 'fs'+import { API_BASE } from './config'+import { REGISTRY_FILE } from './userRegistry'++// Deletes every account created during the run (recorded via recordCreatedUser).+// DELETE /me cascades all the user's data, so the DB is left exactly as it+// started. This is the authoritative cleanup — per-test/worker teardown is no+// longer relied on for it — and it's resilient: retries the transient+// SQLite-busy miss, and treats 401 (token already invalid) as "already gone".+export default async function globalTeardown(): Promise<void> {+ if (!existsSync(REGISTRY_FILE)) return++ const tokens = [...new Set(+ readFileSync(REGISTRY_FILE, 'utf8').split('\n').map(t => t.trim()).filter(Boolean),+ )]+ if (tokens.length === 0) {+ rmSync(REGISTRY_FILE, { force: true })+ return+ }++ const api = await request.newContext({ ignoreHTTPSErrors: true })+ let deleted = 0+ for (const token of tokens) {+ for (let attempt = 0; attempt < 3; attempt++) {+ const res = await api+ .delete(`${API_BASE}/me`, { headers: { Authorization: `Bearer ${token}` } })+ .catch(() => null)+ // ok() = deleted; 401 = token invalid → already gone. Both are terminal.+ if (!res) break+ if (res.ok() || res.status() === 401) { if (res.ok()) deleted++; break }+ await new Promise(r => setTimeout(r, 200 * (attempt + 1))) // retry busy/5xx+ }+ }+ await api.dispose()+ rmSync(REGISTRY_FILE, { force: true })+ // eslint-disable-next-line no-console+ console.log(`[globalTeardown] swept ${deleted}/${tokens.length} e2e accounts`)+}diff --git a/web/e2e/programs.spec.ts b/web/e2e/programs.spec.tsindex 2d0389a..5d8fa7b 100644--- a/web/e2e/programs.spec.ts+++ b/web/e2e/programs.spec.ts@@ -1,5 +1,6 @@-import { test, expect } from '@playwright/test'-import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'+import { test, expect } from './fixtures'+import { API_BASE as API } from './config'+import { cleanupSeed } from './seedHelpers'const E2E_PROGRAM_NAME = 'Test Program E2E'const SEED_PROGRAM_NAME = 'Seeded Test Program'const SEED_SEARCH_PROGRAM_NAME = 'ZZZ E2E SearchTarget Program'@@ -9,46 +10,24 @@ let searchProgramId: numberlet authToken: stringtest.describe('Programs', () => {- test.beforeAll(async ({ request }) => {- const res = await request.post(`${API}/auth/login`, {- data: { email: TEST_EMAIL, password: TEST_PASSWORD }- })- const body = await res.json()- authToken = body.data.token+ test.beforeAll(async ({ request, workerAuth }) => {+ authToken = workerAuth.tokenconst headers = { Authorization: `Bearer ${authToken}` }- // Pre-clean any accumulated seed programs from prior runs so the search- // and list assertions don't see duplicates. Serial deletes — bulk- // Promise.all races against SQLite's single-writer.- const existing = await request.get(`${API}/programs`, { headers })- const eb = await existing.json()- const stale = (eb.data ?? []).filter((p: any) =>- p.name === SEED_PROGRAM_NAME ||- p.name === SEED_SEARCH_PROGRAM_NAME ||- p.name === E2E_PROGRAM_NAME- )- for (const p of stale) {- await request.delete(`${API}/programs/${p.id}`, { headers })- }-- // Retry create on transient backend failure (e.g. SQLite busy under- // concurrent worker load). spb.data is undefined when backend returned- // an error envelope instead of the created row.- const createSeed = async (name: string, notes: string): Promise<number> => {- for (let attempt = 0; attempt < 3; attempt++) {- const r = await request.post(`${API}/programs`, {- headers,- data: { name, notes, exercises: [] },- })- const rb = await r.json()- if (rb.data?.id) return rb.data.id- await new Promise(res => setTimeout(res, 200 * (attempt + 1)))- }- throw new Error(`Failed to create seed program "${name}" after 3 attempts`)+ // Idempotent seed: clear our own seed names, then create exactly one of each.+ // (Previously a retry-on-transient-failure here could double-create — if the+ // first POST committed but returned an error envelope — leaving duplicates.)+ await cleanupSeed(request, authToken, `${API}/programs`, `${API}/programs`,+ p => p.name === SEED_PROGRAM_NAME || p.name === SEED_SEARCH_PROGRAM_NAME)++ const createProgram = async (name: string, notes: string): Promise<number> => {+ const r = await request.post(`${API}/programs`, { headers, data: { name, notes, exercises: [] } })+ const rb = await r.json()+ if (!rb.data?.id) throw new Error(`Failed to create seed program "${name}": ${JSON.stringify(rb)}`)+ return rb.data.id}-- programId = await createSeed(SEED_PROGRAM_NAME, 'Created by E2E seed')- searchProgramId = await createSeed(SEED_SEARCH_PROGRAM_NAME, 'Created by E2E seed for search')+ programId = await createProgram(SEED_PROGRAM_NAME, 'Created by E2E seed')+ searchProgramId = await createProgram(SEED_SEARCH_PROGRAM_NAME, 'Created by E2E seed for search')})test.afterAll(async ({ request }) => {@@ -110,7 +89,9 @@ test.describe('Programs', () => {const searchInput = page.getByPlaceholder(/search programs/i)await searchInput.fill('SearchTarget')await expect(page.getByText(SEED_SEARCH_PROGRAM_NAME).first()).toBeVisible()- await expect(page.getByText(SEED_PROGRAM_NAME)).not.toBeVisible()+ // toHaveCount(0) auto-retries until fully filtered out; not.toBeVisible()+ // would strict-mode-throw on the transient 2-node re-render.+ await expect(page.getByText(SEED_PROGRAM_NAME)).toHaveCount(0)})test('clearing search restores full list', async ({ page }) => {@@ -118,7 +99,7 @@ test.describe('Programs', () => {await searchInput.fill('SearchTarget')await expect(page.getByText(SEED_SEARCH_PROGRAM_NAME).first()).toBeVisible()await searchInput.fill('')- await expect(page.getByText(SEED_PROGRAM_NAME)).toBeVisible()+ await expect(page.getByText(SEED_PROGRAM_NAME).first()).toBeVisible()await expect(page.getByText(SEED_SEARCH_PROGRAM_NAME).first()).toBeVisible()})diff --git a/web/e2e/seedHelpers.ts b/web/e2e/seedHelpers.tsnew file mode 100644index 0000000..58d8962--- /dev/null+++ b/web/e2e/seedHelpers.ts@@ -0,0 +1,26 @@+import { type APIRequestContext } from '@playwright/test'++// Idempotent seeding helper. Deletes every item at `listUrl` matching `match`+// before the caller (re)creates its seed rows, so seeding produces exactly one+// set no matter how many times a `beforeAll` runs. That matters because a+// describe whose `beforeAll` seeds data runs once PER PROJECT (chromium ++// mobile), and at workers:1 both projects share one worker user — so without+// this, a tagged spec would double-seed and tests would hit duplicate rows.+//+// Targeted (exact match on the caller's own seed identifiers), not a broad+// "wipe everything" — so it can't clobber unrelated data. Serial deletes:+// SQLite is a single writer.+export async function cleanupSeed(+ request: APIRequestContext,+ token: string,+ listUrl: string,+ deleteBase: string,+ match: (item: any) => boolean,+): Promise<void> {+ const headers = { Authorization: `Bearer ${token}` }+ const res = await request.get(listUrl, { headers })+ const body = await res.json().catch(() => ({}))+ for (const item of (body.data ?? []).filter(match)) {+ await request.delete(`${deleteBase}/${item.id}`, { headers })+ }+}diff --git a/web/e2e/settings.spec.ts b/web/e2e/settings.spec.tsindex 4f7bac3..8aa24bc 100644--- a/web/e2e/settings.spec.ts+++ b/web/e2e/settings.spec.ts@@ -1,4 +1,4 @@-import { test, expect } from '@playwright/test'+import { test, expect } from './fixtures'// Authenticated spec — relies on the shared storage state from auth.setup.ts// (no test.use override), since Settings is only reachable when logged in.diff --git a/web/e2e/userRegistry.ts b/web/e2e/userRegistry.tsnew file mode 100644index 0000000..9424101--- /dev/null+++ b/web/e2e/userRegistry.ts@@ -0,0 +1,21 @@+import { appendFileSync, mkdirSync } from 'fs'+import path from 'path'+import { fileURLToPath } from 'url'++const __dirname = path.dirname(fileURLToPath(import.meta.url))++// Tokens of accounts created during the run, swept by globalTeardown. This gives+// a hard cleanup guarantee without needing an admin "list/delete users" endpoint:+// whoever creates a throwaway account records its token here, and globalTeardown+// deletes every one at the end — even if a per-test cleanup missed (a transient+// DELETE /me under load) or a test crashed before cleaning up. Gitignored (.auth).+export const REGISTRY_FILE = path.join(__dirname, '.auth', 'created-tokens.txt')++export function recordCreatedUser(token: string): void {+ try {+ mkdirSync(path.dirname(REGISTRY_FILE), { recursive: true })+ appendFileSync(REGISTRY_FILE, token + '\n')+ } catch {+ // best-effort — globalTeardown is the catch-all, not this record step+ }+}diff --git a/web/e2e/weight.spec.ts b/web/e2e/weight.spec.tsindex 9025622..04965d1 100644--- a/web/e2e/weight.spec.ts+++ b/web/e2e/weight.spec.ts@@ -1,5 +1,6 @@-import { test, expect } from '@playwright/test'-import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'+import { test, expect } from './fixtures'+import { API_BASE as API } from './config'+import { cleanupSeed } from './seedHelpers'const SEED_WEIGHT_NOTE = 'E2E seed weight'const FORM_WEIGHT_NOTE = 'E2E form weight test'@@ -8,13 +9,14 @@ let authToken: stringlet seedWeightIds: number[] = []test.describe('Weight', () => {- test.beforeAll(async ({ request }) => {- const res = await request.post(`${API}/auth/login`, {- data: { email: TEST_EMAIL, password: TEST_PASSWORD }- })- authToken = (await res.json()).data.token+ test.beforeAll(async ({ request, workerAuth }) => {+ authToken = workerAuth.tokenconst headers = { Authorization: `Bearer ${authToken}` }+ // Idempotent seed (beforeAll runs in both projects on the shared workers:1 user).+ seedWeightIds = []+ await cleanupSeed(request, authToken, `${API}/weight?limit=100`, `${API}/weight`, w => w.notes === SEED_WEIGHT_NOTE)+// Seed entries at -7d, -3d, and today so history and period selector have dataconst offsets = [7, 3, 0]for (const daysAgo of offsets) {diff --git a/web/e2e/workouts.spec.ts b/web/e2e/workouts.spec.tsindex 9a47021..5ac4961 100644--- a/web/e2e/workouts.spec.ts+++ b/web/e2e/workouts.spec.ts@@ -1,5 +1,6 @@-import { test, expect } from '@playwright/test'-import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'+import { test, expect } from './fixtures'+import { API_BASE as API } from './config'+import { cleanupSeed } from './seedHelpers'const E2E_WORKOUT_NAME = 'Test Workout E2E'const SEED_WORKOUT_NAME = 'Seeded Test Workout'const SEED_SEARCH_WORKOUT_NAME = 'ZZZ E2E SearchTarget Workout'@@ -11,12 +12,13 @@ let searchWorkoutId: numberlet authToken: stringtest.describe('Workouts', () => {- test.beforeAll(async ({ request }) => {- const res = await request.post(`${API}/auth/login`, {- data: { email: TEST_EMAIL, password: TEST_PASSWORD }- })- const body = await res.json()- authToken = body.data.token+ test.beforeAll(async ({ request, workerAuth }) => {+ authToken = workerAuth.token++ // Idempotent seed: clear our own seed names first so the list stays+ // deterministic regardless of how many times beforeAll runs.+ await cleanupSeed(request, authToken, `${API}/workouts?limit=100`, `${API}/workouts`,+ w => w.name === SEED_WORKOUT_NAME || w.name === SEED_SEARCH_WORKOUT_NAME)const w = await request.post(`${API}/workouts`, {headers: { Authorization: `Bearer ${authToken}` },@@ -133,7 +135,9 @@ test.describe('Workouts', () => {const searchInput = page.getByPlaceholder(/search workouts/i)await searchInput.fill('SearchTarget')await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible()- await expect(page.getByText(SEED_WORKOUT_NAME)).not.toBeVisible()+ // toHaveCount(0) auto-retries until the filtered-out item is fully gone;+ // not.toBeVisible() would strict-mode-throw on the transient 2-node re-render.+ await expect(page.getByText(SEED_WORKOUT_NAME)).toHaveCount(0)})test('clearing search restores full list', async ({ page }) => {@@ -141,7 +145,7 @@ test.describe('Workouts', () => {await searchInput.fill('SearchTarget')await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible()await searchInput.fill('')- await expect(page.getByText(SEED_WORKOUT_NAME)).toBeVisible()+ await expect(page.getByText(SEED_WORKOUT_NAME).first()).toBeVisible()await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible()})@@ -183,11 +187,8 @@ let gymExerciseId: number// @mobile: Gym Mode is the mobile-first full-screen workout UX — run it on the// iPhone profile (it also runs on chromium via the full suite).test.describe('Gym Mode', { tag: '@mobile' }, () => {- test.beforeAll(async ({ request }) => {- const res = await request.post(`${API}/auth/login`, {- data: { email: TEST_EMAIL, password: TEST_PASSWORD }- })- gymAuthToken = (await res.json()).data.token+ test.beforeAll(async ({ request, workerAuth }) => {+ gymAuthToken = workerAuth.tokenconst exRes = await request.get(`${API}/exercises?limit=1`, {headers: { Authorization: `Bearer ${gymAuthToken}` }diff --git a/web/playwright.config.ts b/web/playwright.config.tsindex 218eea7..d467bb4 100644--- a/web/playwright.config.ts+++ b/web/playwright.config.ts@@ -20,14 +20,16 @@ const baseURL = process.env.BASE_URLexport default defineConfig({testDir: './e2e',+ // Deletes every e2e account created during the run (recorded in userRegistry),+ // guaranteeing the DB is left as it started — no orphaned test users locally.+ globalTeardown: './e2e/globalTeardown.ts',fullyParallel: false,forbidOnly: !!process.env.CI,retries: process.env.CI ? 1 : 0,- // Single worker. Each spec file is run twice (chromium + mobile projects)- // and shares one demo user, so two workers running the same spec across- // projects race on cleanup — both `beforeAll` hooks run their pre-clean,- // and the second worker wipes the first's seeded rows mid-test.- // Per-worker namespacing would unblock workers > 1; deferred for now.+ // Kept at 1 for now: each worker registers its own isolated user (see+ // e2e/fixtures.ts), so the suite is parallel-SAFE, but the backend is a single+ // SQLite writer (DELETE journal mode) that drops writes under concurrent load.+ // Raising workers waits on SQLite WAL (a separate backend change).workers: 1,reporter: 'list',use: {@@ -37,15 +39,9 @@ export default defineConfig({screenshot: 'only-on-failure',},projects: [- { name: 'setup', testMatch: '**/auth.setup.ts' },- {- name: 'chromium',- use: {- ...devices['Desktop Chrome'],- storageState: 'e2e/.auth/user.json',- },- dependencies: ['setup'],- },+ // storageState is supplied per-worker by e2e/fixtures.ts (logged-in specs).+ // auth.spec imports @playwright/test directly and stays logged out.+ { name: 'chromium', use: { ...devices['Desktop Chrome'] } },{// Mobile (iPhone-14) runs ONLY @mobile-tagged tests — the flows where the// phone viewport itself is under test (gym mode, barcode scanner) plus a@@ -53,11 +49,7 @@ export default defineConfig({// logic is covered once; the mobile project guards mobile-specific UX// without re-running every viewport-independent test. See docs/TESTING.md.name: 'mobile',- use: {- ...devices['iPhone 14'],- storageState: 'e2e/.auth/user.json',- },- dependencies: ['setup'],+ use: { ...devices['iPhone 14'] },grep: /@mobile/,},],