'use strict'; /* * UPSTREAM e2e (npm run e2e). Boots the real server in-process (temp SQLite file, fast or slow world) and drives real Chromium * through playwright-core. Target: under 3 minutes for the default set. Exit code 1 if any check fails. * * node e2e/run.js all default suites (everything except 'slow') * node e2e/run.js push units only the named suites * E2E_SLOW=1 node e2e/run.js also the slow suite; node e2e/run.js slow runs only it (about 70 s) * 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 * * Suites: desktop phone layout push smoke: sign-up, build, map, nav, layout matrix, push by WebSocket (e2e/run.js) * units movements reconnect slow world (speed 1), seeded buildings and units; flights are moved up like the push suite does (e2e/flows.js) * alliance trade nb pwa fast world; nb = Norwegian (raw keys, English leftovers, live switch and fresh render), pwa = manifest and icons * endgame own world backdated to day 100.5: phase banner, 7 sites, ship to a held site * slow opt-in: no WebSocket at all, the raid must still show up by REST polling (45 s gap) * * What it does NOT do: no combat balance, takeover/capture flows, confederation views or diplomacy moves, no Firefox/WebKit, no real * devices, no real proxy (nginx Proxy Manager), no load. Flights that take real minutes (speed 1, 10 minute minimum latency) are * moved up in the database (UPDATE movements/events + scheduler.arm), the handlers themselves run unchanged. */ const fs = require('fs'); const path = require('path'); const { chromium } = require('playwright-core'); const L = require('./lib.js'); const F = require('./flows.js'); const { check, group, sleep, PROFILES, noErrors, tapper, openFromMore } = L; const SHOTS = process.env.E2E_SHOTS || ''; const want = process.argv.slice(2); const SLOW = ['slow']; // opt-in suites: only by name or with E2E_SLOW=1 const wanted = (n) => (want.length ? want.includes(n) : !SLOW.includes(n) || !!process.env.E2E_SLOW); if (SHOTS) fs.mkdirSync(SHOTS, { recursive: true }); const shot = async (page, name) => { if (SHOTS) await page.screenshot({ path: path.join(SHOTS, name + '.png') }).catch(() => {}); }; // ---------------------------------------------------------------- shared flow pieces 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; } 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(); // An account that lost its operator (world reset) sees a join card and gets a POP with one click. const u = await S.signup('rejoin' + Date.now() % 1e5); S.db.run('DELETE FROM buildings WHERE town_id = ?', u.townId); S.db.run('DELETE FROM towns WHERE owner_id = ?', u.operatorId); S.db.run('DELETE FROM operators WHERE id = ?', u.operatorId); const J = await L.newPage(browser, PROFILES.desktop); await J.page.addInitScript((tok) => { try { localStorage.setItem('upstream.token', tok); } catch (e) { /* ignore */ } }, u.token); await J.page.goto(S.base + '/#/pop'); await check('desktop: account without a POP sees the join card and founds one', async () => { await J.page.waitForSelector('[data-screen="pop"] .btn.primary', { timeout: 15000 }); await J.page.click('[data-screen="pop"] .btn.primary'); await J.page.waitForSelector('.town-name', { timeout: 15000 }); return noErrors(J); }); await J.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(); } } // Units + movements + reports share one slow world (speed 1: a raid really takes half an hour, so the flight is on screen; the // arrival is moved up by hurryMovement, like the push suite does). async function suiteMilitary(browser) { const S = await L.bootServer({ speed: 1 }); try { const U = await F.armedPair(S, 'Alice' + F.uniq(), 'Bob' + F.uniq()); if (wanted('units')) await F.suiteUnits(browser, S, U); if (wanted('movements')) await F.suiteMovements(browser, S, U); if (wanted('reconnect')) await F.suiteReconnect(browser, S); } 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); if (wanted('alliance') || wanted('trade') || wanted('nb') || wanted('pwa')) { const S2 = await L.bootServer({ speed: 4000 }); try { if (wanted('alliance')) await F.suiteAlliance(browser, S2); if (wanted('trade')) await F.suiteTrade(browser, S2); if (wanted('nb')) await F.suiteNorwegian(browser, S2); if (wanted('pwa')) await F.suitePwa(browser, S2); } finally { await S2.close(); } } if (wanted('units') || wanted('movements') || wanted('reconnect')) await suiteMilitary(browser); if (wanted('endgame')) await F.suiteEndgame(browser); if (wanted('slow')) await F.suiteSlow(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); })();