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:
@@ -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 {}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user