summaryrefslogtreecommitdiff
path: root/e2e/helpers
diff options
context:
space:
mode:
Diffstat (limited to 'e2e/helpers')
-rw-r--r--e2e/helpers/server.ts167
-rw-r--r--e2e/helpers/tab.ts188
-rw-r--r--e2e/helpers/table.ts51
3 files changed, 406 insertions, 0 deletions
diff --git a/e2e/helpers/server.ts b/e2e/helpers/server.ts
new file mode 100644
index 0000000..8357421
--- /dev/null
+++ b/e2e/helpers/server.ts
@@ -0,0 +1,167 @@
+/**
+ * Boots the real Dart game server for the E2E specs (PLAN.md Phase 7).
+ *
+ * `bin/main.dart` is compiled to a native executable once (cached under
+ * `e2e/.cache/`, recompiled when `bin/main.dart` is newer) so the
+ * resilience specs can kill and restart the server quickly. Each test gets
+ * a fresh temp saves dir and a free port, so the specs never share state.
+ */
+import {
+ execFileSync,
+ spawn,
+ type ChildProcess
+} from 'node:child_process';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ statSync
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// This file lives in `e2e/helpers/`; the E2E root is one level up.
+const E2E_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const REPO_ROOT = path.resolve(E2E_DIR, '..');
+const SERVER_DIR = path.join(REPO_ROOT, 'server');
+const WEB_DIST = path.join(REPO_ROOT, 'web', 'dist');
+const CACHE_DIR = path.join(E2E_DIR, '.cache');
+const BINARY = path.join(CACHE_DIR, 'xhaven-server');
+const MAIN_DART = path.join(SERVER_DIR, 'bin', 'main.dart');
+
+let compilePromise: Promise<void> | null = null;
+
+/** Compiles the server to a native binary (cached; recompile when stale). */
+export function ensureServerBinary(): Promise<void> {
+ const needsCompile =
+ !existsSync(BINARY) ||
+ statSync(MAIN_DART).mtimeMs > statSync(BINARY).mtimeMs;
+ if (!needsCompile) return Promise.resolve();
+ compilePromise ??= (async () => {
+ mkdirSync(CACHE_DIR, { recursive: true });
+ execFileSync('dart', ['compile', 'exe', 'bin/main.dart', '-o', BINARY], {
+ cwd: SERVER_DIR,
+ stdio: 'inherit',
+ timeout: 300_000
+ });
+ })();
+ return compilePromise;
+}
+
+/** A free TCP port on localhost. */
+export async function freePort(): Promise<number> {
+ const net = await import('node:net');
+ return new Promise((resolve, reject) => {
+ const srv = net.createServer();
+ srv.unref();
+ srv.listen(0, '127.0.0.1', () => {
+ const addr = srv.address();
+ const port = typeof addr === 'object' && addr ? addr.port : 0;
+ srv.close(() => (port ? resolve(port) : reject(new Error('no port'))));
+ });
+ });
+}
+
+export interface RunningServer {
+ /** `http://127.0.0.1:<port>` — open a tab here. */
+ url: string;
+ port: number;
+ /** The temp dir holding game.json / settings.json / seats.json. */
+ savesDir: string;
+ child: ChildProcess;
+ /** SIGKILL the server (crash simulation). */
+ kill(): Promise<void>;
+ /** SIGKILL, then report the exit code. */
+ killAndWait(): Promise<number>;
+}
+
+export interface StartServerOptions {
+ /** Reuse an existing saves dir (restart mid-game). */
+ savesDir?: string;
+ /** Bind a specific port (restart must keep the old port). */
+ port?: number;
+}
+
+/**
+ * Starts the server on a free port (or [opts.port]) with a fresh saves dir
+ * (or [opts.savesDir]) and resolves once `/healthz` answers.
+ */
+export async function startServer(
+ opts: StartServerOptions = {}
+): Promise<RunningServer> {
+ await ensureServerBinary();
+ if (!existsSync(WEB_DIST)) {
+ throw new Error(
+ `web/dist missing — run \`npm run build\` in ${WEB_DIST} first`
+ );
+ }
+ const port = opts.port ?? (await freePort());
+ const savesDir =
+ opts.savesDir ?? mkdtempSync(path.join(tmpdir(), 'xhaven-e2e-'));
+
+ const child = spawn(
+ BINARY,
+ [`--port=${port}`, `--static-dir=${WEB_DIST}`, `--saves-dir=${savesDir}`],
+ { cwd: SERVER_DIR }
+ );
+ let logs = '';
+ child.stdout?.on('data', (d) => (logs += String(d)));
+ child.stderr?.on('data', (d) => (logs += String(d)));
+
+ try {
+ await waitForHttp(`http://127.0.0.1:${port}/healthz`, 90_000);
+ } catch (err) {
+ child.kill('SIGKILL');
+ rmSync(savesDir, { recursive: true, force: true });
+ throw new Error(`server failed to start on port ${port}:\n${logs}\n${String(err)}`);
+ }
+
+ return {
+ url: `http://127.0.0.1:${port}`,
+ port,
+ savesDir,
+ child,
+ kill: () => new Promise((resolve) => {
+ // Already dead (e.g. the spec killed it): nothing to wait for.
+ if (child.exitCode !== null || child.signalCode !== null) {
+ resolve();
+ return;
+ }
+ child.once('exit', () => resolve());
+ child.kill('SIGKILL');
+ }),
+ killAndWait: () =>
+ new Promise<number>((resolve) => {
+ if (child.exitCode !== null || child.signalCode !== null) {
+ resolve(child.exitCode ?? -1);
+ return;
+ }
+ child.once('exit', (code) => resolve(code ?? -1));
+ child.kill('SIGKILL');
+ })
+ };
+}
+
+/** Polls [url] until it answers 2xx (or the timeout elapses). */
+export async function waitForHttp(url: string, timeoutMs: number): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ try {
+ const res = await fetch(url);
+ if (res.ok) return;
+ } catch {
+ // not up yet
+ }
+ if (Date.now() > deadline) {
+ throw new Error(`timed out waiting for ${url}`);
+ }
+ await new Promise((r) => setTimeout(r, 200));
+ }
+}
+
+/** Removes a stale cached binary (used by `npm run e2e:clean`). */
+export function cleanCache(): void {
+ rmSync(CACHE_DIR, { recursive: true, force: true });
+}
diff --git a/e2e/helpers/tab.ts b/e2e/helpers/tab.ts
new file mode 100644
index 0000000..616f783
--- /dev/null
+++ b/e2e/helpers/tab.ts
@@ -0,0 +1,188 @@
+/**
+ * One browser tab on the table (PLAN.md Phase 7): drives the real UI —
+ * menus, character rows, the initiative widget, the draw button — and
+ * asserts on the DOM each connection actually receives (the per-connection
+ * masked state, PLAN.md section 3.4).
+ */
+import type { Locator, Page } from '@playwright/test';
+
+export class Tab {
+ constructor(public readonly page: Page) {}
+
+ /** Loads the game page and waits for the WS handshake to complete. */
+ async open(url: string): Promise<void> {
+ await this.page.goto(url, { waitUntil: 'domcontentloaded' });
+ await this.waitForConnected();
+ }
+
+ /** The "Connecting…" banner is visible until the first `welcome` lands. */
+ async waitForConnected(): Promise<void> {
+ await this.page.waitForSelector('.topbar');
+ await this.page
+ .locator('.banner[role="status"]')
+ .waitFor({ state: 'detached', timeout: 30_000 });
+ }
+
+ // --- main list -----------------------------------------------------------
+
+ /** The character row whose display name is [name]. */
+ row(name: string): Locator {
+ return this.page
+ .locator('.row--character')
+ .filter({ has: this.page.locator('.row__name', { hasText: name }) });
+ }
+
+ /** The monster row whose name is [name]. */
+ monsterRow(name: string): Locator {
+ return this.page
+ .locator('.row--monster')
+ .filter({ has: this.page.locator('.row__name', { hasText: name }) });
+ }
+
+ // --- menus ---------------------------------------------------------------
+
+ /** Opens the main drawer and picks the [label] entry (a menu dialog). */
+ async openMenu(label: string): Promise<void> {
+ await this.page.locator('.topbar__menu').click();
+ await this.page
+ .locator('nav[aria-label="Main menu"]')
+ .getByRole('button', { name: label, exact: true })
+ .click();
+ await this.page.locator('.dialog__overlay').first().waitFor();
+ }
+
+ /** The open dialog titled [title]. */
+ dialog(title: string): Locator {
+ return this.page
+ .locator('.dialog__overlay')
+ .filter({
+ has: this.page.locator('.dialog__title', { hasText: title })
+ });
+ }
+
+ /**
+ * Adds a character via the Add Character menu (level defaults to 1).
+ * Resolves once the row appears — i.e. the server's update arrived.
+ */
+ async addCharacter(name: string, level = 1): Promise<void> {
+ await this.openMenu('Add Character');
+ const dlg = this.dialog('Add Character');
+ const up = dlg.locator('.stepbtn').nth(1);
+ for (let i = 1; i < level; i++) await up.click();
+ await dlg.locator('.menulist__item').filter({ hasText: name }).click();
+ await this.row(name).waitFor({ timeout: 15_000 });
+ }
+
+ /** Picks [scenarioName] (optionally switching to [campaign] first). */
+ async selectScenario(scenarioName: string, campaign?: string): Promise<void> {
+ await this.openMenu('Set Scenario');
+ const dlg = this.dialog('Set Scenario');
+ if (campaign) {
+ await dlg.locator('.campaignbtns button').filter({ hasText: campaign }).click();
+ }
+ await dlg
+ .locator('.menulist__item')
+ .filter({ hasText: scenarioName })
+ .first()
+ .click();
+ await this.page.locator('.dialog__overlay').waitFor({ state: 'detached' });
+ }
+
+ /** Adds a monster via the Add Monsters menu. */
+ async addMonster(name: string, level = 1): Promise<void> {
+ await this.openMenu('Add Monsters');
+ const dlg = this.dialog('Add Monsters');
+ const up = dlg.locator('.stepbtn').nth(1);
+ for (let i = 1; i < level; i++) await up.click();
+ await dlg.locator('.menulist__item').filter({ hasText: name }).first().click();
+ await this.monsterRow(name).waitFor({ timeout: 15_000 });
+ }
+
+ // --- initiative (the server-gated secret) --------------------------------
+
+ /** Enters [value] in this tab's initiative input for [rowName]. */
+ async setInitiative(rowName: string, value: number): Promise<void> {
+ const input = this.row(rowName).locator('input.init__input');
+ await input.waitFor({ timeout: 15_000 });
+ await input.fill(String(value));
+ }
+
+ /** The initiative value shown on [rowName] in this tab (the `.init` cell). */
+ initDisplay(rowName: string): Locator {
+ return this.row(rowName).locator('.init');
+ }
+
+ /** True when [rowName] shows an editable initiative input on this tab. */
+ async hasInitiativeInput(rowName: string): Promise<boolean> {
+ return (await this.row(rowName).locator('input.init__input').count()) > 0;
+ }
+
+ // --- draw / turns ---------------------------------------------------------
+
+ /** Taps Draw (chooseInitiative) or Next Round (playTurns). */
+ async clickDraw(): Promise<void> {
+ await this.page.locator('button.drawbtn').click();
+ }
+
+ /** Waits until the round has been drawn (the button reads Next Round). */
+ async waitForDrawn(): Promise<void> {
+ await this.page
+ .getByRole('button', { name: /Next Round/ })
+ .waitFor({ timeout: 15_000 });
+ }
+
+ /** Waits until a new round is being chosen (the button reads Draw). */
+ async waitForRoundChosen(): Promise<void> {
+ await this.page.getByRole('button', { name: /Draw/ }).waitFor({ timeout: 15_000 });
+ }
+
+ /** Taps the right-hand turn-done zone of [rowName] (playTurns). */
+ async turnDone(rowName: string): Promise<void> {
+ await this.row(rowName).locator('div[aria-label="Turn done"]').click();
+ }
+
+ /** The round counter under the draw button (e.g. "Round 1/1"). */
+ roundLabel(): Locator {
+ return this.page.locator('.drawbtn__round');
+ }
+
+ /** The draw/next-round button's enabled state (players only). */
+ async drawEnabled(): Promise<boolean> {
+ return this.page.locator('button.drawbtn').isEnabled();
+ }
+
+ // --- seats (claim / re-claim) --------------------------------------------
+
+ /**
+ * Opens the figure's status (stat) menu by tapping the row's name, and
+ * returns the open dialog (titled with the figure's display name).
+ */
+ async openStatusMenu(rowName: string): Promise<Locator> {
+ await this.row(rowName).locator('.row__name').click();
+ const dlg = this.dialog(rowName);
+ await dlg.waitFor({ timeout: 15_000 });
+ return dlg;
+ }
+
+ /** The "Claim" chip on [rowName] (visible while the character is unclaimed). */
+ claimChip(rowName: string): Locator {
+ return this.row(rowName).locator('button.chip--claim');
+ }
+
+ /** Clicks the Claim chip on [rowName]. */
+ async claim(rowName: string): Promise<void> {
+ await this.claimChip(rowName).click();
+ }
+
+ // --- misc -----------------------------------------------------------------
+
+ /** The current toast text (server errors / scenario events), if any. */
+ toast(): Locator {
+ return this.page.locator('.toast[role="status"]');
+ }
+
+ /** Closes this tab's page (the server sees the connection drop). */
+ async closePage(): Promise<void> {
+ await this.page.close();
+ }
+}
diff --git a/e2e/helpers/table.ts b/e2e/helpers/table.ts
new file mode 100644
index 0000000..9641a24
--- /dev/null
+++ b/e2e/helpers/table.ts
@@ -0,0 +1,51 @@
+/**
+ * The `table` fixture: one real Dart server + a factory for browser tabs.
+ *
+ * Each `newTab()` opens a fresh browser context (its own cookie jar → its
+ * own session id on the server), so two tabs are two independent players /
+ * spectators — exactly the deployment model (PLAN.md section 3.3).
+ */
+import { test as base, expect, type BrowserContext, type Page } from '@playwright/test';
+
+import { startServer, type RunningServer } from './server.js';
+import { Tab } from './tab.js';
+
+export interface OpenTab {
+ tab: Tab;
+ page: Page;
+ context: BrowserContext;
+}
+
+export interface Table {
+ server: RunningServer;
+ /** Opens a new browser tab (fresh session) on the table. */
+ newTab(): Promise<OpenTab>;
+}
+
+interface Opened {
+ context: BrowserContext;
+ page: Page;
+}
+
+export const test = base.extend<{ table: Table }>({
+ table: async ({ browser }, use) => {
+ const server = await startServer();
+ const opened: Opened[] = [];
+ await use({
+ server,
+ newTab: async () => {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ opened.push({ context, page });
+ return { tab: new Tab(page), page, context };
+ }
+ });
+ for (const { context, page } of opened) {
+ await page.close().catch(() => {});
+ await context.close().catch(() => {});
+ }
+ await server.kill();
+ }
+});
+
+export { expect };