mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
test(server): seed and read test data through ORM factories
The server suite seeds and reads its database through some 5,500 raw better-sqlite3 statements on the sync handle. They restate the schema by hand, skip the repositories the app goes through and run on SQLite only, so nothing in the suite could ever exercise the dialect layer on another engine. tests/helpers/factories/ adds typed factories per domain (users, trips and days, places, assignments, bookings, budget, packing, to-dos, files, journeys, tours, collections, notifications, settings, plugins, tokens, atlas, vacay, photos, collab) and generic readers (findRow, findRows, countRows, updateRows, deleteRows) that go through MikroORM in a request context of their own, against the app's ORM or a createTestOrm handle. They refuse a write to a read-only foreign-key twin, which MikroORM would otherwise drop without a word. The README there is the conversion guide. The categories integration suite and the tags and calendar-feed e2e suites are converted in full as worked examples; the tags suite also moves from hand-rolled tables to the migrated snapshot. lint:test-sql (scripts/test-sql-ratchet.mjs) holds the raw statements left to a per-file baseline: growth and stale entries fail, files whose subject is raw SQL are exempt with a reason, and a single statement can be allowed with a test-sql-allow comment. CI runs it next to lint:boundaries.
This commit is contained in:
@@ -14,29 +14,24 @@ import type { Server } from 'http';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
vi.mock('../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb } = await import('../helpers/db-mock');
|
||||
const db = createSnapshotTestDb();
|
||||
return {
|
||||
db,
|
||||
canAccessTrip: (tripId: number | string, userId: number) =>
|
||||
db.prepare('SELECT id, user_id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
|
||||
isOwner: () => true,
|
||||
getPlaceWithTags: () => null,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
};
|
||||
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
|
||||
return buildDbMock(createSnapshotTestDb());
|
||||
});
|
||||
|
||||
import { db } from '../../src/db/database';
|
||||
import { FeedsModule } from '../../src/nest/feeds/feeds.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { createTestMikroOrmModule } from '../helpers/test-orm';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { makeTrip, readTripDays } from '../helpers/factories/trips';
|
||||
import { makeReservation } from '../helpers/factories/reservations';
|
||||
|
||||
describe('Calendar feed visibility e2e (real CalendarService over temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let feedToken: string;
|
||||
let orm: TestOrm;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), FeedsModule] }).compile();
|
||||
@@ -47,18 +42,34 @@ describe('Calendar feed visibility e2e (real CalendarService over temp SQLite)',
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
db.prepare(
|
||||
"INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user')",
|
||||
).run();
|
||||
// Seeded through MikroORM (tests/helpers/factories), not raw SQL.
|
||||
orm = await createTestOrm(db);
|
||||
const { user } = await makeUser(orm, { username: 'e2e-user', email: 'e2e@example.test' });
|
||||
feedToken = 'feed-token-visibility';
|
||||
db.prepare(
|
||||
"INSERT INTO trips (id, user_id, title, start_date, end_date, feed_token) VALUES (1, 1, 'Kyoto', '2026-09-01', '2026-09-05', ?)",
|
||||
).run(feedToken);
|
||||
db.prepare("INSERT INTO days (id, trip_id, day_number, date) VALUES (1, 1, 1, '2026-09-01')").run();
|
||||
db.prepare(`INSERT INTO reservations (trip_id, day_id, title, type, status, reservation_time, confirmation_number, ingest_state)
|
||||
VALUES (1, 1, 'Parked Flight', 'flight', 'confirmed', '2026-09-01T08:00', 'SECRET1', 'staged')`).run();
|
||||
db.prepare(`INSERT INTO reservations (trip_id, day_id, title, type, status, reservation_time, confirmation_number)
|
||||
VALUES (1, 1, 'Booked Flight', 'flight', 'confirmed', '2026-09-01T12:00', 'OPEN1')`).run();
|
||||
const trip = await makeTrip(orm, user.id, {
|
||||
title: 'Kyoto',
|
||||
start_date: '2026-09-01',
|
||||
end_date: '2026-09-05',
|
||||
feed_token: feedToken,
|
||||
});
|
||||
const [firstDay] = await readTripDays(orm, trip.id);
|
||||
await makeReservation(orm, trip.id, {
|
||||
day: firstDay.id,
|
||||
title: 'Parked Flight',
|
||||
type: 'flight',
|
||||
status: 'confirmed',
|
||||
reservation_time: '2026-09-01T08:00',
|
||||
confirmation_number: 'SECRET1',
|
||||
ingest_state: 'staged',
|
||||
});
|
||||
await makeReservation(orm, trip.id, {
|
||||
day: firstDay.id,
|
||||
title: 'Booked Flight',
|
||||
type: 'flight',
|
||||
status: 'confirmed',
|
||||
reservation_time: '2026-09-01T12:00',
|
||||
confirmation_number: 'OPEN1',
|
||||
});
|
||||
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
@@ -66,6 +77,7 @@ describe('Calendar feed visibility e2e (real CalendarService over temp SQLite)',
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
it('the public feed serves the live booking and neither the staged one nor its confirmation number', async () => {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* Tags module e2e — exercises the migrated /api/tags endpoints through the real
|
||||
* JwtAuthGuard against a temp SQLite db. TagsService runs its real SQL via
|
||||
* DatabaseModule (the DATABASE_CONNECTION factory picks up the mocked db
|
||||
* singleton); tags are user-scoped (no admin gate), so a normal authenticated
|
||||
* Tags module e2e: exercises the migrated /api/tags endpoints through the real
|
||||
* JwtAuthGuard against a real migrated temp SQLite db (createSnapshotTestDb(),
|
||||
* no hand-rolled CREATE TABLEs). Rows are seeded and read through the
|
||||
* factories in tests/helpers/factories, which go through MikroORM rather than
|
||||
* raw SQL; tags are user-scoped (no admin gate), so a normal authenticated
|
||||
* user can do everything.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
|
||||
@@ -10,41 +11,30 @@ import request from 'supertest';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { seedUser, sessionCookie } from './harness';
|
||||
import { sessionCookie } from './harness';
|
||||
|
||||
const { db } = vi.hoisted(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const Database = require('better-sqlite3');
|
||||
const tmp = new Database(':memory:');
|
||||
tmp.exec('PRAGMA journal_mode = WAL');
|
||||
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
||||
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
||||
tmp.exec(`CREATE TABLE tags (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT DEFAULT '#10b981',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);`);
|
||||
// StorageRegistryService (behind StorageModule, now in this module chain) reads
|
||||
// this at onModuleInit.
|
||||
tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');
|
||||
return { db: tmp };
|
||||
vi.mock('../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
|
||||
return buildDbMock(createSnapshotTestDb());
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
import { db } from '../../src/db/database';
|
||||
import { Tags } from '../../src/db/entities/Tags.entity';
|
||||
import { TagsModule } from '../../src/nest/tags/tags.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { createTestMikroOrmModule } from '../helpers/test-orm';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { makeTag } from '../helpers/factories/places';
|
||||
import { deleteRows, findRow } from '../helpers/factories/rows';
|
||||
|
||||
function insertTag(userId: number, name: string, color = '#10b981'): number {
|
||||
const res = db.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(userId, name, color);
|
||||
return Number(res.lastInsertRowid);
|
||||
let orm: TestOrm;
|
||||
|
||||
async function insertTag(userId: number, name: string, color = '#10b981'): Promise<number> {
|
||||
return (await makeTag(orm, userId, { name, color })).id;
|
||||
}
|
||||
|
||||
describe('Tags e2e (real auth guard + temp SQLite)', () => {
|
||||
describe('Tags e2e (real auth guard + migrated temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
@@ -58,18 +48,21 @@ describe('Tags e2e (real auth guard + temp SQLite)', () => {
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
seedUser(db as never, { id: 2, email: 'e2e-2@example.test' });
|
||||
orm = await createTestOrm(db);
|
||||
// Pinned ids: sessionCookie(1) and (2) sign for exactly these users.
|
||||
await makeUser(orm, { id: 1, email: 'e2e@example.test' });
|
||||
await makeUser(orm, { id: 2, email: 'e2e-2@example.test' });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
db.exec('DELETE FROM tags');
|
||||
beforeEach(async () => {
|
||||
await deleteRows(orm, Tags);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
@@ -78,9 +71,9 @@ describe('Tags e2e (real auth guard + temp SQLite)', () => {
|
||||
});
|
||||
|
||||
it('200 list scoped to the user, ordered by name', async () => {
|
||||
insertTag(1, 'Zebra');
|
||||
insertTag(1, 'Apple');
|
||||
insertTag(2, 'Other-User-Tag');
|
||||
await insertTag(1, 'Zebra');
|
||||
await insertTag(1, 'Apple');
|
||||
await insertTag(2, 'Other-User-Tag');
|
||||
const res = await request(server).get('/api/tags').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.tags.map((t: { name: string }) => t.name)).toEqual(['Apple', 'Zebra']);
|
||||
@@ -107,32 +100,32 @@ describe('Tags e2e (real auth guard + temp SQLite)', () => {
|
||||
});
|
||||
|
||||
it('200 on update of an owned tag, COALESCE preserving the color', async () => {
|
||||
const id = insertTag(1, 'Beach', '#ff0000');
|
||||
const id = await insertTag(1, 'Beach', '#ff0000');
|
||||
const res = await request(server).put(`/api/tags/${id}`).set('Cookie', sessionCookie(1)).send({ name: 'Hike' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.tag).toMatchObject({ id, name: 'Hike', color: '#ff0000' });
|
||||
});
|
||||
|
||||
it('404 on update of a tag the user does not own', async () => {
|
||||
const id = insertTag(2, 'Not-Yours');
|
||||
const id = await insertTag(2, 'Not-Yours');
|
||||
const res = await request(server).put(`/api/tags/${id}`).set('Cookie', sessionCookie(1)).send({ name: 'X' });
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Tag not found' });
|
||||
});
|
||||
|
||||
it('200 on delete of an owned tag, removing the row', async () => {
|
||||
const id = insertTag(1, 'ToDelete');
|
||||
const id = await insertTag(1, 'ToDelete');
|
||||
const res = await request(server).delete(`/api/tags/${id}`).set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true });
|
||||
expect(db.prepare('SELECT id FROM tags WHERE id = ?').get(id)).toBeUndefined();
|
||||
expect(await findRow(orm, Tags, { id })).toBeNull();
|
||||
});
|
||||
|
||||
it('404 on delete of a tag the user does not own', async () => {
|
||||
const id = insertTag(2, 'Not-Yours');
|
||||
const id = await insertTag(2, 'Not-Yours');
|
||||
const res = await request(server).delete(`/api/tags/${id}`).set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Tag not found' });
|
||||
expect(db.prepare('SELECT id FROM tags WHERE id = ?').get(id)).toBeDefined();
|
||||
expect(await findRow(orm, Tags, { id })).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user