Files
ins-landing-page/server.test.js
T

160 lines
6.0 KiB
JavaScript

// Run with `npm test` (starts a throwaway Postgres), or set TEST_DATABASE_URL=postgres://user:pass@host:port/db
// Each run creates its own schema and drops it afterwards, so existing tables are never touched.
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 { spawn } = require('node:child_process');
const { Pool } = require('pg');
const { createServer } = require('./server');
const adminUrl = process.env.TEST_DATABASE_URL;
if (!adminUrl) throw new Error('Set TEST_DATABASE_URL to a Postgres the tests may create a schema in');
const schema = `test_${process.pid}_${Date.now()}`;
const withSchema = (s) => {
const u = new URL(adminUrl);
u.searchParams.set('options', `-c search_path=${s}`);
return u.toString();
};
const dbUrl = withSchema(schema);
const admin = new Pool({ connectionString: adminUrl });
let server, base;
before(async () => {
await admin.query(`CREATE SCHEMA ${schema}`);
server = await createServer(dbUrl);
await new Promise((r) => server.listen(0, r));
base = `http://127.0.0.1:${server.address().port}`;
});
after(async () => {
await new Promise((r) => server.close(r));
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
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' },
body: typeof body === 'string' ? body : JSON.stringify(body),
});
const rows = async () => (await admin.query(`SELECT * FROM ${schema}.leads ORDER BY id`)).rows;
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 = await 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 instanceof Date);
});
test('missing required field is rejected', async () => {
const before = (await rows()).length;
const res = await post({ ...valid, phone: '' });
assert.strictEqual(res.status, 400);
assert.ok((await res.json()).error);
assert.strictEqual((await 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 = (await rows()).length;
const res = await post({ ...valid, website: 'http://spam.example' });
assert.strictEqual(res.status, 200);
assert.strictEqual((await rows()).length, before);
});
test('missing page file fails at startup, not on a request', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-nopage-'));
fs.copyFileSync(path.join(__dirname, 'server.js'), path.join(tmp, 'server.js'));
fs.symlinkSync(path.join(__dirname, 'node_modules'), path.join(tmp, 'node_modules'));
const { createServer: create } = require(path.join(tmp, 'server.js'));
await assert.rejects(() => create(dbUrl), /ENOENT/);
fs.rmSync(tmp, { recursive: true, force: true });
});
test('unreachable database fails at startup', async () => {
await assert.rejects(() => createServer('postgres://nobody:nothing@127.0.0.1:1/none'));
});
test('exits promptly on SIGTERM', async () => {
const child = spawn(process.execPath, [path.join(__dirname, 'server.js')], {
env: { ...process.env, PORT: '0', DATABASE_URL: dbUrl },
});
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);
});
test('docs/schema.sql matches the table the server creates', async () => {
const docSchema = `${schema}_doc`;
const cols = async (s) => (await admin.query(
`SELECT column_name, data_type, is_nullable, column_default, is_identity
FROM information_schema.columns WHERE table_schema = $1 AND table_name = 'leads' ORDER BY ordinal_position`, [s])).rows;
const doc = new Pool({ connectionString: withSchema(docSchema) });
try {
await admin.query(`CREATE SCHEMA ${docSchema}`);
await doc.query(fs.readFileSync(path.join(__dirname, 'docs', 'schema.sql'), 'utf8'));
assert.deepStrictEqual(await cols(docSchema), await cols(schema));
} finally {
await doc.end();
await admin.query(`DROP SCHEMA IF EXISTS ${docSchema} CASCADE`);
}
});