zappier-account-balance/test/health.test.js

73 lines
2.4 KiB
JavaScript

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { DatabaseSync } from 'node:sqlite';
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
function seedBillingDb(dbPath) {
const db = new DatabaseSync(dbPath);
db.exec(`
CREATE TABLE customers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
verae_user_id TEXT,
balance_cents INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE usage_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_id TEXT NOT NULL,
endpoint_id TEXT NOT NULL,
cents INTEGER NOT NULL,
metadata_bytes INTEGER NOT NULL DEFAULT 0,
attachment_bytes INTEGER NOT NULL DEFAULT 0,
timestamp_ms INTEGER NOT NULL
);
`);
db.prepare(
`INSERT INTO customers (id, name, verae_user_id, balance_cents) VALUES (?, ?, ?, ?)`,
).run('cust_1', 'Ada (free)', 'vu_ada', 0);
const now = Date.now();
const ins = db.prepare(
`INSERT INTO usage_entries (customer_id, endpoint_id, cents, timestamp_ms) VALUES (?, ?, ?, ?)`,
);
for (let i = 0; i < 3; i++) ins.run('cust_1', 'timestamp', 10, now - i * 1000);
db.close();
}
test('account-balance health and statement from billing.db facade', async () => {
const port = 18010;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ab-facade-'));
const billingDb = path.join(dir, 'billing.db');
seedBillingDb(billingDb);
const child = spawn(process.execPath, ['src/server.js'], {
cwd: root,
env: {
...process.env,
PORT: String(port),
BILLING_DB: billingDb,
EDGE_URL: '',
FACADE: '1',
},
stdio: ['ignore', 'pipe', 'pipe'],
});
await new Promise((r) => setTimeout(r, 500));
try {
const h = await (await fetch(`http://127.0.0.1:${port}/health`)).json();
assert.equal(h.role, 'zappier-account-balance');
assert.equal(h.facade, true);
const st = await (await fetch(`http://127.0.0.1:${port}/statement/cust_1`)).json();
assert.equal(st.customerId, 'cust_1');
assert.equal(st.name, 'Ada (free)');
assert.equal(st.prepaidCents, 0);
assert.equal(st.usage.length, 3);
assert.equal(st.source, 'billing.db');
} finally {
child.kill('SIGTERM');
fs.rmSync(dir, { recursive: true, force: true });
}
});