Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

test(db): run the boot, boot sweep, demo seed, AirTrail and doc sync context suites on the real database module

Mauricebe1983c9a476
diff --git a/server/scripts/test-mocks-baseline.json b/server/scripts/test-mocks-baseline.json
index 389d7b6ce..efa4be5a2 100644
--- a/server/scripts/test-mocks-baseline.json
+++ b/server/scripts/test-mocks-baseline.json
@@ -53,21 +53,16 @@
"tests/e2e/vacay.e2e.test.ts": 1,
"tests/e2e/weather.e2e.test.ts": 1,
"tests/integration/admin.test.ts": 1,
- "tests/integration/airtrail-sync-request-context.test.ts": 1,
"tests/integration/assignments.test.ts": 1,
"tests/integration/async-closure-truthiness-guards.test.ts": 1,
"tests/integration/atlas-geocode-request-context.test.ts": 1,
"tests/integration/atlas.test.ts": 1,
"tests/integration/auth.test.ts": 1,
"tests/integration/backup.test.ts": 1,
- "tests/integration/boot-sweeps-request-context.test.ts": 1,
- "tests/integration/bootstrap.test.ts": 1,
"tests/integration/collab.test.ts": 1,
"tests/integration/collections.test.ts": 1,
"tests/integration/dayNotes.test.ts": 1,
"tests/integration/dayReorder.test.ts": 1,
- "tests/integration/demo-seed-request-context.test.ts": 1,
- "tests/integration/doc-sync-webhook-request-context.test.ts": 1,
"tests/integration/feeds-request-context.test.ts": 1,
"tests/integration/files.test.ts": 1,
"tests/integration/immich.test.ts": 1,
diff --git a/server/tests/integration/airtrail-sync-request-context.test.ts b/server/tests/integration/airtrail-sync-request-context.test.ts
index c116468b3..ced60658b 100644
--- a/server/tests/integration/airtrail-sync-request-context.test.ts
+++ b/server/tests/integration/airtrail-sync-request-context.test.ts
@@ -24,7 +24,6 @@
* SEAM-FEED-001 uses for the anonymous ICS routes.
*/
import { buildApp } from '../../src/bootstrap';
-import { db as testDb } from '../../src/db/database';
import { Reservations } from '../../src/db/entities/Reservations.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { AirtrailLinkService } from '../../src/nest/integrations/airtrail-link.service';
@@ -33,36 +32,33 @@ import { AirtrailClient, type AirtrailFlightRaw } from '../../src/nest/integrati
import { AirtrailService } from '../../src/nest/integrations/airtrail.service';
import { ReservationsService } from '../../src/nest/reservations/reservations.service';
import { CronRegistrarService } from '../../src/nest/scheduling/cron-registrar.service';
-import { createTrip, createUser } from '../helpers/factories';
import { deleteRows, insertRow } from '../helpers/factories/rows';
+import { makeTrip } from '../helpers/factories/trips';
+import { makeUser } from '../helpers/factories/users';
+import { resetDatabase } from '../helpers/reset-database';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import { SchedulerRegistry } from '@nestjs/schedule';
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
-vi.mock('../../src/db/database', async () => {
- const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
- return buildDbMock(createSnapshotTestDb());
-});
-
describe('airtrail-sync cron tick runs inside a request context', () => {
let app: INestApplication;
beforeAll(async () => {
app = await buildApp();
+ await resetDatabase(app.get(MikroORM));
});
afterAll(async () => {
await app.close();
- testDb.close();
});
it('AIRTRAIL-CTX-001: firing the real registered tick reaches ReservationsService.getReservation with a live request context, against the SAME MikroORM app.get(MikroORM) does', async () => {
const orm = app.get(MikroORM);
const registrar = app.get(CronRegistrarService);
- const { user } = createUser(testDb);
- const trip = createTrip(testDb, user.id);
+ const { user } = await makeUser(orm);
+ const trip = await makeTrip(orm, user.id);
const reservationId = await insertRow(orm, Reservations, {
trip: trip.id,
diff --git a/server/tests/integration/boot-sweeps-request-context.test.ts b/server/tests/integration/boot-sweeps-request-context.test.ts
index b9bc2cbf6..6d782c0bf 100644
--- a/server/tests/integration/boot-sweeps-request-context.test.ts
+++ b/server/tests/integration/boot-sweeps-request-context.test.ts
@@ -57,7 +57,6 @@
* exercising.
*/
import { buildApp } from '../../src/bootstrap';
-import { db as testDb } from '../../src/db/database';
import { AirportsService } from '../../src/nest/airports/airports.service';
import { PlaceRegionsRepairJob } from '../../src/nest/atlas/place-regions-repair.job';
import { DocSyncJob } from '../../src/nest/doc-sync/doc-sync.job';
@@ -72,11 +71,6 @@ import type { INestApplication } from '@nestjs/common';
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
-vi.mock('../../src/db/database', async () => {
- const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
- return buildDbMock(createSnapshotTestDb());
-});
-
describe('Every onApplicationBootstrap boot sweep runs inside a request context', () => {
let app: INestApplication;
@@ -86,7 +80,6 @@ describe('Every onApplicationBootstrap boot sweep runs inside a request context'
afterAll(async () => {
await app.close();
- testDb.close();
});
it('BOOT-SWEEP-001: the eight jobs\' plus AirportsService\'s REAL onApplicationBootstrap, driven through the real production-wired CronRegistrarService, each routes through runOnBoot (structurally asserted), and journey-thumbs and place-regions-repair — the sweeps that reach a repository today — never log cannotUseGlobalContext / "global EntityManager"', async () => {
diff --git a/server/tests/integration/bootstrap.test.ts b/server/tests/integration/bootstrap.test.ts
index ae5bbf6d7..03b9ab5d0 100644
--- a/server/tests/integration/bootstrap.test.ts
+++ b/server/tests/integration/bootstrap.test.ts
@@ -7,20 +7,16 @@
* server/src/bootstrap.ts + index.ts serve everything correctly without the legacy app.
*/
import { buildApp } from '../../src/bootstrap';
-import { db as testDb } from '../../src/db/database';
import { UnitOfWork } from '../../src/nest/database/unit-of-work';
import { authCookie } from '../helpers/auth';
-import { createUser } from '../helpers/factories';
-import { resetTestDb } from '../helpers/test-db';
+import { makeUser } from '../helpers/factories/users';
+import { resetDatabase } from '../helpers/reset-database';
+import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
-vi.mock('../../src/db/database', async () => {
- const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
- return buildDbMock(createSnapshotTestDb());
-});
// BOOT-007 boots with NODE_ENV=production, which opens the cron gate — keep the
// registrar inert so a bootstrap test never schedules real jobs or runs boot
// sweeps against the real uploads/data dirs. The gate itself is covered by
@@ -54,16 +50,17 @@ vi.mock('../../src/nest/scheduling/cron-registrar.service', () => ({
describe('BOOTSTRAP (F6) — unified NestJS app serves the whole surface', () => {
let app: INestApplication;
let instance: import('express').Application;
+ let orm: MikroORM;
beforeAll(async () => {
- resetTestDb(testDb);
app = await buildApp();
instance = app.getHttpAdapter().getInstance();
+ orm = app.get(MikroORM);
+ await resetDatabase(orm);
});
afterAll(async () => {
await app.close();
- testDb.close();
});
it('BOOT-001 — GET /api/health returns 200 { status: ok } (platform transport on Nest)', async () => {
@@ -99,7 +96,7 @@ describe('BOOTSTRAP (F6) — unified NestJS app serves the whole surface', () =>
const anon = await request(instance).get('/api/addons');
expect(anon.status).toBe(401);
- const { user } = createUser(testDb);
+ const { user } = await makeUser(orm);
const res = await request(instance).get('/api/addons').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(Array.isArray(res.body.addons)).toBe(true);
@@ -124,7 +121,7 @@ describe('BOOTSTRAP (F6) — unified NestJS app serves the whole surface', () =>
// The admin-0 country GeoJSON is multi-MB; without compression it stalls
// behind reverse proxies / Cloudflare Tunnel. Proves applyGlobalMiddleware
// gzips it on the wire.
- const { user } = createUser(testDb);
+ const { user } = await makeUser(orm);
const res = await request(instance)
.get('/api/addons/atlas/countries/geo')
.set('Accept-Encoding', 'gzip')
diff --git a/server/tests/integration/demo-seed-request-context.test.ts b/server/tests/integration/demo-seed-request-context.test.ts
index a5b6053a9..c4c14f816 100644
--- a/server/tests/integration/demo-seed-request-context.test.ts
+++ b/server/tests/integration/demo-seed-request-context.test.ts
@@ -16,16 +16,12 @@
* conversion never meets a second C1 (task-6-review-parity.md's boot-sweep
* finding).
*
- * Does NOT use `buildDbMock` the way most integration suites do — its
- * `runDemoSeed` is a deliberate no-op stub (tests/helpers/db-mock.ts) so
- * that suite's app boots don't carry demo-seed side effects, which would
- * silence the very thing this file exists to exercise. `NODE_ENV=test`
- * already gives `db/database.ts`'s own singleton an isolated, per-worker
- * `:memory:` copy of the migrated schema snapshot (`readSchemaSnapshot()`),
- * so nothing needs stubbing for the boot itself — the `vi.mock` below (Task
- * 0b review M2) exists only to wrap `runDemoSeed` with a context-recording
- * spy, not to replace its behaviour: `importOriginal` re-exports everything
- * else from the real module unchanged.
+ * Does NOT use `buildDbMock`: its `runDemoSeed` is a deliberate no-op stub
+ * (tests/helpers/db-mock.ts) so that other suites' app boots don't carry
+ * demo-seed side effects, which would silence the very thing this file
+ * exists to exercise. The suite boots on the real database module, on either
+ * engine; the only thing it adds is a spy on `runDemoSeed` (Task 0b review
+ * M2) that records the context and calls straight through to the real one.
*
* `seedDemoData`'s own `require('../demo/demo-seed')` (a deliberate dynamic
* require — see that file's docstring) cannot resolve under vitest's SWC
@@ -42,6 +38,7 @@
* failure is what actually gets logged instead, unchanged by the wrap.
*/
import { buildApp } from '../../src/bootstrap';
+import * as database from '../../src/db/database';
import { RequestContext } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
@@ -50,36 +47,22 @@ import { describe, it, expect, afterEach, vi } from 'vitest';
/**
* Task 0b review M2: the pre-fix version of this file only asserted "no
* `cannotUseGlobalContext`/`global EntityManager` line reached the log",
- * which cannot distinguish a wrapped call from an unwrapped one — `runDemoSeed`
- * is raw `better-sqlite3` and never touches the ORM, so it produces neither
- * line either way (verified: deleting the `withRequestContext` wrap in
- * `db/orm.ts:59` left this ratchet green, 1/1). Fixed by asserting the
- * context POSITIVELY: a thin spy around the real `runDemoSeed`, preserving
- * everything else `../../src/db/database` exports (`importOriginal`),
- * records whether `RequestContext.currentRequestContext()` is defined at the
- * instant `runDemoSeed` is entered — this is exactly the ratchet MikroORM's
- * own `allowGlobalContext: false` gate reads at query time, so it is the
- * real signal, not a log-line proxy for it. Deleting the `withRequestContext`
- * wrap now fails this test directly (verified).
+ * which cannot distinguish a wrapped call from an unwrapped one: `runDemoSeed`
+ * produces neither line either way (verified: deleting the `withRequestContext`
+ * wrap in `db/orm.ts` left this ratchet green, 1/1). Fixed by asserting the
+ * context POSITIVELY: a spy on the module's `runDemoSeed` export, which
+ * `db/orm.ts` calls through its import binding, records whether
+ * `RequestContext.currentRequestContext()` is defined at the instant
+ * `runDemoSeed` is entered and then runs the real function. This is exactly
+ * what MikroORM's own `allowGlobalContext: false` gate reads at query time,
+ * so it is the real signal, not a log-line proxy for it. Deleting the
+ * `withRequestContext` wrap fails this test directly (verified on SQLite).
*/
-// `vi.hoisted`, not a plain top-level `const`: `vi.mock`'s factory is
-// invoked when something up the import chain first resolves
-// `../../src/db/database` (during `buildApp`'s own module graph, not at
-// this file's textual position), and vitest hoists the `vi.mock` call
-// itself above every import — a plain `const` here would still be in its
-// temporal dead zone when the factory closes over it. Same hazard the
-// legacy `trip-membership.service.test.ts` guarded against with its own
-// `vi.hoisted(() => ({ testDb, dbMock }))`.
-const { contextSeenOnEntry } = vi.hoisted(() => ({ contextSeenOnEntry: [] as boolean[] }));
-vi.mock('../../src/db/database', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../src/db/database')>();
- return {
- ...actual,
- runDemoSeed: async (): Promise<void> => {
- contextSeenOnEntry.push(RequestContext.currentRequestContext() !== undefined);
- return await actual.runDemoSeed();
- },
- };
+const contextSeenOnEntry: boolean[] = [];
+const actualRunDemoSeed = database.runDemoSeed;
+vi.spyOn(database, 'runDemoSeed').mockImplementation(async () => {
+ contextSeenOnEntry.push(RequestContext.currentRequestContext() !== undefined);
+ return await actualRunDemoSeed();
});
describe('runDemoSeed runs inside a request context (Plan 3c Task 0b)', () => {
diff --git a/server/tests/integration/doc-sync-webhook-request-context.test.ts b/server/tests/integration/doc-sync-webhook-request-context.test.ts
index 4f8a3b16b..fa911aa4a 100644
--- a/server/tests/integration/doc-sync-webhook-request-context.test.ts
+++ b/server/tests/integration/doc-sync-webhook-request-context.test.ts
@@ -37,26 +37,22 @@
* `schedule()` call ever touches the EntityManager.
*/
import { buildApp } from '../../src/bootstrap';
-import { db as testDb } from '../../src/db/database';
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 { DocSyncConfigService } from '../../src/nest/doc-sync/doc-sync-config.service';
import { DocSyncWebhookController } from '../../src/nest/doc-sync/doc-sync-webhook.controller';
import { WEBHOOK_NUDGE_DEBOUNCE_SECONDS } from '../../src/nest/doc-sync/doc-sync.constants';
-import { createUser, createTrip } from '../helpers/factories';
import { insertRow, updateRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
+import { makeTrip } from '../helpers/factories/trips';
+import { makeUser } from '../helpers/factories/users';
+import { resetDatabase } from '../helpers/reset-database';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
-vi.mock('../../src/db/database', async () => {
- const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
- return buildDbMock(createSnapshotTestDb());
-});
-
describe('DocSyncWebhookController#schedule() runs its detached timer body inside its own request context', () => {
let app: INestApplication;
let controller: DocSyncWebhookController;
@@ -72,11 +68,13 @@ describe('DocSyncWebhookController#schedule() runs its detached timer body insid
// own reload callback (`syncIsOn`) skips the run otherwise, before ever
// reaching the assertion below.
const orm = app.get(MikroORM);
+ await resetDatabase(orm);
await setAddonEnabled(orm, 'documents', true);
await updateRows(orm, DocumentProviders, { id: 'paperless' }, { enabled: 1 });
- const owner = createUser(testDb, { username: 'docsync-webhook-ctx', email: '[email protected]' }).user;
- const trip = createTrip(testDb, owner.id, { title: 'Japan' });
+ const owner = (await makeUser(orm, { username: 'docsync-webhook-ctx', email: '[email protected]' }))
+ .user;
+ const trip = await makeTrip(orm, owner.id, { title: 'Japan' });
const connectionId = await insertRow(orm, DocumentConnections, {
trip: trip.id,
provider: 'paperless',
@@ -104,7 +102,6 @@ describe('DocSyncWebhookController#schedule() runs its detached timer body insid
afterAll(async () => {
await app.close();
- testDb.close();
});
it('WEBHOOK-CTX-001: schedule(), called from a genuinely bare (non-request) context, never logs cannotUseGlobalContext once its debounce timer fires', async () => {
diff --git a/server/tests/postgres/snapshot-suites-baseline.json b/server/tests/postgres/snapshot-suites-baseline.json
index 799f74cc8..1a5a3e398 100644
--- a/server/tests/postgres/snapshot-suites-baseline.json
+++ b/server/tests/postgres/snapshot-suites-baseline.json
@@ -1,19 +1,14 @@
[
"tests/integration/admin.test.ts",
- "tests/integration/airtrail-sync-request-context.test.ts",
"tests/integration/assignments.test.ts",
"tests/integration/async-closure-truthiness-guards.test.ts",
"tests/integration/atlas-geocode-request-context.test.ts",
"tests/integration/atlas.test.ts",
"tests/integration/auth.test.ts",
"tests/integration/backup.test.ts",
- "tests/integration/boot-sweeps-request-context.test.ts",
- "tests/integration/bootstrap.test.ts",
"tests/integration/collab.test.ts",
"tests/integration/collections.test.ts",
"tests/integration/dayNotes.test.ts",
- "tests/integration/demo-seed-request-context.test.ts",
- "tests/integration/doc-sync-webhook-request-context.test.ts",
"tests/integration/feeds-request-context.test.ts",
"tests/integration/files.test.ts",
"tests/integration/immich.test.ts",