Upstream/e2e/run.js
jvanvik cc0524de5e Smoke e2e, docs consistency pass, status summary
Built: e2e/run.js + lib.js (playwright-core, in-process server, temp DB): desktop flow, phone touch portrait/landscape, layout matrix on 5 viewports x pop/map/trade/world (overflow + console errors), WebSocket push incoming-banner without reload. 61/61 checks, ~54 s, identical over 4 runs; the push and overflow checks were shown to fail when the behaviour is removed.
Docs: fixed stale numbers/claims in DESIGN, DECISIONS, BALANCE, API (undocumented routes, rate limits, notification types), DEPLOY, NEXT (status-at-a-glance on top). Deploy path exercised in a scratch dir: migrations, healthz, signup/build, admin CLI, SIGKILL catch-up, backup restore.

Tested: npm test 207/207, npm run e2e 61/61, bot run 50x14d INVARIANTS OK.
NOT tested: Chromium only; no systemd/nginx Proxy Manager/Node 22.13 run; e2e does not cover units, alliances, messages, trade or end-game flows beyond empty-state rendering; no nb, PWA or polling-fallback e2e; docs/workflows/ still empty.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 20:34:35 +02:00

280 lines
15 KiB
JavaScript

'use strict';
/*
* UPSTREAM smoke e2e (npm run e2e). Boots the real server in-process (temp SQLite file, fast world) and drives real Chromium
* through playwright-core. Target: 1-2 minutes. Exit code 1 if any check fails.
*
* node e2e/run.js all suites
* node e2e/run.js push layout only the named suites (desktop, phone, layout, push)
* E2E_HEADED=1 node e2e/run.js watch it
* E2E_SHOTS=dir node e2e/run.js save a screenshot after each flow / on each failure into dir
*
* What it does NOT do: it is not the full suite (no combat balance, no alliance/trade flows, no Firefox/WebKit, no real proxy).
*/
const fs = require('fs');
const path = require('path');
const { chromium } = require('playwright-core');
const L = require('./lib.js');
const { check, group, sleep, PROFILES } = L;
const SHOTS = process.env.E2E_SHOTS || '';
const want = process.argv.slice(2);
const wanted = (n) => !want.length || want.includes(n);
if (SHOTS) fs.mkdirSync(SHOTS, { recursive: true });
const shot = async (page, name) => { if (SHOTS) await page.screenshot({ path: path.join(SHOTS, name + '.png') }).catch(() => {}); };
const noErrors = (p, label) => (p.errors.length ? (label || 'console') + ' errors:\n' + p.errors.join('\n') : true);
// ---------------------------------------------------------------- shared flow pieces
// Tap/click that does the right thing for the profile (real touch events on phones, real mouse on desktop).
const tapper = (page, touch) => (sel, opts) => (touch ? page.tap(sel, opts) : page.click(sel, opts));
async function signUpThroughUi(P, name, touch) {
const tap = tapper(P.page, touch);
await P.page.goto(P.base + '/');
await P.page.waitForSelector('.auth-form');
await tap('.auth-form .linklike'); // login -> signup
await P.page.fill('#f-user', name);
await P.page.fill('#f-pass', L.PASSWORD);
await tap('.auth-form button[type=submit]');
await P.page.waitForSelector('#nav:not([hidden])', { timeout: 15000 });
await P.page.waitForSelector('.town-name');
}
async function buildFieldAndWait(page, touch) {
const tap = tapper(page, touch);
const before = await page.evaluate(() => { const t = document.querySelector('.tile[data-key="f1"]'); return t ? t.innerText.trim() : null; });
if (before === null) throw new Error('no f1 tile on the POP screen');
await tap('.tile[data-key="f1"]');
await page.waitForSelector('.sheet .btn.primary');
await tap('.sheet .btn.primary');
await page.waitForSelector('.q-item', { timeout: 5000 });
const t1 = (await page.innerText('.q-item')).replace(/\s+/g, ' ');
if (!/\d:\d\d/.test(t1)) throw new Error('queue item shows no countdown: ' + JSON.stringify(t1));
await page.waitForFunction(() => !document.querySelector('.q-item'), null, { timeout: 45000 }); // the countdown reaches zero and the item leaves the queue
await page.waitForFunction((b) => { const t = document.querySelector('.tile[data-key="f1"]'); return t && t.innerText.trim() !== b; }, before, { timeout: 8000 });
return { before, after: await page.evaluate(() => document.querySelector('.tile[data-key="f1"]').innerText.trim()), queue: t1 };
}
// Cable the tapped map tile: tap near the middle of the canvas, expect a tile info sheet.
async function mapTap(page, touch) {
await page.evaluate(() => App.go('map'));
await page.waitForSelector('[data-screen="map"]:not([hidden]) .map-canvas');
await sleep(1200); // first chunk fetch + draw
const box = await page.locator('.map-canvas').boundingBox();
if (!box || box.width < 50 || box.height < 50) throw new Error('map canvas has no size: ' + JSON.stringify(box));
const x = box.x + box.width / 2 + 3, y = box.y + box.height / 2 + 5;
if (touch) await page.touchscreen.tap(x, y); else await page.mouse.click(x, y);
await page.waitForSelector('.sheet .sheet-title', { timeout: 4000 });
const title = (await page.innerText('.sheet .sheet-title')).trim();
if (!title) throw new Error('tile sheet has no title');
await page.keyboard.press('Escape');
await page.waitForSelector('.sheet', { state: 'detached', timeout: 3000 }).catch(() => {});
return title;
}
// Open a "More" screen (Rankings, Alerts, Settings, Trade, World) the way a player does: nav -> More -> row.
async function openFromMore(page, touch, id, label) {
const tap = tapper(page, touch);
await tap('#nav [data-screen="more"]');
await page.waitForSelector('.more-list .row-btn');
await page.locator('.more-list .row-btn', { hasText: label }).first().waitFor({ timeout: 3000 });
await tap('.more-list .row-btn:has-text("' + label + '")');
await page.waitForSelector('[data-screen="' + id + '"]:not([hidden])', { timeout: 5000 });
await sleep(500); // let its first fetch land (errors show up here)
}
async function navReachable(page, vw, vh) {
return page.evaluate(([w, h]) => {
const nav = document.getElementById('nav');
const nr = nav.getBoundingClientRect();
if (nr.width < 20 || nr.height < 20) return 'nav has no size';
if (nr.left < -1 || nr.top < -1 || nr.right > w + 1 || nr.bottom > h + 1) return 'nav outside the viewport: ' + JSON.stringify(nr);
const bad = [];
for (const b of nav.children) {
const r = b.getBoundingClientRect();
if (r.width < 30 || r.height < 30) { bad.push(b.dataset.screen + ' too small ' + Math.round(r.width) + 'x' + Math.round(r.height)); continue; }
const el = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2);
if (!el || !b.contains(el)) bad.push(b.dataset.screen + ' covered by ' + (el ? el.tagName + '.' + el.className : 'nothing'));
}
return bad.length ? bad.join('; ') : null;
}, [vw, vh]);
}
// The core player flow, used by desktop, phone portrait and phone landscape.
async function coreFlow(P, name, touch, signup) {
const { page } = P;
const tap = tapper(page, touch);
if (signup) {
await check(name + ': sign up through the form, land on the POP screen', async () => {
await signUpThroughUi(P, name.replace(/\W+/g, '') + Date.now() % 1e5, touch);
const title = (await page.innerText('.town-name')).trim();
if (!title) return 'empty POP name';
const tiles = await page.locator('.tile[data-key]').count();
if (tiles < 16) return 'expected >= 16 resource field tiles, got ' + tiles;
});
} else {
await page.goto(P.base + '/#/pop');
await page.waitForSelector('.town-name');
}
await check(name + ': build a field, countdown runs, level goes up', async () => {
const r = await buildFieldAndWait(page, touch);
if (r.before === r.after) return 'tile did not change';
});
await shot(page, name.replace(/\W+/g, '-') + '-pop');
await check(name + ': map opens, tapping a tile opens its sheet', async () => { await mapTap(page, touch); });
await shot(page, name.replace(/\W+/g, '-') + '-map');
for (const [id, label] of [['rankings', 'Rankings'], ['alerts', 'Alerts'], ['settings', 'Settings']]) {
await check(name + ': ' + label + ' screen opens from More', async () => { await openFromMore(page, touch, id, label); });
}
await check(name + ': bottom nav is reachable (inside viewport, nothing covers the buttons)', async () => {
const vp = page.viewportSize();
return (await navReachable(page, vp.width, vp.height)) || true;
});
await check(name + ': nav tab switches screens (POP <-> Map <-> Units)', async () => {
for (const id of ['pop', 'map', 'units', 'pop']) {
await tap('#nav [data-screen="' + id + '"]');
await page.waitForSelector('[data-screen="' + id + '"]:not([hidden])', { timeout: 4000 });
}
});
await check(name + ': no horizontal scroll on any screen visited', async () => {
for (const id of ['pop', 'map', 'rankings', 'alerts', 'settings']) {
await page.evaluate((s) => App.go(s), id);
await page.waitForSelector('[data-screen="' + id + '"]:not([hidden])');
await sleep(350);
const o = await L.overflowReport(page);
if (o) return id + ': ' + o;
}
});
await check(name + ': no console errors, warnings, page errors or failed requests', async () => noErrors(P));
}
// ---------------------------------------------------------------- suites
async function suiteDesktop(browser, S) {
group('1. desktop 1280x800');
const P = await L.newPage(browser, PROFILES.desktop);
P.base = S.base;
await coreFlow(P, 'desktop', false, true);
await P.ctx.close();
}
async function suitePhone(browser, S) {
group('2a. phone touch, portrait 390x844');
let P = await L.newPage(browser, PROFILES.phone);
P.base = S.base;
await coreFlow(P, 'phone portrait', true, true);
await P.ctx.close();
group('2b. phone touch, landscape 844x390');
const u = await S.signup('landscape' + Date.now() % 1e5);
P = await L.openSignedIn(browser, S, u, PROFILES.landscape);
P.base = S.base;
await check('landscape: touch is on', async () => (await P.page.evaluate(() => navigator.maxTouchPoints > 0)) || 'maxTouchPoints is 0');
await coreFlow(P, 'phone landscape', true, false);
await P.ctx.close();
}
async function suiteLayout(browser, S) {
group('3. layout matrix: pop / map / trade / world, no overflow, no console errors');
const viewports = [[360, 640, true], [390, 844, true], [844, 390, true], [768, 1024, false], [1280, 800, false]];
const u = await S.signup('layout' + Date.now() % 1e5);
for (const [w, h, touch] of viewports) {
const ctx = touch ? { viewport: { width: w, height: h }, hasTouch: true, isMobile: true, deviceScaleFactor: 2 } : { viewport: { width: w, height: h } };
const P = await L.openSignedIn(browser, S, u, ctx);
for (const id of ['pop', 'map', 'trade', 'world']) {
await check(w + 'x' + h + ' ' + id + ': renders, no horizontal overflow', async () => {
await P.page.evaluate((s) => App.go(s), id);
await P.page.waitForSelector('[data-screen="' + id + '"]:not([hidden])', { timeout: 5000 });
await sleep(id === 'map' ? 1200 : 600);
const visible = await P.page.evaluate((s) => { const el = document.querySelector('[data-screen="' + s + '"]'); const r = el.getBoundingClientRect(); return r.width > 50 && r.height > 50 && el.innerText.trim().length + el.querySelectorAll('canvas').length > 0; }, id);
if (!visible) return 'screen empty or zero size';
await shot(P.page, 'layout-' + w + 'x' + h + '-' + id);
return (await L.overflowReport(P.page)) || true;
});
}
await check(w + 'x' + h + ': nav reachable, no console errors', async () => {
const n = await navReachable(P.page, w, h);
if (n) return n;
return noErrors(P);
});
await P.ctx.close();
}
}
// Push needs a slow world (a raid must stay in flight for a while), so it gets its own server at speed 1.
async function suitePush(browser) {
group('4. push: incoming raid shows on the defender without a reload (WebSocket)');
const S = await L.bootServer({ speed: 1 });
try {
const alice = await S.signup('Alice'), bob = await S.signup('Bob');
const aT = S.db.get('SELECT * FROM towns WHERE id = ?', alice.townId);
L.placeTown(S, bob.townId, aT.x + 4, aT.y + 1);
S.db.run('UPDATE operators SET protection_until = 0');
L.setBuildings(S, alice.townId, { core_router: 10, ops_lab: 6, noc: 5, rack_hall: 6, battery_bank: 6 });
for (const k of ['f13', 'f14', 'f15', 'f16']) S.db.run('UPDATE buildings SET level = 8 WHERE town_id = ? AND key = ?', alice.townId, k);
S.db.run('UPDATE towns SET battery = 900, footprint = 100 WHERE id = ?', alice.townId);
L.giveUnits(S, alice.townId, { script_crew: 40 });
const P = await L.openSignedIn(browser, S, bob, PROFILES.desktop);
const { page } = P;
const hasBanner = () => page.evaluate(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; });
await check('defender: WebSocket connects, no banner yet', async () => {
await page.waitForFunction(() => window.App && App.ws && App.ws.open, null, { timeout: 10000 });
if (await hasBanner()) return 'banner visible before any raid';
await page.evaluate(() => { window.__noReload = 'still-here'; });
});
let sentAt = 0;
await check('attacker launches a raid at the defender through the API', async () => {
sentAt = Date.now();
await S.api('/movements', 'POST', { fromTownId: alice.townId, type: 'raid', toTownId: bob.townId, units: { script_crew: 20 }, confirmEndProtection: true }, alice.token);
});
await check('defender: incoming banner appears by push (<= 6 s), same page, no reload', async () => {
await page.waitForFunction(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; }, null, { timeout: 6000, polling: 100 });
const ms = Date.now() - sentAt;
const marker = await page.evaluate(() => window.__noReload);
if (marker !== 'still-here') return 'page was reloaded';
const mode = await page.evaluate(() => App.ws.open);
if (!mode) return 'socket not open when the banner showed: it came from polling, not push';
console.log(' (banner after ' + ms + ' ms)');
await shot(page, 'push-banner');
});
await check('defender: Moves nav badge shows the incoming raid', async () => {
await page.waitForFunction(() => { const b = document.querySelector('#nav [data-screen="movements"] .nav-badge'); return b && !b.hidden && b.textContent.trim() !== ''; }, null, { timeout: 3000 });
});
await check('raid arrives (accelerated): banner goes away and the report badge appears by push', async () => {
const mv = S.db.get("SELECT * FROM movements WHERE status = 'out' ORDER BY id DESC LIMIT 1");
if (!mv) throw new Error('no movement in flight');
const at = Date.now() + 2500;
S.db.run('UPDATE movements SET arrive_at = ? WHERE id = ?', at, mv.id);
S.db.run("UPDATE events SET due_at = ? WHERE status = 'pending' AND type = 'arrive' AND payload LIKE ?", at, '%"movementId":' + mv.id + '%');
S.srv.scheduler.arm();
await page.waitForFunction(() => App.mil && App.mil.reportsUnread > 0, null, { timeout: 12000, polling: 100 });
await page.waitForFunction(() => { const el = document.querySelector('.mil-banner'); return !el || el.hidden; }, null, { timeout: 4000 });
if ((await page.evaluate(() => window.__noReload)) !== 'still-here') return 'page was reloaded';
});
await check('defender page: no console errors', async () => noErrors(P));
await P.ctx.close();
} finally { await S.close(); }
}
// ---------------------------------------------------------------- main
(async () => {
const t0 = Date.now();
let S = null, browser = null;
const hardStop = setTimeout(() => { console.error('\nE2E TIMEOUT after 5 min'); process.exit(2); }, 5 * 60 * 1000); hardStop.unref();
try {
browser = await chromium.launch({ headless: !process.env.E2E_HEADED });
if (wanted('desktop') || wanted('phone') || wanted('layout')) S = await L.bootServer({ speed: 4000 });
if (wanted('desktop')) await suiteDesktop(browser, S);
if (wanted('phone')) await suitePhone(browser, S);
if (wanted('layout')) await suiteLayout(browser, S);
if (wanted('push')) await suitePush(browser);
} catch (e) {
L.record('harness: unexpected exception', false, e && e.stack || String(e));
} finally {
if (browser) await browser.close().catch(() => {});
if (S) await S.close().catch(() => {});
}
const failed = L.summary();
console.log('elapsed ' + Math.round((Date.now() - t0) / 1000) + ' s');
process.exit(failed ? 1 : 0);
})();