From bb1fd0dc13d76fc0b3e553ffc46400fa03f34e8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Boduro=C4=9Flu?= <80620802+burakboduroglu@users.noreply.github.com> Date: Sat, 1 Aug 2026 21:50:48 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=A7=AA=20Playwright=20e2e=20suite?= =?UTF-8?q?=20and=20wider=20API=20contract=20coverage=20-=20playwright=20s?= =?UTF-8?q?etup=20with=20desktop=20+=20mobile=20projects=20against=20the?= =?UTF-8?q?=20dev=20server,=20=20=20auth-shell=20spec;=20test:e2e=20script?= =?UTF-8?q?,=20report=20artifacts=20gitignored=20-=20contract=20tests=20fo?= =?UTF-8?q?r=20content,=20core,=20and=20learning=20endpoints;=20live-clien?= =?UTF-8?q?t=20=20=20helpers=20extended=20for=20the=20new=20suites=20-=20s?= =?UTF-8?q?erial=20contract=20runs=20(fileParallelism:=20false)=20so=20the?= =?UTF-8?q?=20rate-limited=20=20=20scratch=20backend=20stays=20determinist?= =?UTF-8?q?ic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + bun.lock | 9 +++ e2e/auth-shell.spec.ts | 24 ++++++++ package.json | 2 + playwright.config.ts | 21 +++++++ .../contract/bank-questions.contract.test.ts | 4 +- .../contract/content.contract.test.ts | 45 +++++++++++++++ .../__tests__/contract/core.contract.test.ts | 33 +++++++++++ .../__tests__/contract/helpers/live-client.ts | 57 ++++++++++++++++--- .../contract/learning.contract.test.ts | 53 +++++++++++++++++ vitest.contract.config.ts | 3 + 11 files changed, 242 insertions(+), 11 deletions(-) create mode 100644 e2e/auth-shell.spec.ts create mode 100644 playwright.config.ts create mode 100644 src/api/__tests__/contract/content.contract.test.ts create mode 100644 src/api/__tests__/contract/core.contract.test.ts create mode 100644 src/api/__tests__/contract/learning.contract.test.ts diff --git a/.gitignore b/.gitignore index 96a081e..4adf742 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,8 @@ dist-ssr *.tsbuildinfo .od-skills/ critique.json +playwright-report +test-results # SurrealDB CLI REPL history (kb queries); see .claude/kb-sync.sh history.txt diff --git a/bun.lock b/bun.lock index 3ab49c2..c520ab3 100644 --- a/bun.lock +++ b/bun.lock @@ -15,6 +15,7 @@ "tailwind-merge": "^3.6.0", }, "devDependencies": { + "@playwright/test": "^1.62.1", "@solidjs/testing-library": "^0.8.10", "@tailwindcss/postcss": "^4.3.3", "@tanstack/solid-router-devtools": "^1.167.0", @@ -206,6 +207,8 @@ "@oxc-project/types": ["@oxc-project/types@0.139.0", "", {}, "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw=="], + "@playwright/test": ["@playwright/test@1.62.1", "", { "dependencies": { "playwright": "1.62.1" }, "bin": { "playwright": "cli.js" } }, "sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ=="], + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.1.5", "", { "os": "android", "cpu": "arm64" }, "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ=="], "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.1.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw=="], @@ -584,6 +587,10 @@ "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + "playwright": ["playwright@1.62.1", "", { "dependencies": { "playwright-core": "1.62.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg=="], + + "playwright-core": ["playwright-core@1.62.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw=="], + "postcss": ["postcss@8.5.22", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ=="], "pretty-format": ["pretty-format@27.5.1", "", { "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", "react-is": "^17.0.1" } }, "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ=="], @@ -708,6 +715,8 @@ "babel-plugin-jsx-dom-expressions/parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="], + "playwright/fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="], + "vitest/vite": ["vite@6.4.3", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": "bin/vite.js" }, "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A=="], "@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="], diff --git a/e2e/auth-shell.spec.ts b/e2e/auth-shell.spec.ts new file mode 100644 index 0000000..c40d8f4 --- /dev/null +++ b/e2e/auth-shell.spec.ts @@ -0,0 +1,24 @@ +import { expect, test } from "@playwright/test"; + +const username = process.env.E2E_ADMIN_USERNAME ?? "admin"; +const password = process.env.E2E_ADMIN_PASSWORD ?? "admin123"; + +test("sign-in reaches the authenticated shell with keyboard-accessible navigation", async ({ page }) => { + await page.goto("/login"); + await expect(page.locator("#login-username")).toBeVisible(); + await page.locator("#login-username").fill(username); + await page.locator("#login-password").fill(password); + await page.locator("form").getByRole("button", { name: /log in|sign in|giriş yap/i }).click(); + + await expect(page).toHaveURL(/\/$/); + await expect(page.getByRole("main")).toBeVisible(); + + // The mobile tab bar is absent on desktop but must be reachable and named on + // a touch viewport. This catches accidental removal of its accessible nav. + if (test.info().project.name === "mobile") { + const navigation = page.getByRole("navigation", { name: /menu|menü/i }); + await expect(navigation).toBeVisible(); + await navigation.getByRole("button", { name: /account|hesap/i }).focus(); + await expect(navigation.getByRole("button", { name: /account|hesap/i })).toBeFocused(); + } +}); diff --git a/package.json b/package.json index f4baa14..8ec7642 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "preview": "vite preview", "check": "tsc --noEmit", "test": "vitest run", + "test:e2e": "playwright test", "test:watch": "vitest", "test:contract": "vitest run --config vitest.contract.config.ts", "sync-skills": "bun run scripts/sync-skills.ts", @@ -26,6 +27,7 @@ "tailwind-merge": "^3.6.0" }, "devDependencies": { + "@playwright/test": "^1.62.1", "@solidjs/testing-library": "^0.8.10", "@tailwindcss/postcss": "^4.3.3", "@tanstack/solid-router-devtools": "^1.167.0", diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..6caa7e8 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,21 @@ +import { defineConfig, devices } from "@playwright/test"; + +export default defineConfig({ + testDir: "./e2e", + fullyParallel: false, + retries: process.env.CI ? 2 : 0, + use: { + baseURL: "http://127.0.0.1:4173", + trace: "on-first-retry", + }, + projects: [ + { name: "desktop", use: { ...devices["Desktop Chrome"] } }, + { name: "mobile", use: { ...devices["iPhone 13"], browserName: "chromium" } }, + ], + webServer: { + command: "bun run dev -- --host 127.0.0.1 --port 4173", + url: "http://127.0.0.1:4173/login", + reuseExistingServer: !process.env.CI, + timeout: 30_000, + }, +}); diff --git a/src/api/__tests__/contract/bank-questions.contract.test.ts b/src/api/__tests__/contract/bank-questions.contract.test.ts index a480d67..1d0788c 100644 --- a/src/api/__tests__/contract/bank-questions.contract.test.ts +++ b/src/api/__tests__/contract/bank-questions.contract.test.ts @@ -1,4 +1,4 @@ -import { api, contractBaseUrl, isLive, json, loginAdmin, pngFile, SKIP_MESSAGE } from "./helpers/live-client"; +import { api, configuredExamKind, contractBaseUrl, isLive, json, loginAdmin, pngFile, SKIP_MESSAGE } from "./helpers/live-client"; import type { BankQuestion, Course, ExamQuestion, Subject } from "@/api/client"; if (!isLive) console.warn(SKIP_MESSAGE); @@ -228,7 +228,7 @@ describe.skipIf(!isLive)(`bank-questions contract @ ${contractBaseUrl}`, () => { const template = await createTemplate(`${tag} original text`); const exam = await json<{ id: string }>(`/courses/${courseId}/exams`, { method: "POST", - body: { title: tag, kind: "final" }, + body: { title: tag, kind: await configuredExamKind() }, }); const copy = await json( diff --git a/src/api/__tests__/contract/content.contract.test.ts b/src/api/__tests__/contract/content.contract.test.ts new file mode 100644 index 0000000..3da9d2e --- /dev/null +++ b/src/api/__tests__/contract/content.contract.test.ts @@ -0,0 +1,45 @@ +import { api, contractBaseUrl, expectPage, isLive, json, loginAdmin, pngFile, SKIP_MESSAGE } from "./helpers/live-client"; + +if (!isLive) console.warn(SKIP_MESSAGE); + +describe.skipIf(!isLive)(`content contract @ ${contractBaseUrl}`, () => { + let noteId = ""; + let eventId = ""; + + beforeAll(async () => { + await loginAdmin(); + const note = await json<{ id: string; title: string }>("/notes", { + method: "POST", + body: { title: `contract-note-${Date.now()}`, content: "contract body" }, + }); + noteId = note.id; + }); + + afterAll(async () => { + if (eventId) await api(`/events/${eventId}`, { method: "DELETE" }); + if (noteId) await api(`/notes/${noteId}`, { method: "DELETE" }); + }); + + it("supports note pagination and native multipart file lifecycle", async () => { + expectPage(await json("/notes?limit=1")); + const form = new FormData(); + form.append("file", pngFile("contract.png")); + const file = await json<{ id: string; content_type: string }>(`/notes/${noteId}/files`, { + method: "POST", + body: form, + }); + expect(file.content_type).toBe("image/png"); + expectPage(await json(`/notes/${noteId}/files?limit=10`)); + expect((await api(`/notes/${noteId}/files/${file.id}`, { method: "DELETE" })).status).toBe(204); + }); + + it("preserves event audience and paginated listing", async () => { + const event = await json<{ id: string; audience: { kind: string } }>("/events", { + method: "POST", + body: { title: `contract-event-${Date.now()}`, audience: { kind: "school" } }, + }); + eventId = event.id; + expect(event.audience.kind).toBe("school"); + expectPage(await json("/events?limit=1")); + }); +}); diff --git a/src/api/__tests__/contract/core.contract.test.ts b/src/api/__tests__/contract/core.contract.test.ts new file mode 100644 index 0000000..18c8c8e --- /dev/null +++ b/src/api/__tests__/contract/core.contract.test.ts @@ -0,0 +1,33 @@ +import { api, contractBaseUrl, expectPage, isLive, json, loginAdmin, SKIP_MESSAGE } from "./helpers/live-client"; + +if (!isLive) console.warn(SKIP_MESSAGE); + +describe.skipIf(!isLive)(`core contract @ ${contractBaseUrl}`, () => { + beforeAll(loginAdmin); + + it("keeps the authenticated user DTO stable", async () => { + const me = await json>("/auth/me"); + expect(typeof me.id).toBe("string"); + expect(typeof me.username).toBe("string"); + expect(["student", "parent", "teacher", "manager", "admin"]).toContain(me.role); + }); + + it("exposes the limits document used by client validation", async () => { + const limits = await json>>("/limits"); + expect(typeof limits.user?.max_username_len).toBe("number"); + expect(typeof limits.note?.max_files).toBe("number"); + expect(typeof limits.request?.max_page_limit).toBe("number"); + }); + + it("uses the documented page envelope on administrative list routes", async () => { + for (const path of ["/users?limit=1", "/appointments?limit=1", "/payments/plans?limit=1"]) { + expectPage(await json(path)); + } + }); + + it("rejects anonymous protected reads", async () => { + // This raw request deliberately has no cookie, independent of the suite's jar. + const response = await fetch(`${contractBaseUrl}/auth/me`, { signal: AbortSignal.timeout(10_000) }); + expect(response.status).toBe(401); + }); +}); diff --git a/src/api/__tests__/contract/helpers/live-client.ts b/src/api/__tests__/contract/helpers/live-client.ts index 8244371..786651d 100644 --- a/src/api/__tests__/contract/helpers/live-client.ts +++ b/src/api/__tests__/contract/helpers/live-client.ts @@ -3,6 +3,8 @@ * none of its own in bun/node) plus a hard timeout so a dead port fails fast * instead of hanging the run. Boot recipe: see vitest.contract.config.ts. */ +import { expect } from "vitest"; + // The app's tsconfig has no node types (browser build), so reach env this way. const env: Record = (globalThis as { process?: { env: Record } }).process?.env ?? {}; @@ -16,10 +18,17 @@ export const SKIP_MESSAGE = "CONTRACT_BASE_URL=http://127.0.0.1:8081 bun run test:contract"; const TIMEOUT_MS = 10_000; +const MAX_RATE_LIMIT_RETRIES = 12; let cookie = ""; type Init = { method?: string; body?: unknown; headers?: Record }; +function retryDelayMs(response: Response, attempt: number): number { + const retryAfter = Number(response.headers.get("Retry-After")); + if (Number.isFinite(retryAfter) && retryAfter > 0) return retryAfter * 1_000; + return Math.min(1_000 * 2 ** attempt, 5_000); +} + /** Raw request — returns the Response so tests can assert on status codes. */ export async function api(path: string, init: Init = {}): Promise { const headers: Record = { ...init.headers }; @@ -33,20 +42,27 @@ export async function api(path: string, init: Init = {}): Promise { body = JSON.stringify(init.body); } - const res = await fetch(`${contractBaseUrl}${path}`, { - method: init.method ?? "GET", - headers, - body, - redirect: "manual", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); + let res: Response | undefined; + for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt += 1) { + res = await fetch(`${contractBaseUrl}${path}`, { + method: init.method ?? "GET", + headers, + body, + redirect: "manual", + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + // A 429 has not executed the request, so retrying it is safe even for + // contract-suite POST/PATCH probes. Production calls remain unchanged. + if (res.status !== 429 || attempt === MAX_RATE_LIMIT_RETRIES) break; + await new Promise((resolve) => setTimeout(resolve, retryDelayMs(res!, attempt))); + } - const setCookies = res.headers.getSetCookie?.() ?? []; + const setCookies = res!.headers.getSetCookie?.() ?? []; for (const raw of setCookies) { const pair = raw.split(";")[0]; if (pair.startsWith("session=")) cookie = pair; } - return res; + return res!; } /** Request + JSON body, throwing on a non-2xx so setup failures are loud. */ @@ -70,6 +86,14 @@ export async function loginAdmin(): Promise { }); } +/** Exam kinds are school policy, not a globally fixed enum. */ +export async function configuredExamKind(): Promise { + const settings = await json<{ exam_kinds?: Array<{ name?: unknown }> }>("/settings"); + const kind = settings.exam_kinds?.find((entry) => typeof entry.name === "string" && entry.name.trim())?.name; + if (!kind || typeof kind !== "string") throw new Error("GET /settings returned no configured exam kind"); + return kind; +} + /** Smallest valid 1x1 PNG, for the image-upload steps. */ export function pngFile(name: string): File { const bytes = Uint8Array.from( @@ -80,3 +104,18 @@ export function pngFile(name: string): File { ); return new File([bytes], name, { type: "image/png" }); } + +/** Assert the list envelope shared by all paginated REST routes. */ +export function expectPage(data: unknown): asserts data is { + items: unknown[]; + total: number; + limit: number | null; + offset: number; +} { + expect(data).toMatchObject({}); + expect(Array.isArray((data as { items?: unknown }).items)).toBe(true); + expect(typeof (data as { total?: unknown }).total).toBe("number"); + const limit = (data as { limit?: unknown }).limit; + expect(limit === null || typeof limit === "number").toBe(true); + expect(typeof (data as { offset?: unknown }).offset).toBe("number"); +} diff --git a/src/api/__tests__/contract/learning.contract.test.ts b/src/api/__tests__/contract/learning.contract.test.ts new file mode 100644 index 0000000..8eb48dc --- /dev/null +++ b/src/api/__tests__/contract/learning.contract.test.ts @@ -0,0 +1,53 @@ +import { api, configuredExamKind, contractBaseUrl, expectPage, isLive, json, loginAdmin, SKIP_MESSAGE } from "./helpers/live-client"; + +if (!isLive) console.warn(SKIP_MESSAGE); + +describe.skipIf(!isLive)(`learning contract @ ${contractBaseUrl}`, () => { + let courseId = ""; + let examId = ""; + + beforeAll(async () => { + await loginAdmin(); + const tag = `contract-learning-${Date.now()}`; + const course = await json<{ id: string; title: string; kind: string }>("/courses", { + method: "POST", + body: { title: tag, kind: "course" }, + }); + courseId = course.id; + expect(course).toMatchObject({ title: tag, kind: "course" }); + }); + + afterAll(async () => { + if (courseId) await api(`/courses/${courseId}`, { method: "DELETE" }); + }); + + it("returns filtered courses through the standard page envelope", async () => { + const page = await json<{ items: Array<{ id: string }> }>(`/courses?kind=course&q=contract-learning&limit=10`); + expectPage(page); + expect(page.items.some((course) => course.id === courseId)).toBe(true); + }); + + it("supports course subjects and exam-question lists", async () => { + const subject = await json<{ id: string; course: string }>(`/courses/${courseId}/subjects`, { + method: "POST", + body: { name: "contract subject" }, + }); + expect(subject.course).toBe(courseId); + + const examKind = await configuredExamKind(); + const exam = await json<{ id: string; course: string; draft: boolean }>(`/courses/${courseId}/exams`, { + method: "POST", + body: { title: "contract exam", kind: examKind, draft: true }, + }); + examId = exam.id; + expect(exam.course).toBe(courseId); + + const question = await json<{ id: string; exam: string }>(`/exams/${examId}/questions`, { + method: "POST", + body: { subject_id: subject.id, text: "Contract question", kind: "text", points: 1 }, + }); + expect(question.exam).toBe(examId); + expectPage(await json(`/exams/${examId}/questions?limit=10`)); + expectPage(await json(`/courses/${courseId}/exams?limit=10`)); + }); +}); diff --git a/vitest.contract.config.ts b/vitest.contract.config.ts index ee583ec..e73542a 100644 --- a/vitest.contract.config.ts +++ b/vitest.contract.config.ts @@ -25,6 +25,9 @@ export default defineConfig({ globals: true, environment: "node", include: ["src/api/__tests__/contract/**/*.contract.test.ts"], + // The scratch backend rate-limits all requests from its loopback client. + // Running files serially keeps a contract run deterministic and realistic. + fileParallelism: false, testTimeout: 30_000, hookTimeout: 30_000, },