test(server): seed the small specs through the repositories

The suites with one to three raw statements left now seed and read their
rows through the ORM factories instead of hand-written SQLite on the
better-sqlite3 handle. A legacy statement that serves as a parity oracle,
the schema introspection and the bare backup file keep their raw SQL and
say why with a test-sql-allow marker. Two database mocks still answered a
getPlaceWithTags the module no longer exports; that dead branch goes too,
and the budget seam suite stubs the reservations repository directly
instead of a fake prepare().
This commit is contained in:
Maurice
2026-10-08 15:25:15 +02:00
parent feda6ffdbc
commit b2f2aef016
29 changed files with 489 additions and 403 deletions
@@ -81,6 +81,7 @@
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import type { INestApplication } from '@nestjs/common';
import { MikroORM } from '@mikro-orm/core';
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
@@ -103,6 +104,7 @@ import { db as testDb } from '../../src/db/database';
import { buildApp } from '../../src/bootstrap';
import { createDay, createDayAssignment, createPlace, createTrip, createUser } from '../helpers/factories';
import { generateToken } from '../helpers/auth';
import { setAddonEnabled } from '../helpers/factories/settings';
describe('R1 async-closure truthiness guards (RB2/RS21/RS23) — driven through the real routes', () => {
let app: INestApplication;
@@ -111,7 +113,7 @@ describe('R1 async-closure truthiness guards (RB2/RS21/RS23) — driven through
beforeAll(async () => {
app = await buildApp();
httpApp = app.getHttpAdapter().getInstance() as Application;
testDb.prepare("UPDATE addons SET enabled = 1 WHERE id = 'roadtrip'").run();
await setAddonEnabled(app.get(MikroORM), 'roadtrip', true);
});
afterAll(async () => {
@@ -53,9 +53,15 @@ import { resetTestDb } from '../helpers/test-db';
import { createUser, createTrip, createPlace } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import { PlaceRegionsRepository } from '../../src/db/repositories/PlaceRegions.repository';
import { PlaceRegions } from '../../src/db/entities/PlaceRegions.entity';
import { findRow, findRows } from '../helpers/factories/rows';
import type { FactoryOrm } from '../helpers/factories/context';
import { MikroORM } from '@mikro-orm/core';
let nestApp: INestApplication;
let app: Application;
/** The app's own ORM, for reading back what the background geocode wrote. */
const orm = (): FactoryOrm => nestApp.get(MikroORM);
const errors: unknown[] = [];
beforeAll(async () => {
const orig = PlaceRegionsRepository.prototype.upsertRegionWhileUnmoved;
@@ -83,10 +89,10 @@ describe('AT4/AT29 background geocode request context', () => {
const p = createPlace(testDb, trip.id, { lat: 48.85, lng: 2.35 });
const res = await request(app).get('/api/addons/atlas/stats').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(testDb.prepare('SELECT * FROM place_regions WHERE place_id=?').get(p.id)).toBeUndefined();
expect(await findRow(orm(), PlaceRegions, { place: p.id })).toBeNull();
await new Promise((r) => setTimeout(r, 2500));
expect(errors).toEqual([]);
expect(testDb.prepare('SELECT * FROM place_regions WHERE place_id=?').get(p.id)).toMatchObject({ country_code: 'FR', region_code: 'FR-IDF' });
expect(await findRow(orm(), PlaceRegions, { place: p.id })).toMatchObject({ country_code: 'FR', region_code: 'FR-IDF' });
}, 15_000);
it('IIFE-CTX-AT29 — /regions IIFE writes two places sequentially (2nd after ~2.4s)', async () => {
@@ -99,7 +105,10 @@ describe('AT4/AT29 background geocode request context', () => {
expect(res.status).toBe(200);
await new Promise((r) => setTimeout(r, 3500));
expect(errors).toEqual([]);
const rows = testDb.prepare('SELECT place_id, region_code FROM place_regions ORDER BY place_id').all();
const rows = (await findRows(orm(), PlaceRegions, {}, { place: 'asc' })).map((r) => ({
place_id: r.place_id,
region_code: r.region_code,
}));
expect(rows).toEqual([
{ place_id: p1.id, region_code: 'FR-IDF' },
{ place_id: p2.id, region_code: 'FR-PAC' },
@@ -31,12 +31,14 @@
* callback it schedules (`() => config.getLink(linkId)`) is what needs the
* fork, and it only runs once the timer fires, inside `schedule()`'s own
* `withRequestContext` — exactly the wrap under test. The link id comes from
* a raw `testDb` read (no ORM, no context needed) rather than through
* `nudge()`/`getLinkByToken`, so nothing before the `schedule()` call ever
* touches the EntityManager.
* the fixture `beforeAll` seeds, whose factory calls each open and close a
* request context of their own, rather than through
* `nudge()`/`getLinkByToken`, so nothing in the test body before the
* `schedule()` call ever touches the EntityManager.
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import type { INestApplication } from '@nestjs/common';
import { MikroORM } from '@mikro-orm/core';
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
@@ -56,6 +58,11 @@ vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.
import { db as testDb } from '../../src/db/database';
import { buildApp } from '../../src/bootstrap';
import { createUser, createTrip } from '../helpers/factories';
import { insertRow, updateRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { DocumentConnections } from '../../src/db/entities/DocumentConnections.entity';
import { DocumentProviders } from '../../src/db/entities/DocumentProviders.entity';
import { TripDocumentLinks } from '../../src/db/entities/TripDocumentLinks.entity';
import { WEBHOOK_NUDGE_DEBOUNCE_SECONDS } from '../../src/nest/doc-sync/doc-sync.constants';
import { DocSyncWebhookController } from '../../src/nest/doc-sync/doc-sync-webhook.controller';
import { DocSyncConfigService } from '../../src/nest/doc-sync/doc-sync-config.service';
@@ -74,28 +81,35 @@ describe('DocSyncWebhookController#schedule() runs its detached timer body insid
// The addon gate and the provider both have to be genuinely on: schedule()'s
// own reload callback (`syncIsOn`) skips the run otherwise, before ever
// reaching the assertion below.
testDb.exec("UPDATE addons SET enabled = 1 WHERE id = 'documents'");
testDb.exec("UPDATE document_providers SET enabled = 1 WHERE id = 'paperless'");
const orm = app.get(MikroORM);
await setAddonEnabled(orm, 'documents', true);
await updateRows(orm, DocumentProviders, { id: 'paperless' }, { enabled: 1 });
const owner = createUser(testDb, { username: 'docsync-webhook-ctx', email: 'docsync-webhook-ctx@test.local' }).user;
const trip = createTrip(testDb, owner.id, { title: 'Japan' });
const connInfo = testDb
.prepare(
`INSERT INTO document_connections (trip_id, provider_id, owner_user_id, base_url, secrets, settings)
VALUES (?, 'paperless', ?, 'https://paperless.example.com', NULL, '{}')`,
)
.run(trip.id, owner.id);
const linkInfo = testDb
.prepare(
`INSERT INTO trip_document_links
(trip_id, connection_id, provider_id, remote_scope_key, remote_label, direction, delete_policy,
conflict_policy, sync_enabled, webhook_token, created_by)
VALUES (?, ?, 'paperless', 'tag:1', 'Japan', 'both', 'unlink', 'manual', 1, 'webhook-ctx-ratchet-token', ?)`,
)
.run(trip.id, connInfo.lastInsertRowid, owner.id);
// A plain better-sqlite3 read — no ORM, no request context — so nothing
// before the `schedule()` call below ever touches the EntityManager.
linkId = Number(linkInfo.lastInsertRowid);
const connectionId = await insertRow(orm, DocumentConnections, {
trip: trip.id,
provider: 'paperless',
ownerUser: owner.id,
base_url: 'https://paperless.example.com',
secrets: null,
settings: '{}',
});
// Each factory call above closed its own request context before returning,
// so the test body below starts with no EntityManager fork around it.
linkId = await insertRow(orm, TripDocumentLinks, {
trip: trip.id,
connection: connectionId,
provider_id: 'paperless',
remote_scope_key: 'tag:1',
remote_label: 'Japan',
direction: 'both',
delete_policy: 'unlink',
conflict_policy: 'manual',
sync_enabled: 1,
webhook_token: 'webhook-ctx-ratchet-token',
createdByRef: owner.id,
});
});
afterAll(async () => {
@@ -67,7 +67,9 @@ import { db as testDb } from '../../src/db/database';
import { buildApp } from '../../src/bootstrap';
import { CalendarService } from '../../src/nest/calendar/calendar.service';
import { Trips } from '../../src/db/entities/Trips.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { createTrip, createUser } from '../helpers/factories';
import { updateRows } from '../helpers/factories/rows';
describe('Anonymous ICS feed routes run inside a request context', () => {
let app: INestApplication;
@@ -86,7 +88,7 @@ describe('Anonymous ICS feed routes run inside a request context', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Context-Proof Trip' });
const token = randomUUID();
testDb.prepare('UPDATE trips SET feed_token = ? WHERE id = ?').run(token, trip.id);
await updateRows(app.get(MikroORM), Trips, { id: trip.id }, { feed_token: token });
let repoRead: unknown;
let caught: unknown;
@@ -136,7 +138,7 @@ describe('Anonymous ICS feed routes run inside a request context', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Mutation-Proof Trip' });
const token = randomUUID();
testDb.prepare('UPDATE trips SET feed_token = ? WHERE id = ?').run(token, trip.id);
await updateRows(app.get(MikroORM), Trips, { id: trip.id }, { feed_token: token });
const calendar = app.get(CalendarService);
const spy = vi.spyOn(calendar, 'buildTripCalendar').mockImplementation(async () => {
@@ -184,7 +186,7 @@ describe('Anonymous ICS feed routes run inside a request context', () => {
const { user } = createUser(testDb);
createTrip(testDb, user.id, { title: 'User-Feed Context-Proof Trip' });
const token = randomUUID();
testDb.prepare('UPDATE users SET feed_token = ? WHERE id = ?').run(token, user.id);
await updateRows(app.get(MikroORM), Users, { id: user.id }, { feed_token: token });
let repoRead: unknown;
let caught: unknown;
@@ -58,6 +58,8 @@ import { PluginRuntimeService } from '../../src/nest/plugins/plugin-runtime.serv
import { PlaceShadowRetentionJob } from '../../src/nest/place-shadow/place-shadow.job';
import { StorageService } from '../../src/nest/storage/storage.service';
import { Users } from '../../src/db/entities/Users.entity';
import { PlaceShadowPicks } from '../../src/db/entities/PlaceShadowPicks.entity';
import { countRows, insertRow } from '../helpers/factories/rows';
import { createUser } from '../helpers/factories';
import { generateToken } from '../helpers/auth';
@@ -161,10 +163,18 @@ describe('ORM request-context seams populated in production', () => {
const isEnabledSpy = vi.spyOn(registrar, 'isEnabled').mockReturnValue(true);
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
testDb.prepare(`
INSERT INTO place_shadow_picks (created_at, query, source, live_rank, live_count, picked_name, picked_lat, picked_lng)
VALUES (datetime('now', '-999 days'), 'seam-003', 'nominatim', 1, 1, 'expired pick', 0, 0)
`).run();
// 999 days old, in the `datetime('now')` text form the column defaults to.
const expiredAt = new Date(Date.now() - 999 * 86_400_000).toISOString().slice(0, 19).replace('T', ' ');
await insertRow(orm, PlaceShadowPicks, {
created_at: expiredAt,
query: 'seam-003',
source: 'nominatim',
live_rank: 1,
live_count: 1,
picked_name: 'expired pick',
picked_lat: 0,
picked_lng: 0,
});
// Real bug found converting `purgeExpired` to a genuinely async
// repository call (0b security review F-B4): the `cron` package's
@@ -199,8 +209,7 @@ describe('ORM request-context seams populated in production', () => {
// `withRequestContext` wrap in `cron-registrar.service.ts`'s `register()`
// makes the repository call throw inside `PlaceShadowRetentionJob.tick`'s
// own try/catch, and the row survives (verified by hand, reverted).
const remaining = testDb.prepare("SELECT COUNT(*) as n FROM place_shadow_picks WHERE query = 'seam-003'").get() as { n: number };
expect(remaining.n).toBe(0);
expect(await countRows(orm, PlaceShadowPicks, { query: 'seam-003' })).toBe(0);
} finally {
registrar.unregister('place-shadow-retention');
isEnabledSpy.mockRestore();
+14 -2
View File
@@ -6,6 +6,7 @@ import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vites
import request from 'supertest';
import type { Application } from 'express';
import type { INestApplication } from '@nestjs/common';
import { MikroORM } from '@mikro-orm/core';
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
@@ -44,15 +45,26 @@ import { buildApp } from '../../src/bootstrap';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import { findRows } from '../helpers/factories/rows';
import type { FactoryOrm } from '../helpers/factories/context';
import { VacayHolidayCalendars } from '../../src/db/entities/VacayHolidayCalendars.entity';
let nestApp: INestApplication;
let app: Application;
let orm: FactoryOrm;
beforeAll(async () => {
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
orm = nestApp.get(MikroORM);
});
/** The id of the holiday calendar created last. */
async function latestCalendarId(): Promise<number | undefined> {
const [latest] = await findRows(orm, VacayHolidayCalendars, {}, { id: 'desc' });
return latest?.id;
}
beforeEach(async () => {
resetTestDb(testDb);
await resetRateLimits(nestApp);
@@ -299,7 +311,7 @@ describe('Vacay holiday calendar CRUD', () => {
.send({ region: 'US', label: 'US Holidays' });
expect(createRes.status).toBe(200);
const calId = createRes.body.plan?.holiday_calendars?.at(-1)?.id
?? (testDb.prepare('SELECT id FROM vacay_holiday_calendars ORDER BY id DESC LIMIT 1').get() as any)?.id;
?? (await latestCalendarId());
const res = await request(app)
.put(`/api/addons/vacay/plan/holiday-calendars/${calId}`)
@@ -317,7 +329,7 @@ describe('Vacay holiday calendar CRUD', () => {
.set('Cookie', authCookie(user.id))
.send({ region: 'FR', label: 'French Holidays' });
expect(createRes.status).toBe(200);
const calId = (testDb.prepare('SELECT id FROM vacay_holiday_calendars ORDER BY id DESC LIMIT 1').get() as any)?.id;
const calId = await latestCalendarId();
const res = await request(app)
.delete(`/api/addons/vacay/plan/holiday-calendars/${calId}`)