From fade816169713b57fc0a032e19f8c3663d7c1818 Mon Sep 17 00:00:00 2001 From: Benjamin Oezcan Date: Thu, 19 Nov 2026 09:47:22 +0100 Subject: [PATCH] test(e2e): playwright - two browsers play online, server shop, offline campaign (P4-2) --- .gitignore | 2 + CLAUDE.md | 5 ++- docs/MULTIPLAYER-PLAN.md | 4 +- eslint.config.js | 4 +- package-lock.json | 46 ++++++++++++++++++++ package.json | 4 +- playwright.config.js | 32 ++++++++++++++ tests/e2e/helpers.js | 31 ++++++++++++++ tests/e2e/offline.spec.js | 28 ++++++++++++ tests/e2e/online.spec.js | 90 +++++++++++++++++++++++++++++++++++++++ tests/e2e/server.js | 17 ++++++++ 11 files changed, 257 insertions(+), 6 deletions(-) create mode 100644 playwright.config.js create mode 100644 tests/e2e/helpers.js create mode 100644 tests/e2e/offline.spec.js create mode 100644 tests/e2e/online.spec.js create mode 100644 tests/e2e/server.js diff --git a/.gitignore b/.gitignore index ac06a52..d9c6b17 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,5 @@ server/node_modules/ server/.env server/data.sqlite* server/*.sqlite* +test-results/ +playwright-report/ diff --git a/CLAUDE.md b/CLAUDE.md index 1feb637..ee80f81 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -137,6 +137,8 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz. `npm --prefix server run db:reset` (DB frisch + Testkonten), `npm run deploy` (= `bash server/deploy/deploy.sh`, `-- --reset-db` setzt die DB zurück), `npm run smoke -- https://roboclash.michael-media.de` (nach jedem Deploy). Zwei Spieler lokal: `?online&slot=1` und `?online&slot=2` in zwei Tabs. + `npm run e2e` = Playwright-Browsertests (`tests/e2e/`, nutzt das installierte Chrome, startet eigenen Server auf + :8099 mit frischer DB): zwei Browser spielen online gegeneinander, Shop gegen Server, Kampagne über `file://`. - Grafik/Sound: `sprite-generator/prompts.py` + `audio.py` → `gen generate`, `gen adopt --all` (Sprites), `gen adopt_scene bg_*` (Hintergründe als JPG), `gen make_tileable tex_floor`, `gen adopt_audio --all`. Fehlende Bilder → Ersatz-Symbol (`RC.pic`), fehlende Sounds → Synth. - `game/uicheck.js` Layout-Selbsttest: `&uicheck` misst Scrollen, Überläufe, Überlappungen, zu kleine Tap-Ziele, @@ -163,7 +165,8 @@ ist die Aufgabenliste – Tasks der Reihe nach, Task-ID im Commit, erledigte Tas REST-Endpunkte und WS-Nachrichten aus `game/protocol.js`. Protokolländerung = `PROTOCOL_VERSION` erhöhen. 6. **Seat/Index-Spiegelung** nur an einer Stelle (`protocol.js`), mit Test. Nie im Spielcode verstreut. 7. **Kampagne bleibt offline:** nach jeder Änderung `game/index.html` per Doppelklick (`file://`) prüfen. - UI-Änderung → `&uicheck` laufen lassen. + UI-Änderung → `&uicheck` laufen lassen. Änderung an UI, Netz, Lobby, Kampf oder Shop → zusätzlich `npm run e2e` + (deckt Online-Kampf und `file://`-Kampagne im echten Browser ab). 8. **Server-Änderungen** auf den Dev-Server (`roboclash.michael-media.de`, derzeit einziges Server-System, darf per `npm run db:reset` zurückgesetzt werden) deployen und dort prüfen. Nie direkt auf dem Server Dateien editieren – nur über das Deploy-Skript. Produktion kommt später als eigene Umgebung. diff --git a/docs/MULTIPLAYER-PLAN.md b/docs/MULTIPLAYER-PLAN.md index 7dcba46..f53d8a7 100644 --- a/docs/MULTIPLAYER-PLAN.md +++ b/docs/MULTIPLAYER-PLAN.md @@ -26,7 +26,7 @@ Shop-Kauf landet in der Server-DB, Kampagne offline über `file://` (headless + - Admin-Seite läuft jetzt unter `/admin/` auf dem Server; `admin/cleanup.js`/`setcoins.js` (Firebase) gelöscht. **Offen / nächste Schritte:** P2-6 (Online-Turnier), P3-1 Rest (SSH-Nutzer `deploy`, Passwort-Login aus), P3-5 -(Logs/Monitoring), P3-6 (Gitea Actions + act_runner), P4-1 voller Bot-Client, P4-2 Playwright, P4-3 Lasttest, +(Logs/Monitoring), P3-6 (Gitea Actions + act_runner), P4-1 voller Bot-Client, P4-3 Lasttest, P4-4 Vorhersage (erst nach Spieltest), P4-5 `game.js` aufteilen (~2000 Zeilen), `tests/sim.test.js:442` (halber Test). Hinweis: Der Smoke-Test legt Gastkonten an (`SmokeA`/`SmokeB`), die in der Rangliste auftauchen können → `--reset-db` beim Deploy räumt auf. @@ -288,7 +288,7 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau. - [ ] **P4-1 Bot-Client** `tools/bot.js`: verbindet sich per WS, nimmt Challenges an, spielt mit `RC.AI`. Nutzbar für Smoke-Tests und als Gegner auf dem Dev-Server. *AK:* `node tools/bot.js --url … --count 20` spielt 10 Matches parallel. -- [ ] **P4-2 Browser-E2E** mit Playwright: zwei Browser-Kontexte, Gast-Login, Lobby, Challenge, Kampf mit `&auto`, +- [x] **P4-2 Browser-E2E** mit Playwright: zwei Browser-Kontexte, Gast-Login, Lobby, Challenge, Kampf mit `&auto`, beide sehen spiegelbildliches Ergebnis. Läuft in CI gegen einen lokal gestarteten Server. - [ ] **P4-3 Lasttest:** 100 Bots / 50 Matches auf dem Dev-Server; Tick-Dauer und CPU dokumentieren. - [ ] **P4-4 Latenz-Komfort:** Vorhersage für den eigenen Roboter (Eingabe sofort lokal anwenden, mit Server-Snapshot diff --git a/eslint.config.js b/eslint.config.js index f54bba4..d19a6e4 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -9,7 +9,7 @@ const gameGlobals = { RC: 'writable', Kit: 'writable', THREE: 'readonly', KIT_AS module.exports = [ { ignores: ['node_modules/**', 'server/node_modules/**', 'release/**', 'game/vendor/**', 'game/kit/**', - 'launcher/**', 'sprite-generator/**', 'tools/shots/**', 'admin/**'], + 'launcher/**', 'sprite-generator/**', 'tools/shots/**', 'admin/**', 'test-results/**', 'playwright-report/**'], }, js.configs.recommended, { @@ -23,7 +23,7 @@ module.exports = [ languageOptions: { sourceType: 'script', globals: { ...globals.browser, ...gameGlobals } }, }, { - files: ['server/**/*.js', 'tests/**/*.js', 'tools/**/*.js', 'eslint.config.js'], + files: ['server/**/*.js', 'tests/**/*.js', 'tools/**/*.js', 'eslint.config.js', 'playwright.config.js'], languageOptions: { sourceType: 'commonjs', globals: { ...globals.node } }, }, { diff --git a/package-lock.json b/package-lock.json index 30f5229..e2320bf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.1.0", "devDependencies": { "@eslint/js": "^9.39.5", + "@playwright/test": "^1.65.1", "eslint": "^9.39.5", "globals": "^16.5.0", "terser": "^5.46.1" @@ -290,6 +291,22 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@playwright/test": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz", + "integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.65.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@types/estree": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", @@ -1037,6 +1054,35 @@ "node": ">=8" } }, + "node_modules/playwright": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz", + "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.65.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", diff --git a/package.json b/package.json index f50e80d..721d869 100644 --- a/package.json +++ b/package.json @@ -14,10 +14,12 @@ "balance": "node tests/balance.js -v", "lint": "eslint .", "dev": "npm --prefix server run dev", - "build:web": "node build-web.mjs" + "build:web": "node build-web.mjs", + "e2e": "playwright test" }, "devDependencies": { "@eslint/js": "^9.39.5", + "@playwright/test": "^1.65.1", "eslint": "^9.39.5", "globals": "^16.5.0", "terser": "^5.46.1" diff --git a/playwright.config.js b/playwright.config.js new file mode 100644 index 0000000..5433ceb --- /dev/null +++ b/playwright.config.js @@ -0,0 +1,32 @@ +// Browser end-to-end tests (npm run e2e). Uses the installed Google Chrome (no browser download) and starts its own +// server on port 8099 with a fresh throw-away database (tests/e2e/server.js). +'use strict'; +const { defineConfig } = require('@playwright/test'); + +const PORT = 8099; + +module.exports = defineConfig({ + testDir: 'tests/e2e', + testMatch: '**/*.spec.js', + timeout: 90 * 1000, + expect: { timeout: 15 * 1000 }, + fullyParallel: false, + workers: 1, + retries: 0, + reporter: [['list']], + use: { + baseURL: `http://127.0.0.1:${PORT}`, + channel: 'chrome', + headless: true, + viewport: { width: 1280, height: 720 }, + launchOptions: { args: ['--enable-unsafe-swiftshader', '--use-angle=swiftshader', '--autoplay-policy=no-user-gesture-required'] }, + trace: 'retain-on-failure', + }, + webServer: { + command: 'node tests/e2e/server.js', + url: `http://127.0.0.1:${PORT}/healthz`, + env: { PORT: String(PORT) }, + reuseExistingServer: false, + timeout: 30 * 1000, + }, +}); diff --git a/tests/e2e/helpers.js b/tests/e2e/helpers.js new file mode 100644 index 0000000..7cf8ecb --- /dev/null +++ b/tests/e2e/helpers.js @@ -0,0 +1,31 @@ +/* Shared steps for the browser tests: log in through the real UI, get from the workshop into the lobby. */ +'use strict'; +const { expect } = require('@playwright/test'); + +const mode = page => page.locator('body').getAttribute('data-mode'); + +// open the game in online mode and log in with name + password through the login card +async function login(page, name, pass) { + await page.goto('/?online'); + await page.locator('#oLogin').fill(name); + await page.locator('#oPass').fill(pass); + await page.locator('#oGo').click(); + await chooseCountry(page); + await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage'); + await expect(page.locator('#hUser')).toContainText(name); +} + +// first start asks for a country - take the default +async function chooseCountry(page) { + const go = page.locator('#cfGo'); + try { await go.waitFor({ timeout: 4000 }); await go.click(); } catch (e) { /* already chosen */ } +} + +async function toLobby(page) { + await page.locator('#bLeague').click(); + await expect(page.locator('body')).toHaveAttribute('data-mode', 'lobby'); +} + +const credits = async page => Number((await page.locator('#hMoney').textContent()).replace(/[^\d]/g, '')); + +module.exports = { mode, login, chooseCountry, toLobby, credits }; diff --git a/tests/e2e/offline.spec.js b/tests/e2e/offline.spec.js new file mode 100644 index 0000000..e61400d --- /dev/null +++ b/tests/e2e/offline.spec.js @@ -0,0 +1,28 @@ +// The offline campaign must keep working without any server (double-click on game/index.html = file://). +'use strict'; +const { test, expect } = require('@playwright/test'); +const path = require('path'); +const { pathToFileURL } = require('url'); + +const file = pathToFileURL(path.join(__dirname, '..', '..', 'game', 'index.html')).href; + +test('campaign runs from file:// : training fight with the AI pilot, layout check passes', async ({ page }) => { + const errors = []; + page.on('pageerror', e => errors.push(e.message)); + await page.goto(file + '?play&fight=2&auto&ff=20&uicheck'); + await expect(page.locator('body')).toHaveAttribute('data-gmode', 'campaign'); + await expect(page.locator('body')).toHaveAttribute('data-mode', /fight|result/); + await expect(page.locator('#uicheck')).toContainText('UI ok'); + expect(errors).toEqual([]); +}); + +test('campaign workshop: buying a part works offline', async ({ page }) => { + await page.goto(file + '?play'); + await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage'); + const money = async () => Number((await page.locator('#hMoney').textContent()).replace(/[^\d]/g, '')); + const before = await money(); + await page.locator('.tab[data-slot="armour"]').click(); + await page.locator('#cards .item:not(:has(.badge)):not(:has(.pr.no))').first().click(); + await page.locator('#detail button[data-act="buy"]').click(); + expect(await money()).toBeLessThan(before); +}); diff --git a/tests/e2e/online.spec.js b/tests/e2e/online.spec.js new file mode 100644 index 0000000..26cf27f --- /dev/null +++ b/tests/e2e/online.spec.js @@ -0,0 +1,90 @@ +// Two real browsers play a live fight through the server: login, lobby, challenge, accept, fight, give up, result. +'use strict'; +const { test, expect } = require('@playwright/test'); +const { login, toLobby, credits, chooseCountry } = require('./helpers'); + +test('michi challenges benni, benni gives up: mirrored result and server-booked rewards', async ({ browser }) => { + const ctxA = await browser.newContext(), ctxB = await browser.newContext(); + const a = await ctxA.newPage(), b = await ctxB.newPage(); + const errors = []; + for (const p of [a, b]) p.on('pageerror', e => errors.push(e.message)); + + await login(a, 'michi', 'Michi2000!'); + await login(b, 'benni', 'Benni2000!'); + const moneyA = await credits(a), moneyB = await credits(b); + await toLobby(a); + await toLobby(b); + + // each sees the other in the lobby + await expect(a.locator('.prow', { hasText: 'benni' })).toBeVisible(); + await expect(b.locator('.prow', { hasText: 'michi' })).toBeVisible(); + + // challenge -> incoming card -> accept -> both are in the fight + await a.locator('.prow', { hasText: 'benni' }).locator('.chal').click(); + await expect(a.locator('#lCancel')).toBeVisible(); + await expect(b.locator('#cYes')).toBeVisible(); + await b.locator('#cYes').click(); + await expect(a.locator('body')).toHaveAttribute('data-mode', 'fight'); + await expect(b.locator('body')).toHaveAttribute('data-mode', 'fight'); + await expect(a.locator('#fN1')).toHaveText('benni'); + await expect(b.locator('#fN1')).toHaveText('michi'); + + // the fight runs on the server: after the countdown michi drives - the clock must tick down + await a.waitForTimeout(4500); + await a.keyboard.down('w'); + await a.waitForTimeout(1500); + await a.keyboard.up('w'); + await expect(a.locator('#fightHud')).not.toContainText('2:00'); + + // benni gives up through the pause card (live: no pause, the fight keeps running) + await b.keyboard.press('p'); + await expect(b.locator('#bGiveUp')).toBeVisible(); + await b.locator('#bGiveUp').click(); + + // result: michi wins, benni loses - never both "victory" (the old mirrored-result bug) + await expect(a.locator('body')).toHaveAttribute('data-mode', 'result', { timeout: 20000 }); + await expect(b.locator('body')).toHaveAttribute('data-mode', 'result', { timeout: 20000 }); + await expect(a.locator('#overlay h1')).toHaveText(/victory/i); + await expect(b.locator('#overlay h1')).toHaveText(/defeat/i); + + // rewards came from the server and survive a reload (server is the authority) + const afterA = await credits(a), afterB = await credits(b); + expect(afterA).toBeGreaterThan(moneyA); + expect(afterB).toBeGreaterThanOrEqual(moneyB); + await a.reload(); + await chooseCountry(a); + await expect(a.locator('body')).toHaveAttribute('data-mode', 'garage'); + await expect.poll(() => credits(a)).toBe(afterA); + + expect(errors, 'no JavaScript errors in either browser').toEqual([]); + await ctxA.close(); await ctxB.close(); +}); + +test('shop purchase is checked and stored by the server', async ({ browser }) => { + const ctx = await browser.newContext(); + const page = await ctx.newPage(); + await page.goto('/?online'); + await page.locator('#oAnon').click(); // guest account on the server + await chooseCountry(page); + await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage'); + const before = await credits(page); + + await page.locator('.tab[data-slot="armour"]').click(); + const item = page.locator('#cards .item:not(:has(.badge)):not(:has(.pr.no))').first(); + await item.click(); + await page.locator('#detail button[data-act="buy"]').click(); + await expect.poll(() => credits(page)).toBeLessThan(before); + const after = await credits(page); + + // what the server stored + const token = await page.evaluate(() => JSON.parse(localStorage.getItem('robotclash.net.session')).idToken); + const res = await page.request.get('/api/online', { headers: { Authorization: 'Bearer ' + token } }); + const srv = await res.json(); + expect(srv.money).toBe(after); + expect(srv.build.armour).toBeTruthy(); + + // the client cannot simply give itself money + const cheat = await page.request.put('/api/online/save', { headers: { Authorization: 'Bearer ' + token }, data: { money: 999999 } }); + expect((await cheat.json()).money).toBe(after); + await ctx.close(); +}); diff --git a/tests/e2e/server.js b/tests/e2e/server.js new file mode 100644 index 0000000..cd7ef83 --- /dev/null +++ b/tests/e2e/server.js @@ -0,0 +1,17 @@ +/* Server for the browser tests: fresh database file every run, seed accounts michi / benni, then the real app. */ +'use strict'; +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const file = path.join(os.tmpdir(), 'robotclash-e2e.sqlite'); +for (const ext of ['', '-wal', '-shm']) fs.rmSync(file + ext, { force: true }); +process.env.DB_FILE = file; +process.env.NODE_ENV = 'test'; // high auth rate limit, no secret warning +process.env.PORT = process.env.PORT || '8099'; + +const { createUser } = require('../../server/auth'); +const economy = require('../../server/economy'); +for (const [name, pass] of [['michi', 'Michi2000!'], ['benni', 'Benni2000!']]) economy.load(createUser({ name, pass, role: 'admin' }).uid); + +require('../../server/app').listen().then(srv => console.log('e2e server on :' + srv.address().port));