A test fails if docs/schema.sql drifts from the table server.js creates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfmHGGiYUjNcvJoyzdf
157 lines
5.6 KiB
JavaScript
157 lines
5.6 KiB
JavaScript
const { test, before, after } = require('node:test');
|
|
const assert = require('node:assert');
|
|
const fs = require('node:fs');
|
|
const os = require('node:os');
|
|
const path = require('node:path');
|
|
const { DatabaseSync } = require('node:sqlite');
|
|
const { createServer } = require('./server');
|
|
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-leads-'));
|
|
const dbPath = path.join(dir, 'leads.db');
|
|
let server, base;
|
|
|
|
before(async () => {
|
|
server = createServer(dbPath);
|
|
await new Promise((r) => server.listen(0, r));
|
|
base = `http://127.0.0.1:${server.address().port}`;
|
|
});
|
|
after(() => {
|
|
server.close();
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
});
|
|
|
|
const valid = {
|
|
name: 'Aisyah Rahman',
|
|
email: 'aisyah@seripinang.com.my',
|
|
phone: '+60 12-345 6789',
|
|
company: 'Hotel Seri Pinang',
|
|
service: 'Cloud IP PABX',
|
|
utm_source: 'google',
|
|
referrer: 'https://www.google.com/',
|
|
};
|
|
|
|
const post = (body) =>
|
|
fetch(`${base}/api/leads`, {
|
|
method: 'POST',
|
|
headers: { 'content-type': 'application/json', referer: 'https://ads.example.com/' },
|
|
body: typeof body === 'string' ? body : JSON.stringify(body),
|
|
});
|
|
|
|
const rows = () => {
|
|
const db = new DatabaseSync(dbPath);
|
|
const r = db.prepare('SELECT * FROM leads').all();
|
|
db.close();
|
|
return r;
|
|
};
|
|
|
|
test('serves the landing page', async () => {
|
|
const res = await fetch(`${base}/`);
|
|
assert.strictEqual(res.status, 200);
|
|
assert.match(res.headers.get('content-type'), /text\/html/);
|
|
});
|
|
|
|
test('valid lead is stored', async () => {
|
|
const res = await post(valid);
|
|
assert.strictEqual(res.status, 201);
|
|
const r = rows();
|
|
assert.strictEqual(r.length, 1);
|
|
assert.strictEqual(r[0].name, valid.name);
|
|
assert.strictEqual(r[0].company, valid.company);
|
|
assert.strictEqual(r[0].service, 'Cloud IP PABX');
|
|
assert.strictEqual(r[0].utm_source, 'google');
|
|
assert.strictEqual(r[0].referrer, 'https://www.google.com/');
|
|
assert.ok(r[0].created_at);
|
|
});
|
|
|
|
test('missing required field is rejected', async () => {
|
|
const before = rows().length;
|
|
const res = await post({ ...valid, phone: '' });
|
|
assert.strictEqual(res.status, 400);
|
|
assert.ok((await res.json()).error);
|
|
assert.strictEqual(rows().length, before);
|
|
});
|
|
|
|
test('invalid email is rejected', async () => {
|
|
assert.strictEqual((await post({ ...valid, email: 'abc' })).status, 400);
|
|
});
|
|
|
|
test('free email providers are rejected with a friendly message', async () => {
|
|
for (const email of ['a@gmail.com', 'a@Yahoo.com.my', 'a@hotmail.com', 'a@outlook.com', 'a@icloud.com']) {
|
|
const res = await post({ ...valid, email });
|
|
assert.strictEqual(res.status, 400, email);
|
|
assert.match((await res.json()).error, /work email/i);
|
|
}
|
|
});
|
|
|
|
test('unknown service is rejected, missing service is allowed', async () => {
|
|
assert.strictEqual((await post({ ...valid, service: 'Plumbing' })).status, 400);
|
|
const { service, ...noService } = valid;
|
|
assert.strictEqual((await post(noService)).status, 201);
|
|
});
|
|
|
|
test('over-long field is rejected', async () => {
|
|
assert.strictEqual((await post({ ...valid, name: 'x'.repeat(201) })).status, 400);
|
|
});
|
|
|
|
test('non-JSON body is rejected', async () => {
|
|
assert.strictEqual((await post('not json')).status, 400);
|
|
});
|
|
|
|
test('oversized body is rejected', async () => {
|
|
assert.strictEqual((await post({ ...valid, company: 'x'.repeat(11000) })).status, 413);
|
|
});
|
|
|
|
test('honeypot submission is accepted but not stored', async () => {
|
|
const before = rows().length;
|
|
const res = await post({ ...valid, website: 'http://spam.example' });
|
|
assert.strictEqual(res.status, 200);
|
|
assert.strictEqual(rows().length, before);
|
|
});
|
|
|
|
const { spawn } = require('node:child_process');
|
|
|
|
test('missing page file fails at startup, not on a request', () => {
|
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-nopage-'));
|
|
fs.copyFileSync(path.join(__dirname, 'server.js'), path.join(tmp, 'server.js'));
|
|
const { createServer: create } = require(path.join(tmp, 'server.js'));
|
|
assert.throws(() => create(path.join(tmp, 'leads.db')), /ENOENT/);
|
|
fs.rmSync(tmp, { recursive: true, force: true });
|
|
});
|
|
|
|
test('insert waits for a lock held by another process (e.g. an export)', async () => {
|
|
const lock = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', '-e', `
|
|
const { DatabaseSync } = require('node:sqlite');
|
|
const db = new DatabaseSync(${JSON.stringify(dbPath)});
|
|
db.exec('BEGIN EXCLUSIVE');
|
|
console.log('locked');
|
|
setTimeout(() => { db.exec('COMMIT'); db.close(); }, 500);
|
|
`]);
|
|
await new Promise((r) => lock.stdout.once('data', r));
|
|
const res = await post(valid);
|
|
assert.strictEqual(res.status, 201);
|
|
});
|
|
|
|
test('exits promptly on SIGTERM', async () => {
|
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-term-'));
|
|
const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', path.join(__dirname, 'server.js')], {
|
|
env: { ...process.env, PORT: '0', DB_PATH: path.join(tmp, 'leads.db') },
|
|
});
|
|
await new Promise((r) => child.stdout.once('data', r));
|
|
const start = Date.now();
|
|
child.kill('SIGTERM');
|
|
const code = await new Promise((r) => child.on('exit', (c) => r(c)));
|
|
assert.strictEqual(code, 0);
|
|
assert.ok(Date.now() - start < 2000);
|
|
fs.rmSync(tmp, { recursive: true, force: true });
|
|
});
|
|
|
|
test('docs/schema.sql matches the table the server creates', () => {
|
|
const cols = (db) => db.prepare('PRAGMA table_info(leads)').all().map((c) => [c.name, c.type, c.notnull, c.dflt_value, c.pk]);
|
|
const fromDoc = new DatabaseSync(':memory:');
|
|
fromDoc.exec(fs.readFileSync(path.join(__dirname, 'docs', 'schema.sql'), 'utf8'));
|
|
const fromServer = new DatabaseSync(dbPath, { readOnly: true });
|
|
assert.deepStrictEqual(cols(fromDoc), cols(fromServer));
|
|
fromDoc.close();
|
|
fromServer.close();
|
|
});
|