31 lines
1.7 KiB
JavaScript
31 lines
1.7 KiB
JavaScript
'use strict';
|
|
// Run inside the API container with: node < student-tests/storage.js
|
|
const assert = require('node:assert/strict');
|
|
const { pool, transaction } = require('./src/db');
|
|
const { migrate } = require('./src/migrate');
|
|
const { randomUUID } = require('node:crypto');
|
|
async function counts() {
|
|
const result = {};
|
|
for (const table of ['users', 'chats', 'chat_members', 'messages', 'sessions'])
|
|
result[table] = (await pool.query(`SELECT count(*) AS n FROM ${table}`)).rows[0].n;
|
|
return result;
|
|
}
|
|
async function main() {
|
|
const before = await counts();
|
|
await migrate(); await migrate();
|
|
assert.deepEqual(await counts(), before);
|
|
assert.equal((await pool.query('SELECT count(*)::int AS n FROM schema_migrations')).rows[0].n, 1);
|
|
const id = randomUUID();
|
|
await assert.rejects(transaction(async client => {
|
|
await client.query('INSERT INTO chats(id,title) VALUES($1,$2)', [id, 'Rollback test']);
|
|
await client.query('INSERT INTO chat_members VALUES($1,$2)', [id, randomUUID()]);
|
|
}), e => e.code === '23503');
|
|
assert.equal((await pool.query('SELECT id FROM chats WHERE id=$1', [id])).rowCount, 0);
|
|
const constraints = (await pool.query(`SELECT contype,count(*)::int AS n FROM pg_constraint
|
|
WHERE connamespace='public'::regnamespace GROUP BY contype`)).rows;
|
|
assert.ok(constraints.some(c => c.contype === 'f' && c.n >= 4));
|
|
console.log('PASS: two repeated migrations preserve all row counts; FK failure rolls back chat insert; foreign keys present.');
|
|
console.log(JSON.stringify({ counts: before, constraints }));
|
|
}
|
|
main().catch(error => { console.error('FAIL: storage checks (' + (error.code || error.name) + ')'); process.exitCode = 1; }).finally(() => pool.end());
|