'use strict'; /* * Shared test helpers (no tests in here). An in-memory server on port 0 with a fake clock and no background timer: * events only run when a request, a command or the test calls scheduler.runDue(). * * const { createTestServer } = require('./helpers'); * const t = await createTestServer(); * const alice = await t.signup('alice'); // { token, userId, operatorId, townId, name } * const r = await t.api('/alliances', { method: 'POST', body: { name: 'X', tag: 'X1' } }, alice.token); * t.clock.advance(3600e3); t.srv.scheduler.runDue(); * await t.close(); */ const assert = require('node:assert'); const { createServer } = require('../server'); const { FakeClock } = require('../server/clock'); // ---- optional response contract check: every 2xx JSON body must satisfy its route's declared `response` schema // (server/routes/schemas.js), error bodies the Error schema. Opt-in: createTestServer({ contract: true }). let contractRouter = null; function contract() { if (contractRouter) return contractRouter; const { Router } = require('../server/http'); const routes = require('../server/routes'); const router = new Router(); routes.register(router, new Proxy({}, { get: () => new Proxy(function () {}, { get: () => () => null, apply: () => null }) })); contractRouter = { router, schemas: require('../server/routes/schemas').schemas }; return contractRouter; } function conforms(schemas, schema, v, path, errs) { if (schema.$ref) return conforms(schemas, schemas[schema.$ref], v, path, errs); const types = Array.isArray(schema.type) ? schema.type : [schema.type]; if (v === null) { if (!types.includes('null')) errs.push(path + ' is null'); return; } const t = types.find((x) => x !== 'null'); if (t === 'integer') { if (!Number.isInteger(v)) errs.push(path + ' not an integer: ' + JSON.stringify(v)); } else if (t === 'number') { if (typeof v !== 'number') errs.push(path + ' not a number'); } else if (t === 'string') { if (typeof v !== 'string') errs.push(path + ' not a string'); } else if (t === 'boolean') { if (typeof v !== 'boolean') errs.push(path + ' not a boolean'); } else if (t === 'array') { if (!Array.isArray(v)) errs.push(path + ' not an array'); else if (schema.items) v.forEach((x, i) => conforms(schemas, schema.items, x, path + '[' + i + ']', errs)); } else if (t === 'object') { if (typeof v !== 'object' || Array.isArray(v)) { errs.push(path + ' not an object'); return; } for (const k of schema.required || []) if (!(k in v)) errs.push(path + '.' + k + ' missing'); for (const k of Object.keys(schema.properties || {})) if (k in v) conforms(schemas, schema.properties[k], v[k], path + '.' + k, errs); } } function checkContract(method, path, status, body) { const { router, schemas } = contract(); const found = router.find(method, path.split('?')[0].replace(/^\/api\/v1/, '')); if (!found || !found.route) return; const errs = []; conforms(schemas, status < 300 ? (found.route.meta.response || { $ref: 'Ok' }) : { $ref: 'Error' }, body, '', errs); if (errs.length) throw new assert.AssertionError({ message: method + ' ' + path + ' -> ' + status + ' breaks its response schema: ' + errs.join('; ') + ' in ' + JSON.stringify(body).slice(0, 400) }); } async function createTestServer(o) { o = o || {}; const clock = o.clock || new FakeClock(); const srv = await createServer(Object.assign({ port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false, log: () => {}, // many signups and calls from one IP: lift the per-IP/token/auth rate limits ipRate: 1e6, ipBurst: 1e6, tokenRate: 1e6, tokenBurst: 1e6, authRate: 1e6, authBurst: 1e6, }, o.server || {})); const base = 'http://127.0.0.1:' + srv.port + '/api/v1'; // api(path, { method, body, headers }, token) -> { status, body, headers } async function api(path, opts, token) { opts = opts || {}; const headers = Object.assign({ 'content-type': 'application/json' }, opts.headers || {}); if (token) headers.authorization = 'Bearer ' + token; const r = await fetch(base + path, { method: opts.method || 'GET', headers, body: opts.body === undefined ? undefined : JSON.stringify(opts.body) }); const out = { status: r.status, body: await r.json(), headers: r.headers }; if (o.contract) checkContract(opts.method || 'GET', path, out.status, out.body); return out; } const names = new Map(); async function signup(name) { const r = await api('/auth/signup', { method: 'POST', body: { username: name, password: 'correct horse battery' } }); assert.equal(r.status, 201, 'signup ' + name + ': ' + JSON.stringify(r.body)); const op = r.body.operators[0]; const u = { token: r.body.token, userId: r.body.user.id, operatorId: op.id, townId: op.towns[0].id, name }; names.set(name, u); return u; } // Set a building level directly (tests that need a Peering office without playing through the build chain). function setBuilding(townId, type, level) { srv.db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?) ON CONFLICT (town_id, key) DO UPDATE SET level = excluded.level', townId, type, type, level); } // signup + Peering office level (default 1), ready to found or join an alliance. async function signupPeering(name, level) { const u = await signup(name); setBuilding(u.townId, 'peering_office', level === undefined ? 1 : level); return u; } // Bulk operators without the scrypt cost and without a usable token (drive them through srv.commands.run). function quickSignup(name) { const r = srv.commands.run('signup', { username: name, passHash: 'x', tokenHash: require('crypto').randomBytes(16).toString('hex'), device: 'test' }); return { userId: r.userId, operatorId: r.operatorId, townId: r.townId, name }; } const close = () => srv.close(); return { srv, clock, api, signup, signupPeering, quickSignup, setBuilding, close, base }; } module.exports = { createTestServer, checkContract };