test: end-to-end suites (install.sh, licensing, browser, Android emulator) + runner

tests/e2e (see its README):
- install.mjs: real install.sh in a Debian container - VPN-safe HOST_IP
  detection on simulated hosts, fresh/upgrade/re-run, and the proxy config
  byte-identical to nginx-proxy/nginx.conf (guards rule CS-5)
- license_e2e.py: real cloud + site processes with a throwaway signing key -
  400 days offline, tampered file, clock rollback, expiry deferred to workday
  close, renewal, remote lock
- browser.mjs: web delivery modes (same-origin, plain HTTP by LAN IP, venue
  mode) and the install dialog on Android/iPhone/desktop/no-APK
- android.mjs basics|rediscovery|stacks: pairing, venues, camera, back
  button, restart; IP change / server down / cold start; TLS pinning
  (wrong-key QR, impostor, upgrade, renewal, rediscovery) and UI bundles
  (apply, staged, tampered, APK too old, rollback, two venues) on isolated
  compose stacks built from the repo
- lib/: env (paths, LAN IP autodetect, settings), proc (seeded throwaway
  DBs via demo_seed.py, backends, nginx, Vite, compose stacks), android
  (adb + WebView DevTools, boots the AVD), cdp
- run-all.mjs runs everything fastest-first with a summary
Nothing machine-specific is hard-coded; developer stacks/DBs are never touched.
Results on this machine: install 9/9, license 17/17, browser 22/22,
android basics 19/19, rediscovery 10/10, stacks 21/21.

Pack README: Testing section + rule CS-11 (tests follow the code; run
run-all before a release).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-28 23:38:18 +03:00
co-authored by Claude Opus 5.5
parent f00c99fd36
commit 584dd1e510
14 changed files with 1326 additions and 1 deletions
+124
View File
@@ -0,0 +1,124 @@
// Driving the real app on an Android emulator: real taps/typing via adb,
// state via the debug build's WebView DevTools (lib/cdp.mjs).
import { execFileSync, spawn } from 'node:child_process'
import { existsSync, readdirSync, statSync, writeFileSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { connectWebView } from './cdp.mjs'
import { OUT, WAITER, sleep } from './env.mjs'
export const APP_ID = 'gr.bonamin.xenia'
const SDK = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT
|| (process.platform === 'win32' ? path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk') : path.join(os.homedir(), 'Android', 'Sdk'))
const exe = name => path.join(SDK, ...name.split('/')) + (process.platform === 'win32' ? '.exe' : '')
export const ADB = exe('platform-tools/adb')
export const adb = (...args) => execFileSync(ADB, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
/** Make sure a device is attached; boot the test AVD headless if none is. */
export async function ensureDevice() {
if (/\tdevice$/m.test(adb('devices'))) return
const avd = process.env.AVD || 'Xenia_Test_Phone'
console.log(` booting emulator ${avd} (headless)…`)
spawn(exe('emulator/emulator'), ['-avd', avd, '-no-window', '-no-audio', '-no-boot-anim', '-gpu', 'swiftshader_indirect', '-no-snapshot'],
{ detached: true, stdio: 'ignore' }).unref()
for (let i = 0; i < 90; i++) {
try { if (adb('shell', 'getprop', 'sys.boot_completed').trim() === '1') return } catch {}
await sleep(3000)
}
throw new Error(`emulator ${avd} did not boot — create it in Android Studio or set AVD=<name>`)
}
/** Newest debug APK from `npm run apk:debug` (WebView debugging needs a debug build). */
export function debugApk() {
const dir = path.join(WAITER, 'releases')
const apks = existsSync(dir) ? readdirSync(dir).filter(f => f.endsWith('-debug.apk')) : []
if (!apks.length) throw new Error('no debug APK — run `npm run apk:debug` in waiter_pwa first')
return path.join(dir, apks.sort((a, b) => statSync(path.join(dir, b)).mtimeMs - statSync(path.join(dir, a)).mtimeMs)[0])
}
export function installApp({ fresh = true } = {}) {
if (fresh) { try { adb('uninstall', APP_ID) } catch {} }
adb('install', '-r', debugApk())
}
export const launch = () => adb('shell', 'monkey', '-p', APP_ID, '-c', 'android.intent.category.LAUNCHER', '1')
export const home = () => adb('shell', 'input', 'keyevent', 'KEYCODE_HOME')
export const back = () => adb('shell', 'input', 'keyevent', 'KEYCODE_BACK')
export const clearData = () => adb('shell', 'pm', 'clear', APP_ID)
export const focusedWindow = () => adb('shell', 'dumpsys', 'window').match(/mCurrentFocus=[^}]*\}/)?.[0] || ''
export const shot = name => writeFileSync(path.join(OUT, `${name}.png`), execFileSync(ADB, ['exec-out', 'screencap', '-p']))
/** Attach to the app's WebView over DevTools (the socket changes when the process restarts). */
export async function attach() {
for (let i = 0; i < 40; i++) {
const sock = adb('shell', 'cat', '/proc/net/unix').match(/webview_devtools_remote_\d+/)?.[0]
if (sock) {
adb('forward', 'tcp:9333', `localabstract:${sock}`)
try { return await connectWebView() } catch {}
}
await sleep(750)
}
throw new Error('could not attach to the app WebView (is this a debug build?)')
}
export async function relaunch() {
adb('shell', 'am', 'force-stop', APP_ID)
launch()
await sleep(4000)
return attach()
}
/** Reload inside the running app (a force-stop right after a localStorage write can lose it). */
export async function reloadApp(v, target = '/') {
await v.evaluate(`setTimeout(() => location.replace(${JSON.stringify(target)}), 300)`)
v.close()
await sleep(3500)
return attach()
}
const statusBar = () => Number(adb('shell', 'dumpsys', 'window').match(/statusBars.*?frame=\[0,0\]\[\d+,(\d+)\]/s)?.[1] || 0)
/** Real tap on the element matching a CSS selector (and containing `text`). */
export async function tap(v, selector, text = '', { last = false } = {}) {
const r = await v.evaluate(`(() => {
const els = [...document.querySelectorAll(${JSON.stringify(selector)})].filter(e => e.textContent.includes(${JSON.stringify(text)}))
const b = els[${last ? 'els.length - 1' : '0'}]?.getBoundingClientRect()
return b ? { x: b.x + b.width / 2, y: b.y + b.height / 2, dpr: devicePixelRatio } : null
})()`)
if (!r) throw new Error(`nothing to tap: ${selector} "${text}"`)
adb('shell', 'input', 'tap', String(Math.round(r.x * r.dpr)), String(Math.round(r.y * r.dpr + statusBar())))
}
/** Replace the first input's content by real typing. */
export async function typeInto(v, text) {
await tap(v, 'input')
await sleep(300)
await v.evaluate("document.querySelector('input').select()")
adb('shell', 'input', 'keyevent', 'KEYCODE_DEL')
adb('shell', `input text '${text}'`) // quoted for the device shell (& in URLs)
}
/** Tap a system dialog button (e.g. the camera permission prompt) by its label. */
export function tapDialogButton(label) {
adb('shell', 'uiautomator', 'dump', '/sdcard/ui.xml')
const xml = adb('shell', 'cat', '/sdcard/ui.xml')
const m = xml.match(new RegExp(`text="${label}"[^>]*bounds="\\[(\\d+),(\\d+)\\]\\[(\\d+),(\\d+)\\]"`))
if (!m) throw new Error(`dialog button not found: ${label}`)
adb('shell', 'input', 'tap', String((+m[1] + +m[3]) >> 1), String((+m[2] + +m[4]) >> 1))
}
/** Navigate inside the app without a reload. */
export const goTo = (v, p) => v.evaluate(`history.pushState({}, '', ${JSON.stringify(p)}); dispatchEvent(new PopStateEvent('popstate'))`)
export const venuesState = async v => JSON.parse(await v.evaluate("localStorage.getItem('xenia.venues')"))
export async function setVenues(v, state) {
await v.evaluate(`localStorage.setItem('xenia.venues', ${JSON.stringify(JSON.stringify(state))})`)
await sleep(1200)
}
export const GREEN = 'rgb(34, 197, 94)'
export const connectivityColor = v => v.evaluate("document.querySelector('.connectivity-bar') ? getComputedStyle(document.querySelector('.connectivity-bar')).backgroundColor : 'none'")
// @capgo/capacitor-updater from inside the page
export const UPD = "(window.Capacitor.Plugins.CapacitorUpdater || window.Capacitor.registerPlugin('CapacitorUpdater'))"
+41
View File
@@ -0,0 +1,41 @@
// Minimal Chrome DevTools Protocol client for the app's Android WebView
// (exposed with `adb forward tcp:9333 localabstract:webview_devtools_remote_<pid>`).
// Playwright can't drive an Android WebView's browser context, so this speaks CDP directly.
export async function connectWebView(port = 9333) {
const targets = await fetch(`http://127.0.0.1:${port}/json`).then(r => r.json())
const target = targets.find(t => t.type === 'page')
if (!target) throw new Error('no WebView page target')
const ws = new WebSocket(target.webSocketDebuggerUrl)
await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = reject })
let id = 0
const pending = new Map()
const logs = []
ws.onmessage = ev => {
const msg = JSON.parse(ev.data)
if (msg.id && pending.has(msg.id)) {
const { resolve, reject } = pending.get(msg.id)
pending.delete(msg.id)
msg.error ? reject(new Error(msg.error.message)) : resolve(msg.result)
} else if (msg.method === 'Runtime.consoleAPICalled') {
logs.push(`[${msg.params.type}] ` + msg.params.args.map(a => a.value ?? a.description ?? '').join(' ').slice(0, 300))
} else if (msg.method === 'Runtime.exceptionThrown') {
const d = msg.params.exceptionDetails
logs.push('EXCEPTION ' + (d.exception?.description || d.text).slice(0, 400))
}
}
const send = (method, params = {}) => new Promise((resolve, reject) => {
const msgId = ++id
pending.set(msgId, { resolve, reject })
ws.send(JSON.stringify({ id: msgId, method, params }))
})
await send('Runtime.enable')
await send('Page.enable')
const evaluate = async expression => {
const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })
if (r.exceptionDetails) throw new Error('eval failed: ' + (r.exceptionDetails.exception?.description || r.exceptionDetails.text))
return r.result.value
}
return { send, evaluate, logs, close: () => ws.close() }
}
+71
View File
@@ -0,0 +1,71 @@
// Shared settings for the end-to-end suites. Everything is derived from the repo
// layout or the environment — no machine-specific paths or IPs are hard-coded.
import { mkdirSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const here = path.dirname(fileURLToPath(import.meta.url))
export const E2E = path.resolve(here, '..') // client-services/tests/e2e
export const CS = path.resolve(E2E, '..', '..') // client-services
export const REPO = path.resolve(CS, '..') // xenia-pos (parent)
export const BACKEND = path.join(CS, 'local_backend')
export const WAITER = path.join(CS, 'waiter_pwa')
export const CLOUD = process.env.CLOUD_DIR || path.join(REPO, 'cloud-service', 'cloud_backend')
export const OUT = path.join(E2E, 'out') // screenshots, logs, temp data (gitignored)
mkdirSync(OUT, { recursive: true })
export const PYTHON = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3')
// Playwright browser: system Edge by default; BROWSER_CHANNEL= (empty) uses Playwright's own Chromium
export const BROWSER_CHANNEL = process.env.BROWSER_CHANNEL ?? 'msedge'
// Break-glass login the test backends are started with (never a real account)
export const MASTER = { username: 'e2e', password: 'e2e-pass-123' }
// The Android emulator reaches the host machine at this address
export const EMULATOR_HOST = '10.0.2.2'
/**
* This machine's LAN IPv4 — for "plain HTTP by LAN IP" browser tests.
* LAN_IP wins; otherwise the first address on a non-virtual, non-VPN adapter.
*/
export function lanIp() {
if (process.env.LAN_IP) return process.env.LAN_IP
const skip = /vEthernet|WSL|docker|br-|veth|virtual|vmware|vbox|hyper-v|wireguard|wg\d|tailscale|zerotier|vpn|loopback/i
for (const [name, addrs] of Object.entries(os.networkInterfaces())) {
if (skip.test(name)) continue
const a = (addrs || []).find(x => x.family === 'IPv4' && !x.internal && !x.address.startsWith('169.254.'))
if (a) return a.address
}
throw new Error('Could not detect this machine\'s LAN IP — set LAN_IP=<ip>')
}
/** Tiny PASS/FAIL reporter shared by the suites. */
export function reporter(suite) {
let failures = 0
console.log(`\n── ${suite}`)
return {
check(name, ok, extra = '') {
if (!ok) failures++
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${extra ? ' ' + extra : ''}`)
},
done() {
console.log(failures ? `✗ ${suite}: ${failures} failure(s)` : `✓ ${suite}: all passed`)
return failures
},
}
}
export const sleep = ms => new Promise(r => setTimeout(r, ms))
export async function waitFor(fn, timeoutMs, stepMs = 1000) {
const t0 = Date.now()
while (Date.now() - t0 < timeoutMs) {
try {
const r = await fn()
if (r) return r
} catch {
// not yet
}
await sleep(stepMs)
}
return null
}
+154
View File
@@ -0,0 +1,154 @@
// Starting and stopping what the suites run against: local backends on a
// seeded throwaway database, nginx containers serving the waiter build, the
// Vite dev server, and isolated docker-compose stacks.
import { execFileSync, spawn } from 'node:child_process'
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { BACKEND, CS, MASTER, OUT, PYTHON, WAITER, sleep } from './env.mjs'
/** Kill a process and its children (npx/shell wrappers on Windows). */
export function killTree(child) {
if (!child || child.exitCode !== null) return
if (process.platform === 'win32') {
try { execFileSync('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore' }) } catch {}
} else {
try { process.kill(-child.pid) } catch { child.kill() }
}
}
export async function waitHttp(url, up = true, timeoutMs = 60_000) {
const t0 = Date.now()
while (Date.now() - t0 < timeoutMs) {
const ok = await fetch(url, { signal: AbortSignal.timeout(2000) }).then(() => true, () => false)
if (ok === up) return
await sleep(500)
}
throw new Error(`${url} did not ${up ? 'come up' : 'go down'} within ${timeoutMs / 1000}s`)
}
/**
* A fresh demo-seeded database (demo_seed.py: manager + 4 waiters, 13 tables,
* order history). Seeded once into out/seed.db, then copied per test run.
*/
export function seededDataDir(label = 'data') {
const template = path.join(OUT, 'seed.db')
if (!existsSync(template)) {
console.log(' seeding a demo database (once)…')
const partial = `${template}.partial`
rmSync(partial, { force: true })
execFileSync(PYTHON, ['demo_seed.py'], {
cwd: BACKEND, stdio: 'ignore',
env: { ...process.env, DATABASE_URL: `sqlite:///${partial.replace(/\\/g, '/')}`, PYTHONIOENCODING: 'utf-8' },
})
// Only a database that really holds the demo data becomes the template
const count = execFileSync(PYTHON, ['-c', 'import sqlite3, sys; print(sqlite3.connect(sys.argv[1]).execute("select count(*) from orders").fetchone()[0])', partial], { encoding: 'utf8' })
if (!Number(count)) throw new Error('demo_seed.py produced no orders — check local_backend/demo_seed.py')
renameSync(partial, template)
}
const dir = mkdtempSync(path.join(OUT, `${label}-`))
copyFileSync(template, path.join(dir, 'pos.db'))
return dir
}
/** Local backend (uvicorn) on `port` with its own data dir. Returns { url, dataDir, stop() }. */
export async function startBackend({ port = 8055, siteId = 'test-site-1', siteKey = 'x', cloudUrl = '', dataDir, env = {} } = {}) {
dataDir ??= seededDataDir(`backend-${port}`)
const log = openSync(path.join(dataDir, 'backend.log'), 'a')
const child = spawn(PYTHON, ['-m', 'uvicorn', 'main:app', '--host', '0.0.0.0', '--port', String(port)], {
cwd: BACKEND, stdio: ['ignore', log, log],
env: {
...process.env, DATABASE_URL: `sqlite:///${path.join(dataDir, 'pos.db').replace(/\\/g, '/')}`,
SITE_ID: siteId, SITE_KEY: siteKey, CLOUD_URL: cloudUrl, SECRET_KEY: 'e2e-secret',
MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password, ...env,
},
})
const url = `http://127.0.0.1:${port}`
await waitHttp(`${url}/api/system/health`)
return { url, dataDir, child, stop: async () => { killTree(child); await waitHttp(`${url}/api/system/health`, false).catch(() => {}) } }
}
export async function login(baseUrl) {
const r = await fetch(`${baseUrl}/api/auth/login`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(MASTER),
})
return (await r.json()).access_token
}
/** nginx:alpine serving a waiter build (`dist`) with the waiter's own nginx.conf, /api → host backend. */
export async function serveWaiterBuild({ name, port, dist = path.join(WAITER, 'dist'), backendPort = 8055 }) {
const conf = path.join(OUT, `${name}.nginx.conf`)
writeFileSync(conf, readFileSync(path.join(WAITER, 'nginx.conf'), 'utf8').replace(/http:\/\/backend:8000/g, `http://host.docker.internal:${backendPort}`))
try { execFileSync('docker', ['rm', '-f', name], { stdio: 'ignore' }) } catch {}
execFileSync('docker', ['run', '-d', '--rm', '--name', name, '--add-host', 'host.docker.internal:host-gateway',
'-p', `${port}:80`, '-v', `${conf}:/etc/nginx/conf.d/default.conf:ro`, '-v', `${dist}:/usr/share/nginx/html:ro`, 'nginx:alpine'],
{ stdio: 'ignore', env: { ...process.env, MSYS_NO_PATHCONV: '1' } })
await waitHttp(`http://127.0.0.1:${port}/`)
return { stop: () => { try { execFileSync('docker', ['rm', '-f', name], { stdio: 'ignore' }) } catch {} } }
}
/** Vite dev server pointed at a backend by URL (VITE_SERVER_URL) — the "native-like" venue mode. */
export async function startViteNative({ port = 5180, backendUrl }) {
const log = openSync(path.join(OUT, `vite-${port}.log`), 'w')
const child = spawn('npx', ['vite', '--port', String(port), '--strictPort'], {
cwd: WAITER, shell: process.platform === 'win32', detached: process.platform !== 'win32',
stdio: ['ignore', log, log], env: { ...process.env, VITE_SERVER_URL: backendUrl },
})
await waitHttp(`http://localhost:${port}/`)
await fetch(`http://localhost:${port}/src/main.jsx`).catch(() => {}) // warm the first compile
await sleep(3000)
return { stop: () => killTree(child) }
}
/**
* Isolated docker-compose stack built from this repo (its own project name,
* images, data dir and host ports) — never touches a developer's running stack.
*/
export function composeStack({ project, version, siteId, http, https, manager, extraEnv = {} }) {
const dir = path.join(OUT, project)
mkdirSync(path.join(dir, 'data'), { recursive: true })
mkdirSync(path.join(dir, 'fiscal'), { recursive: true })
if (!existsSync(path.join(dir, 'data', 'pos.db'))) copyFileSync(path.join(seededDataDir(project), 'pos.db'), path.join(dir, 'data', 'pos.db'))
copyFileSync(path.join(CS, 'logo.png'), path.join(dir, 'logo.png'))
const fwd = p => p.replace(/\\/g, '/')
const envFile = path.join(dir, 'e2e.env')
writeFileSync(envFile, Object.entries({
REGISTRY: 'e2e', VERSION: version, SITE_ID: siteId, SITE_KEY: 'x', CLOUD_URL: '', SECRET_KEY: 'e2e-secret',
HOST_IP: '10.0.2.2', TLS_PORT: https, HTTP_PORT: http, MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password,
DATA_PATH: fwd(path.join(dir, 'data')), LOGO_PATH: fwd(path.join(dir, 'logo.png')), FISCAL_PATH: fwd(path.join(dir, 'fiscal')),
...extraEnv,
}).map(([k, v]) => `${k}=${v}`).join('\n') + '\n')
const ports = path.join(dir, 'ports.yml')
writeFileSync(ports, `services:
backend:
ports: !reset []
waiter_pwa:
ports: !reset []
manager_dashboard:
ports: !reset []
netinfo:
profiles: ["off"]
proxy:
ports: !override
- "${http}:80"
- "${manager}:8081"
- "${https}:8443"
`)
const args = ['compose', '-p', project, '--env-file', envFile, '-f', 'docker-compose.yml', '-f', 'docker-compose.dev.yml', '-f', ports]
const compose = (...a) => execFileSync('docker', [...args, ...a], { cwd: CS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
return {
dir,
compose,
async up() {
console.log(` building + starting stack ${project} (${version})…`)
compose('build')
compose('up', '-d', '--force-recreate')
await waitHttp(`http://127.0.0.1:${http}/api/system/health`, true, 180_000)
},
down() {
try { compose('down', '-v') } catch {}
for (const s of ['backend', 'waiter', 'manager']) {
try { execFileSync('docker', ['rmi', `e2e/pos-${s}:${version}`], { stdio: 'ignore' }) } catch {}
}
},
}
}