mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
test(server): seed the share, quota, photo and stats specs through the factories
Converts the raw prepare() fixtures and reads in the share and place shadow
e2e suites, the google quota, travel stats and MCP guard services, the
memories MCP spec, the admin seeder spec and the assignment participants
repository spec to the ORM factories and readers.
The place shadow e2e moves from hand-rolled tables to the migrated snapshot
with its users pinned to the ids their session cookies are signed for. The
share e2e drops the raw canAccessTrip it still put on the database mock:
nothing has read it since trip access moved onto the repositories. The
quota spec computes yesterday and the retention window in UTC, the same
calendar day SQLite's date('now') gives. The participants oracle keeps its
raw statement behind an allow marker.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* /api/place-shadow e2e — the real JwtAuthGuard, the real AdminGuard and the
|
||||
* real Zod pipe against a temp SQLite db.
|
||||
* real Zod pipe against a migrated temp SQLite db.
|
||||
*
|
||||
* The three things worth booting a server for: that a non-admin cannot read
|
||||
* other people's searches, that a switched-off log answers 200 instead of an
|
||||
@@ -14,33 +14,24 @@ import type { Server } from 'http';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { APP_PIPE } from '@nestjs/core';
|
||||
import { ZodValidationPipe } from 'nestjs-zod';
|
||||
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(`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 app_settings (key TEXT PRIMARY KEY, value TEXT);');
|
||||
tmp.exec(`CREATE TABLE place_shadow_picks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
query TEXT NOT NULL, lang TEXT, bias_lat REAL, bias_lng REAL, source TEXT NOT NULL,
|
||||
live_rank INTEGER NOT NULL, live_count INTEGER NOT NULL,
|
||||
picked_name TEXT NOT NULL, picked_lat REAL NOT NULL, picked_lng REAL NOT NULL,
|
||||
picked_place_id 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, canAccessTrip: vi.fn(), isOwner: vi.fn(), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
||||
}));
|
||||
|
||||
import { db } from '../../src/db/database';
|
||||
import { PlaceShadowPicks } from '../../src/db/entities/PlaceShadowPicks.entity';
|
||||
import { PlaceShadowModule } from '../../src/nest/place-shadow/place-shadow.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 { makeAdmin, makeUser } from '../helpers/factories/users';
|
||||
import { countRows, deleteRows } from '../helpers/factories/rows';
|
||||
import { setAppSetting } from '../helpers/factories/settings';
|
||||
|
||||
let orm: TestOrm;
|
||||
|
||||
const PICK = {
|
||||
query: 'kaffee bar am dobi',
|
||||
@@ -56,21 +47,18 @@ const PICK = {
|
||||
const USER = 1;
|
||||
const ADMIN = 2;
|
||||
|
||||
function enable(on: boolean) {
|
||||
db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)')
|
||||
.run('place_shadow_enabled', on ? 'true' : 'false');
|
||||
async function enable(on: boolean): Promise<void> {
|
||||
await setAppSetting(orm, 'place_shadow_enabled', on ? 'true' : 'false');
|
||||
}
|
||||
|
||||
describe('/api/place-shadow e2e (real guards + temp SQLite)', () => {
|
||||
describe('/api/place-shadow e2e (real guards + migrated temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
// JwtAuthGuard (Plan 3b Task 1) injects EntityManager — needs
|
||||
// JwtAuthGuard (Plan 3b Task 1) injects EntityManager, so it needs
|
||||
// MikroOrmModule.forRoot in the graph, same as every other e2e harness
|
||||
// guarding a route with it; this suite's minimal hand-rolled `users`
|
||||
// table already carries the five columns
|
||||
// `findByIdWithPasswordVersion` selects.
|
||||
// guarding a route with it.
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), PlaceShadowModule],
|
||||
providers: [{ provide: APP_PIPE, useClass: ZodValidationPipe }],
|
||||
@@ -83,19 +71,22 @@ describe('/api/place-shadow e2e (real guards + temp SQLite)', () => {
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: USER });
|
||||
seedUser(db as never, { id: ADMIN, email: 'admin@example.com', role: 'admin' });
|
||||
orm = await createTestOrm(db);
|
||||
// Pinned ids: sessionCookie(USER) and (ADMIN) sign for exactly these users.
|
||||
await makeUser(orm, { id: USER, email: 'e2e@example.test' });
|
||||
await makeAdmin(orm, { id: ADMIN, email: 'admin@example.com' });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
db.prepare('DELETE FROM place_shadow_picks').run();
|
||||
enable(true);
|
||||
beforeEach(async () => {
|
||||
await deleteRows(orm, PlaceShadowPicks);
|
||||
await enable(true);
|
||||
});
|
||||
|
||||
describe('POST pick', () => {
|
||||
@@ -107,15 +98,15 @@ describe('/api/place-shadow e2e (real guards + temp SQLite)', () => {
|
||||
const res = await request(server).post('/api/place-shadow/pick').set('Cookie', sessionCookie(USER)).send(PICK);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ recorded: true });
|
||||
expect(db.prepare('SELECT COUNT(*) AS n FROM place_shadow_picks').get()).toEqual({ n: 1 });
|
||||
expect(await countRows(orm, PlaceShadowPicks)).toBe(1);
|
||||
});
|
||||
|
||||
it('200 { recorded: false } while the log is off, not an error status', async () => {
|
||||
enable(false);
|
||||
await enable(false);
|
||||
const res = await request(server).post('/api/place-shadow/pick').set('Cookie', sessionCookie(USER)).send(PICK);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ recorded: false });
|
||||
expect(db.prepare('SELECT COUNT(*) AS n FROM place_shadow_picks').get()).toEqual({ n: 0 });
|
||||
expect(await countRows(orm, PlaceShadowPicks)).toBe(0);
|
||||
});
|
||||
|
||||
it('400 from the pipe on a malformed body, and nothing is written', async () => {
|
||||
@@ -129,7 +120,7 @@ describe('/api/place-shadow e2e (real guards + temp SQLite)', () => {
|
||||
const res = await request(server).post('/api/place-shadow/pick').set('Cookie', sessionCookie(USER)).send(bad);
|
||||
expect(res.status, JSON.stringify(bad).slice(0, 60)).toBe(400);
|
||||
}
|
||||
expect(db.prepare('SELECT COUNT(*) AS n FROM place_shadow_picks').get()).toEqual({ n: 0 });
|
||||
expect(await countRows(orm, PlaceShadowPicks)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -169,7 +160,7 @@ describe('/api/place-shadow e2e (real guards + temp SQLite)', () => {
|
||||
const wiped = await request(server).delete('/api/place-shadow').set('Cookie', sessionCookie(ADMIN));
|
||||
expect(wiped.status).toBe(200);
|
||||
expect(wiped.body).toEqual({ removed: 1 });
|
||||
expect(db.prepare('SELECT COUNT(*) AS n FROM place_shadow_picks').get()).toEqual({ n: 0 });
|
||||
expect(await countRows(orm, PlaceShadowPicks)).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* public /api/shared/:token endpoints through the real JwtAuthGuard against a
|
||||
* temp SQLite db. ShareService runs its real SQL via DatabaseModule (the
|
||||
* DATABASE_CONNECTION factory picks up the mocked db singleton); trip access
|
||||
* resolves through a real-SQL canAccessTrip over the temp db. Only the
|
||||
* resolves through the real repositories over the temp db. Only the
|
||||
* permission check and the photo-cache path lookup stay mocked. Focuses on
|
||||
* auth, trip-access 404, permission 403, the create-201-vs-update-200 split
|
||||
* and the unguarded public read.
|
||||
@@ -20,14 +20,6 @@ vi.mock('../../src/db/database', async () => {
|
||||
const db = createSnapshotTestDb();
|
||||
return {
|
||||
db,
|
||||
// Real-SQL trip access over the temp db — ShareService.verifyTripAccess and
|
||||
// DatabaseModule both read the mocked singleton.
|
||||
canAccessTrip: (tripId: number | string, userId: number) =>
|
||||
db.prepare(`
|
||||
SELECT t.id, t.user_id FROM trips t
|
||||
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
|
||||
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
|
||||
`).get(userId, tripId, userId),
|
||||
isOwner: () => false,
|
||||
getPlaceWithTags: () => null,
|
||||
closeDb: () => {},
|
||||
@@ -53,7 +45,14 @@ import { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
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 } from '../helpers/factories/trips';
|
||||
import { findRow, insertRow } from '../helpers/factories/rows';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { ShareTokens } from '../../src/db/entities/ShareTokens.entity';
|
||||
|
||||
let orm: TestOrm;
|
||||
|
||||
describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
|
||||
let server: Server;
|
||||
@@ -75,31 +74,31 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
// seedUser() omits password_hash, which the real schema requires NOT NULL.
|
||||
db.prepare(
|
||||
"INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user')",
|
||||
).run();
|
||||
orm = await createTestOrm(db);
|
||||
// Pinned id: sessionCookie(1) signs for exactly this user.
|
||||
await makeUser(orm, { id: 1, username: 'e2e-user', email: 'e2e@example.test' });
|
||||
app = await build();
|
||||
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
db.exec('DELETE FROM share_tokens');
|
||||
db.exec('DELETE FROM places');
|
||||
db.exec('DELETE FROM trip_members');
|
||||
db.exec('DELETE FROM trips');
|
||||
tripId = Number(db.prepare('INSERT INTO trips (user_id, title) VALUES (1, ?)').run('Trip').lastInsertRowid);
|
||||
tripId = (await makeTrip(orm, 1, { title: 'Trip' })).id;
|
||||
checkPermission.mockReturnValue(true);
|
||||
serveKey.mockReset();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
function tokenRow() {
|
||||
return db.prepare('SELECT * FROM share_tokens WHERE trip_id = ?').get(tripId) as any;
|
||||
return findRow(orm, ShareTokens, { trip: tripId });
|
||||
}
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
@@ -109,7 +108,7 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
|
||||
it('201 on first create, 200 on a subsequent update', async () => {
|
||||
const created = await request(server).post(`/api/trips/${tripId}/share-link`).set('Cookie', sessionCookie(1)).send({ share_map: true });
|
||||
expect(created.status).toBe(201);
|
||||
expect(created.body).toEqual({ token: tokenRow().token });
|
||||
expect(created.body).toEqual({ token: (await tokenRow())?.token });
|
||||
|
||||
const updated = await request(server).post(`/api/trips/${tripId}/share-link`).set('Cookie', sessionCookie(1)).send({});
|
||||
expect(updated.status).toBe(200);
|
||||
@@ -121,7 +120,7 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
|
||||
const res = await request(server).post(`/api/trips/${tripId}/share-link`).set('Cookie', sessionCookie(1)).send({});
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'No permission' });
|
||||
expect(tokenRow()).toBeUndefined();
|
||||
expect(await tokenRow()).toBeNull();
|
||||
});
|
||||
|
||||
it('404 when the trip is not accessible', async () => {
|
||||
@@ -134,12 +133,12 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
|
||||
await request(server).post(`/api/trips/${tripId}/share-link`).set('Cookie', sessionCookie(1)).send({ share_budget: true });
|
||||
const info = await request(server).get(`/api/trips/${tripId}/share-link`).set('Cookie', sessionCookie(1));
|
||||
expect(info.status).toBe(200);
|
||||
expect(info.body).toEqual(expect.objectContaining({ token: tokenRow().token, share_budget: true, share_packing: false }));
|
||||
expect(info.body).toEqual(expect.objectContaining({ token: (await tokenRow())?.token, share_budget: true, share_packing: false }));
|
||||
|
||||
const removed = await request(server).delete(`/api/trips/${tripId}/share-link`).set('Cookie', sessionCookie(1));
|
||||
expect(removed.status).toBe(200);
|
||||
expect(removed.body).toEqual({ success: true });
|
||||
expect(tokenRow()).toBeUndefined();
|
||||
expect(await tokenRow()).toBeNull();
|
||||
|
||||
const after = await request(server).get(`/api/trips/${tripId}/share-link`).set('Cookie', sessionCookie(1));
|
||||
expect(after.body).toEqual({ token: null });
|
||||
@@ -186,8 +185,7 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
|
||||
|
||||
it('streams cached bytes with no cookie (unguarded) for a valid token + place', async () => {
|
||||
const created = await request(server).post(`/api/trips/${tripId}/share-link`).set('Cookie', sessionCookie(1)).send({});
|
||||
db.prepare('INSERT INTO places (trip_id, name, image_url) VALUES (?, ?, ?)')
|
||||
.run(tripId, 'Louvre', '/api/maps/place-photo/ChIJabc/bytes');
|
||||
await insertRow(orm, Places, { trip: tripId, name: 'Louvre', image_url: '/api/maps/place-photo/ChIJabc/bytes' });
|
||||
serveKey.mockReturnValueOnce(photoName);
|
||||
const res = await request(server).get(`/api/shared/${created.body.token}/place-photo/ChIJabc/bytes`);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
Reference in New Issue
Block a user