From bf8b06d71b50b6cd6f53b0c8679bb9b32f5abc15 Mon Sep 17 00:00:00 2001 From: jubnl Date: Thu, 24 Sep 2026 07:32:46 +0200 Subject: [PATCH] =?UTF-8?q?test(server):=20plan=204=20=E2=80=94=20collapse?= =?UTF-8?q?=20remaining=20test=20harnesses;=20triage=20legacy=20migration?= =?UTF-8?q?=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/tests/e2e/atlas.e2e.test.ts | 32 +- server/tests/e2e/auth.e2e.test.ts | 32 +- server/tests/e2e/budget.e2e.test.ts | 37 +- .../e2e/calendar-feed-visibility.e2e.test.ts | 33 +- server/tests/e2e/collections.e2e.test.ts | 34 +- server/tests/e2e/dawarich.e2e.test.ts | 42 +-- server/tests/e2e/doc-sync.e2e.test.ts | 42 +-- server/tests/e2e/reservations.e2e.test.ts | 35 +- server/tests/e2e/school-holidays.e2e.test.ts | 14 +- server/tests/e2e/share.e2e.test.ts | 39 +- server/tests/helpers/migration-step.ts | 66 ++++ .../plugins/boot-registry-order.test.ts | 45 +-- .../storage-restore-reload.test.ts | 16 +- .../unit/db/atlas-region-crosswalk.test.ts | 161 +++++---- .../tests/unit/db/booked-night-reseat.test.ts | 28 +- .../db/budget-ticket-json-migration.test.ts | 165 +++++---- .../unit/db/instance-api-key-backfill.test.ts | 213 ++++++----- .../db/migration-version-atomicity.test.ts | 55 --- ...reservation-ingest-state-migration.test.ts | 75 ++-- .../db/roadtrip-preferences-migration.test.ts | 69 ++-- server/tests/unit/db/seeds-admin.test.ts | 38 +- server/tests/unit/db/trip-access.test.ts | 4 +- .../db/trip-days-backfill-migration.test.ts | 226 ++++++------ .../db/trip-files-prefix-migration.test.ts | 55 ++- server/tests/unit/demo/demo-seed.test.ts | 4 +- .../unit/plugins/operator-egress.test.ts | 22 +- .../plugins/plugin-instance-settings.test.ts | 29 +- .../unit/plugins/plugin-oauth.service.test.ts | 11 +- .../unit/plugins/plugin-user-settings.test.ts | 7 +- .../unit/plugins/plugins-service.test.ts | 27 +- .../unit/plugins/settings-isolation.test.ts | 21 +- .../unit/services/conflictUpdate.test.ts | 22 +- server/tests/unit/services/migration.test.ts | 332 +++++++----------- .../unit/services/trekPhotoMedia.test.ts | 19 +- .../unit/services/trimUserWhitespace.test.ts | 237 ++++++++----- 35 files changed, 1086 insertions(+), 1201 deletions(-) create mode 100644 server/tests/helpers/migration-step.ts delete mode 100644 server/tests/unit/db/migration-version-atomicity.test.ts diff --git a/server/tests/e2e/atlas.e2e.test.ts b/server/tests/e2e/atlas.e2e.test.ts index 2ad7ffad8..9ecf0d5fb 100644 --- a/server/tests/e2e/atlas.e2e.test.ts +++ b/server/tests/e2e/atlas.e2e.test.ts @@ -14,28 +14,22 @@ import type { Server } from 'http'; import { Test } from '@nestjs/testing'; 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('PRAGMA foreign_keys = ON'); - return { db: tmp }; +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { + db, + closeDb: () => {}, + reinitialize: () => {}, + getPlaceWithTags: () => null, + canAccessTrip: () => undefined, + isOwner: () => false, + }; }); -vi.mock('../../src/db/database', () => ({ - db, - closeDb: () => {}, - reinitialize: () => {}, - getPlaceWithTags: () => null, - canAccessTrip: () => undefined, - isOwner: () => false, -})); - vi.mock('../../src/websocket', () => ({ broadcastToUser: vi.fn(), broadcast: vi.fn() })); -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { createUser, createTrip } from '../helpers/factories'; import { AtlasModule } from '../../src/nest/atlas/atlas.module'; import { DatabaseModule } from '../../src/nest/database/database.module'; @@ -62,8 +56,6 @@ describe('Atlas e2e (real auth guard + real service + temp SQLite)', () => { } beforeAll(async () => { - createTables(db as never); - runMigrations(db as never); userId = createUser(db as never, { username: 'atlas-e2e', email: 'atlas-e2e@test.example' }).user.id; app = await build(); server = app.getHttpServer(); diff --git a/server/tests/e2e/auth.e2e.test.ts b/server/tests/e2e/auth.e2e.test.ts index 73f7b046a..84a96e685 100644 --- a/server/tests/e2e/auth.e2e.test.ts +++ b/server/tests/e2e/auth.e2e.test.ts @@ -14,24 +14,19 @@ import type { Server } from 'http'; import { Test } from '@nestjs/testing'; 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('PRAGMA foreign_keys = ON'); - return { db: tmp }; +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { + db, + closeDb: () => {}, + reinitialize: () => {}, + getPlaceWithTags: () => null, + canAccessTrip: () => undefined, + isOwner: () => false, + }; }); -vi.mock('../../src/db/database', () => ({ - db, - closeDb: () => {}, - reinitialize: () => {}, - getPlaceWithTags: () => null, - canAccessTrip: () => undefined, - isOwner: () => false, -})); - vi.mock('../../src/websocket', () => ({ broadcastToUser: vi.fn(), broadcast: vi.fn() })); // The audit domain is DI-native: writeAudit runs for real against the temp // db's audit_log table; only the file logger is silenced. @@ -45,8 +40,7 @@ vi.mock('../../src/app-config', async (importOriginal) => { }); import { MailerService } from '../../src/nest/notifications/mailer/mailer.service'; -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { createUser } from '../helpers/factories'; import { encrypt_api_key } from '../../src/nest/common/crypto/apiKeyCrypto'; import { resetRateLimits } from '../helpers/test-db'; @@ -90,8 +84,6 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp (db.prepare('SELECT COUNT(*) AS n FROM audit_log WHERE action = ?').get(action) as { n: number }).n; beforeAll(async () => { - createTables(db as never); - runMigrations(db as never); const seeded = createUser(db as never, { username: 'auth-e2e', email: 'u@example.test' }); userId = seeded.user.id; userEmail = seeded.user.email; diff --git a/server/tests/e2e/budget.e2e.test.ts b/server/tests/e2e/budget.e2e.test.ts index 3a3b569cc..fcbec33c9 100644 --- a/server/tests/e2e/budget.e2e.test.ts +++ b/server/tests/e2e/budget.e2e.test.ts @@ -1,7 +1,7 @@ /** * Budget module e2e — exercises the migrated /api/trips/:tripId/budget endpoints - * through the real JwtAuthGuard against a temp SQLite db carrying the full real - * schema (createTables + runMigrations), so the folded BudgetService runs its + * through the real JwtAuthGuard against a temp SQLite db carrying the full real, + * migrated schema (createSnapshotTestDb), so the folded BudgetService runs its * real SQL. Only the db singleton (trip access) and the WebSocket broadcast are * mocked; the permission check is a spy on the container's PermissionsService. */ @@ -14,24 +14,20 @@ import { RealtimeModule } from '../../src/nest/realtime/realtime.module'; import { Test } from '@nestjs/testing'; 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('PRAGMA foreign_keys = ON'); - return { db: tmp }; -}); const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() })); -vi.mock('../../src/db/database', () => ({ - db, - closeDb: () => {}, - reinitialize: () => {}, - canAccessTrip, - getPlaceWithTags: () => null, - isOwner: () => false, -})); +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { + db, + closeDb: () => {}, + reinitialize: () => {}, + canAccessTrip, + getPlaceWithTags: () => null, + isOwner: () => false, + }; +}); vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() })); import { PermissionsService } from '../../src/nest/permissions/permissions.service'; @@ -40,8 +36,7 @@ import { PermissionsService } from '../../src/nest/permissions/permissions.servi // PermissionsService singleton (created in beforeAll, after build()). let checkPermission: MockInstance; -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { BudgetModule } from '../../src/nest/budget/budget.module'; import { ExchangeRatesService } from '../../src/nest/budget/exchange-rates.service'; import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; @@ -70,8 +65,6 @@ describe('Budget e2e (real auth guard + temp SQLite, real budget SQL)', () => { } beforeAll(async () => { - createTables(db); - runMigrations(db); // The temp db carries the real schema (password_hash NOT NULL), so seed the // auth users directly instead of via the trimmed-DDL seedUser helper. db.prepare( diff --git a/server/tests/e2e/calendar-feed-visibility.e2e.test.ts b/server/tests/e2e/calendar-feed-visibility.e2e.test.ts index de9ab5bfc..ffaf84920 100644 --- a/server/tests/e2e/calendar-feed-visibility.e2e.test.ts +++ b/server/tests/e2e/calendar-feed-visibility.e2e.test.ts @@ -13,26 +13,21 @@ import request from 'supertest'; import type { Server } from 'http'; import { Test } from '@nestjs/testing'; -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'); - return { db: tmp }; +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: () => {}, + }; }); -vi.mock('../../src/db/database', () => ({ - 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: () => {}, -})); - -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { DatabaseModule } from '../../src/nest/database/database.module'; import { FeedsModule } from '../../src/nest/feeds/feeds.module'; import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; @@ -53,8 +48,6 @@ describe('Calendar feed visibility e2e (real CalendarService over temp SQLite)', } beforeAll(async () => { - createTables(db); - runMigrations(db); db.prepare( "INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user')", ).run(); diff --git a/server/tests/e2e/collections.e2e.test.ts b/server/tests/e2e/collections.e2e.test.ts index a32fa3c4f..0e2250c66 100644 --- a/server/tests/e2e/collections.e2e.test.ts +++ b/server/tests/e2e/collections.e2e.test.ts @@ -14,30 +14,24 @@ import type { Server } from 'http'; import { Test } from '@nestjs/testing'; 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('PRAGMA foreign_keys = ON'); - return { db: tmp }; +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { + db, + closeDb: () => {}, + reinitialize: () => {}, + getPlaceWithTags: () => null, + 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, + }; }); -vi.mock('../../src/db/database', () => ({ - db, - closeDb: () => {}, - reinitialize: () => {}, - getPlaceWithTags: () => null, - 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, -})); - const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) })); vi.mock('../../src/websocket', () => ({ broadcastToUser: vi.fn(), broadcast: vi.fn() })); -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { createUser, createTrip, createCategory, createDay, createPlace, createDayAssignment } from '../helpers/factories'; import { CollectionsModule } from '../../src/nest/collections/collections.module'; import { DatabaseModule } from '../../src/nest/database/database.module'; @@ -71,8 +65,6 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () => } beforeAll(async () => { - createTables(db as never); - runMigrations(db as never); ownerId = createUser(db as never, { username: 'owner', email: 'owner@test.example' }).user.id; otherId = createUser(db as never, { username: 'other', email: 'other@test.example' }).user.id; createCategory(db as never); diff --git a/server/tests/e2e/dawarich.e2e.test.ts b/server/tests/e2e/dawarich.e2e.test.ts index 83e73403d..448b6b0d9 100644 --- a/server/tests/e2e/dawarich.e2e.test.ts +++ b/server/tests/e2e/dawarich.e2e.test.ts @@ -24,34 +24,28 @@ import type { Server } from 'http'; import { Test } from '@nestjs/testing'; 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('PRAGMA foreign_keys = ON'); - return { db: tmp }; +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { + db, + closeDb: () => {}, + reinitialize: () => {}, + getPlaceWithTags: () => null, + 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, + }; }); -vi.mock('../../src/db/database', () => ({ - db, - closeDb: () => {}, - reinitialize: () => {}, - getPlaceWithTags: () => null, - 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, -})); - const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) })); vi.mock('../../src/websocket', () => ({ broadcastToUser: vi.fn(), broadcast: vi.fn() })); -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { createUser } from '../helpers/factories'; import { DawarichModule } from '../../src/nest/integrations/dawarich.module'; import { DawarichClient } from '../../src/nest/integrations/dawarich.client'; @@ -118,8 +112,6 @@ describe('Dawarich e2e (real addon gate + real auth guard + real services + temp } beforeAll(async () => { - createTables(db as never); - runMigrations(db as never); ownerId = createUser(db as never, { username: 'dawarich-owner', email: 'dawarich-owner@test.example' }).user.id; strangerId = createUser(db as never, { username: 'dawarich-stranger', email: 'dawarich-stranger@test.example' }).user.id; strangerSuggestionId = seedSuggestion(strangerId, 'visit-stranger-1', 'Eiffel Tower'); diff --git a/server/tests/e2e/doc-sync.e2e.test.ts b/server/tests/e2e/doc-sync.e2e.test.ts index 1c50ab259..47f80fc40 100644 --- a/server/tests/e2e/doc-sync.e2e.test.ts +++ b/server/tests/e2e/doc-sync.e2e.test.ts @@ -24,29 +24,24 @@ import type { Server } from 'http'; import { Test } from '@nestjs/testing'; 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('PRAGMA foreign_keys = ON'); - return { db: tmp }; +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { + db, + closeDb: () => {}, + reinitialize: () => {}, + getPlaceWithTags: () => null, + 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, + }; }); -vi.mock('../../src/db/database', () => ({ - db, - closeDb: () => {}, - reinitialize: () => {}, - getPlaceWithTags: () => null, - 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, -})); - const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) })); vi.mock('../../src/websocket', () => ({ broadcastToUser: vi.fn(), broadcast: vi.fn() })); @@ -68,8 +63,7 @@ vi.mock('../../src/utils/ssrfGuard', async (importOriginal) => { }; }); -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { createTrip, createUser } from '../helpers/factories'; import { DocSyncModule } from '../../src/nest/doc-sync/doc-sync.module'; import { DocSyncMcp } from '../../src/nest/doc-sync/doc-sync.mcp'; @@ -158,8 +152,6 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () => } beforeAll(async () => { - createTables(db as never); - runMigrations(db as never); ownerId = createUser(db as never, { username: 'owner', email: 'owner@test.local' }).user.id; memberId = createUser(db as never, { username: 'member', email: 'member@test.local' }).user.id; strangerId = createUser(db as never, { username: 'stranger', email: 'stranger@test.local' }).user.id; diff --git a/server/tests/e2e/reservations.e2e.test.ts b/server/tests/e2e/reservations.e2e.test.ts index 0c00541aa..d24da824e 100644 --- a/server/tests/e2e/reservations.e2e.test.ts +++ b/server/tests/e2e/reservations.e2e.test.ts @@ -2,7 +2,7 @@ * Reservations + accommodations module e2e — exercises both migrated mounts * through the real JwtAuthGuard against a temp SQLite db. Reservation SQL runs * for real (ReservationsService is DI-native, no mock — the temp db carries the - * full schema via createTables + runMigrations), and so does the accommodation + * full, real migrated schema via createSnapshotTestDb), and so does the accommodation * SQL (the injected DaysService is DI-native too); the budget service, the * permission check and the WebSocket broadcast stay mocked. */ @@ -22,29 +22,21 @@ import type { Server } from 'http'; import request from 'supertest'; import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest'; -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'); - // What production runs (db/database.ts) and what createTestDb gives every - // unit suite. Without it the reservation foreign keys are inert here, and an - // id that resolves to nothing passes the mount unnoticed. - tmp.exec('PRAGMA foreign_keys = ON'); - return { db: tmp }; -}); - // Task 9 fix wave (B-L11): `src/db/database.ts` no longer exports // `canAccessTrip` (Plan 3c Task 0b moved it onto `TripsRepository` behind // `TripAccessGuard`'s own `EntityManager`), so mocking it here was a dead // no-op — the "404 when trip not accessible" cases below already delete/ // restore the real row instead (see their own comments). -vi.mock('../../src/db/database', () => ({ - db, - getPlaceWithTags: vi.fn(), - closeDb: () => {}, - reinitialize: () => {}, -})); +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { + db, + getPlaceWithTags: vi.fn(), + closeDb: () => {}, + reinitialize: () => {}, + }; +}); vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() })); const { notificationSend } = vi.hoisted(() => ({ notificationSend: vi.fn().mockResolvedValue(undefined) })); import { PermissionsService } from '../../src/nest/permissions/permissions.service'; @@ -56,8 +48,7 @@ let checkPermission: MockInstance; // The budget-sync seam runs the real injected BudgetService (BudgetModule is // imported by ReservationsModule since the budget fold) over the same temp db. -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { NotificationsService } from '../../src/nest/notifications/notifications.service'; import { TestUnitOfWorkModule } from '../helpers/test-uow'; import { createTestMikroOrmModule } from '../helpers/test-orm'; @@ -81,8 +72,6 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real } beforeAll(async () => { - createTables(db); - runMigrations(db); // The temp db carries the real schema (password_hash NOT NULL), so seed the // auth user directly instead of via the trimmed-DDL seedUser helper. db.prepare( diff --git a/server/tests/e2e/school-holidays.e2e.test.ts b/server/tests/e2e/school-holidays.e2e.test.ts index 44c9afb20..784628b7d 100644 --- a/server/tests/e2e/school-holidays.e2e.test.ts +++ b/server/tests/e2e/school-holidays.e2e.test.ts @@ -8,13 +8,12 @@ import { RealtimeModule } from '../../src/nest/realtime/realtime.module'; import { withRequestContext } from '../../src/nest/database/request-context'; import { sessionCookie } from './harness'; -const { db } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - return { db: new Database(':memory:') }; +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { db, closeDb: () => {} }; }); -vi.mock('../../src/db/database', () => ({ db, closeDb: () => {} })); -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { DatabaseModule } from '../../src/nest/database/database.module'; import { SchoolHolidaysModule } from '../../src/nest/school-holidays/school-holidays.module'; import { SchoolHolidaysService } from '../../src/nest/school-holidays/school-holidays.service'; @@ -33,9 +32,6 @@ let app: INestApplication; let service: SchoolHolidaysService; let orm: MikroORM; beforeAll(async () => { - db.pragma('foreign_keys = ON'); - createTables(db); - runMigrations(db); db.prepare("INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'admin', 'admin@test.local', '', 'admin'), (2, 'member', 'member@test.local', '', 'user')").run(); const module = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DatabaseModule, RealtimeModule, SchoolHolidaysModule] }).compile(); app = module.createNestApplication(); diff --git a/server/tests/e2e/share.e2e.test.ts b/server/tests/e2e/share.e2e.test.ts index 576444543..1f8d94e2d 100644 --- a/server/tests/e2e/share.e2e.test.ts +++ b/server/tests/e2e/share.e2e.test.ts @@ -15,29 +15,25 @@ import type { Server } from 'http'; import { Test } from '@nestjs/testing'; 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'); - return { db: tmp }; -}); - -vi.mock('../../src/db/database', () => ({ - 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(` +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../helpers/db-mock'); + 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: () => {}, - reinitialize: () => {}, -})); + isOwner: () => false, + getPlaceWithTags: () => null, + closeDb: () => {}, + reinitialize: () => {}, + }; +}); import { PermissionsService } from '../../src/nest/permissions/permissions.service'; @@ -51,8 +47,7 @@ const serveKey = vi.fn(); import path from 'node:path'; import fs from 'node:fs'; -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { db } from '../../src/db/database'; import { ShareModule } from '../../src/nest/share/share.module'; import { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-cache.service'; import { DatabaseModule } from '../../src/nest/database/database.module'; @@ -81,8 +76,6 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => { } beforeAll(async () => { - createTables(db); - runMigrations(db); // 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')", diff --git a/server/tests/helpers/migration-step.ts b/server/tests/helpers/migration-step.ts new file mode 100644 index 000000000..b2ab309af --- /dev/null +++ b/server/tests/helpers/migration-step.ts @@ -0,0 +1,66 @@ +/** + * A bare MikroORM instance (no entities) wired only for driving the numbered + * migration chain in `src/db/migrations/` against a throwaway `:memory:` db — + * for tests that need to observe ONE specific migration's effect in isolation: + * migrate to the step immediately before it, seed rows with raw SQL, apply + * just that one step, assert. + * + * Same shape as `tests/unit/db/restore-migrates-forward.test.ts`'s own + * `ormFor()`, minus the seeder extension (these tests never seed) and pointed + * at `:memory:` instead of a temp file — nothing here needs a second process + * to open the same file, so raw SQL runs over the ORM's own connection + * (`rawExec`/`rawQuery` below) instead of a probe `Database` handle. + */ +import type { Migration } from '@mikro-orm/migrations'; +import { Migrator } from '@mikro-orm/migrations'; +import { MikroORM } from '@mikro-orm/sqlite'; +import type { AbstractSqlDriver } from '@mikro-orm/sql'; +import type { Configuration } from '@mikro-orm/core'; +import path from 'node:path'; + +const MIGRATIONS = path.join(__dirname, '../../src/db/migrations'); + +export async function createMigrationOrm(): Promise { + return MikroORM.init({ + entities: [], + discovery: { warnWhenNoEntities: false }, + extensions: [Migrator], + migrations: { path: MIGRATIONS, pathTs: MIGRATIONS, snapshot: false, silent: true }, + dbName: ':memory:', + }); +} + +export function migratorOf(orm: MikroORM): Migrator { + return orm.config.getExtension('@mikro-orm/migrator') as Migrator; +} + +/** Migrate up to and including the named migration (its `Migration<...>` class name). */ +export async function migrateTo(orm: MikroORM, name: string): Promise { + await migratorOf(orm).up({ to: name }); +} + +/** The full pending list on a fresh db, in application order — index by class name. */ +export async function pendingNames(orm: MikroORM): Promise { + return (await migratorOf(orm).getPending()).map((m) => m.name); +} + +/** Raw SQL over the ORM's own connection (no entities are registered). */ +export async function rawExec(orm: MikroORM, sql: string, params: unknown[] = []): Promise { + await orm.em.getConnection().execute(sql, params); +} + +export async function rawQuery(orm: MikroORM, sql: string, params: unknown[] = []): Promise { + return (await orm.em.getConnection().execute(sql, params)) as T[]; +} + +/** + * Constructs and runs ONE migration class directly against the ORM's driver, + * bypassing the Migrator's `mikro_orm_migrations` bookkeeping entirely — for a + * test that needs to invoke a migration's `up()` a second time (idempotency / + * replay-safety guards) without the Migrator's own "already applied, skip" + * short-circuit getting in the way. + */ +export async function runMigrationDirect(orm: MikroORM, MigrationClass: new (driver: AbstractSqlDriver, config: Configuration) => Migration): Promise { + const migration = new MigrationClass(orm.em.getDriver(), orm.config); + await migration.up(); +} diff --git a/server/tests/integration/plugins/boot-registry-order.test.ts b/server/tests/integration/plugins/boot-registry-order.test.ts index b22ef8685..5fd9e79f0 100644 --- a/server/tests/integration/plugins/boot-registry-order.test.ts +++ b/server/tests/integration/plugins/boot-registry-order.test.ts @@ -23,33 +23,14 @@ import path from 'node:path'; import { Test } from '@nestjs/testing'; import type { TestingModule } from '@nestjs/testing'; -const { testDb } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - const db = new Database(':memory:'); - db.exec(`CREATE TABLE plugins ( - id TEXT PRIMARY KEY, status TEXT, enabled INTEGER DEFAULT 0, version TEXT, api_version INTEGER DEFAULT 1, permissions TEXT DEFAULT '[]', operator_egress INTEGER DEFAULT 0, granted_permissions TEXT DEFAULT '', - config TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', capabilities TEXT DEFAULT '{}', last_error TEXT, updated_at TEXT, - trek_range TEXT DEFAULT '>=3.0.0', - source_repo TEXT, author_pubkey TEXT, update_block_code TEXT, update_block_detail TEXT, update_block_version TEXT); - CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT); - CREATE TABLE plugin_settings_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER, default_value TEXT); - CREATE TABLE settings (user_id INTEGER, key TEXT, value TEXT); - CREATE TABLE plugin_entity_metadata (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, entity_type TEXT, entity_id INTEGER, key TEXT, value TEXT, updated_at TEXT); - CREATE TABLE plugin_user_config (plugin_id TEXT, user_id INTEGER, field_key TEXT, value TEXT, PRIMARY KEY (plugin_id, user_id, field_key)); - CREATE TABLE plugin_meta_migrations (plugin_id TEXT, migration_id TEXT, PRIMARY KEY (plugin_id, migration_id)); - CREATE TABLE plugin_capability_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, acting_user_id INTEGER, method TEXT, resource TEXT, code TEXT, ts TEXT, prev_hash TEXT, hash TEXT); - CREATE TABLE plugin_scheduled_tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT NOT NULL, name TEXT NOT NULL, due_at INTEGER NOT NULL, payload TEXT NOT NULL DEFAULT 'null', every_ms INTEGER, created_at TEXT DEFAULT (datetime('now')), UNIQUE(plugin_id, name)); - CREATE TABLE plugin_user_erasure_queue (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT NOT NULL, user_id INTEGER NOT NULL, created_at TEXT DEFAULT (datetime('now')), UNIQUE(plugin_id, user_id)); - CREATE TABLE addons (id TEXT PRIMARY KEY, enabled INTEGER DEFAULT 0); - CREATE TABLE audit_log ( - id INTEGER PRIMARY KEY AUTOINCREMENT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - user_id INTEGER, action TEXT NOT NULL, resource TEXT, details TEXT, ip TEXT);`); - return { testDb: db }; +vi.mock('../../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { db, canAccessTrip: () => undefined }; }); -vi.mock('../../../src/db/database', () => ({ db: testDb, canAccessTrip: () => undefined })); vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() })); -import { db as dbConn } from '../../../src/db/database'; +import { db as testDb } from '../../../src/db/database'; import { DatabaseService } from '../../../src/nest/database/database.service'; import { AuditService } from '../../../src/nest/audit/audit.service'; import { createTestAddonsService } from '../../helpers/test-addons'; @@ -107,7 +88,7 @@ beforeAll(() => { // db:own. Seeded 'inactive' (not the 'active' a real shutdown leaves) so the // poll below only terminates on a status the THIS-boot supervisor wrote. testDb - .prepare("INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config) VALUES ('migrator','inactive',1,'[\"db:own\"]','[\"db:own\"]','{}')") + .prepare("INSERT INTO plugins (id, name, status, enabled, permissions, granted_permissions, config, trek_range) VALUES ('migrator','migrator','inactive',1,'[\"db:own\"]','[\"db:own\"]','{}','>=3.0.0')") .run(); }); @@ -123,18 +104,18 @@ afterAll(async () => { describe('plugin boot vs registry scan ordering', () => { it('BOOT-REG-001 a plugin enabled before a restart activates cleanly even though the registry scan runs in a LATER provider\'s onModuleInit', async () => { - const dbs = new DatabaseService(dbConn); + const dbs = new DatabaseService(testDb); // Empty at construction — exactly what PluginRpcRegistryService is before its // own onModuleInit scan has run. const registry = new PluginRpcRegistry(); - t = await createTestOrm(dbConn); + t = await createTestOrm(testDb); // Plan 3j Task 3: `PluginRpcHostFactory`'s `audit` callback now takes // `PluginCapabilityAuditRepository`, not `DatabaseService`. const hostFactory = new PluginRpcHostFactory(t.repo(PluginCapabilityAudit), registry as unknown as PluginRpcRegistryService); const userSettings = new PluginUserSettingsService((t as TestOrm).repo(PluginSettingsFields), (t as TestOrm).repo(PluginUserConfig)); const auditLogRepo = t.repo(AuditLog); const usersRepo = t.repo(Users); - const addonsService = await createTestAddonsService(dbConn, dbs); + const addonsService = await createTestAddonsService(testDb, dbs); mod = await Test.createTestingModule({ providers: [ @@ -217,10 +198,10 @@ describe('plugin boot vs registry scan ordering', () => { const dir = path.join(codeRoot, 'addongated', 'server'); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, 'index.js'), `module.exports = { async onLoad(ctx) {} };`); - testDb.prepare("INSERT INTO addons (id, enabled) VALUES ('needsaddon_addon', 1)").run(); + testDb.prepare("INSERT INTO addons (id, name, enabled) VALUES ('needsaddon_addon', 'needsaddon_addon', 1)").run(); testDb .prepare( - "INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, dependencies) VALUES ('addongated','inactive',1,'[]','[]','{}', ?)", + "INSERT INTO plugins (id, name, status, enabled, permissions, granted_permissions, config, trek_range, dependencies) VALUES ('addongated','addongated','inactive',1,'[]','[]','{}','>=3.0.0', ?)", ) .run(JSON.stringify({ requiredAddons: ['needsaddon_addon'] })); @@ -233,11 +214,11 @@ describe('plugin boot vs registry scan ordering', () => { // exactly the bug this test exists to catch): this is what makes the // addon check below genuinely depend on the withRequestContext wrap // rather than passing either way. - const t2 = await createTestOrm(dbConn, { allowGlobalContext: false }); + const t2 = await createTestOrm(testDb, { allowGlobalContext: false }); const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); let mod2: TestingModule | undefined; try { - const dbs2 = new DatabaseService(dbConn); + const dbs2 = new DatabaseService(testDb); const userSettings2 = new PluginUserSettingsService(t2.repo(PluginSettingsFields), t2.repo(PluginUserConfig)); const registry2 = new PluginRpcRegistry(); // Registry already scanned — this test is about the addon check, not the diff --git a/server/tests/integration/storage-restore-reload.test.ts b/server/tests/integration/storage-restore-reload.test.ts index 193d88d8a..3255f3c75 100644 --- a/server/tests/integration/storage-restore-reload.test.ts +++ b/server/tests/integration/storage-restore-reload.test.ts @@ -21,29 +21,19 @@ * accepted precedent from storage-registry.service.test.ts, harmless (mkdir * -p on an existing dir), and orthogonal to what this test actually exercises. */ -import { describe, it, expect, beforeAll, afterEach } from 'vitest'; +import { describe, it, expect, afterEach } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -// eslint-disable-next-line @typescript-eslint/no-require-imports -const Database = require('better-sqlite3'); -import { createTables } from '../../src/db/schema'; -import { runMigrations } from '../../src/db/migrations'; +import { createSnapshotTestDb } from '../helpers/db-mock'; import type { RuntimeEnvService } from '../../src/nest/app-config/runtime-env.service'; import { StorageEventsService } from '../../src/nest/storage/storage-events.service'; import { BACKENDS_KEY, CATEGORIES_KEY, StorageRegistryService } from '../../src/nest/storage/storage-registry.service'; import { StorageService } from '../../src/nest/storage/storage.service'; import { createTestUnitOfWork, createTestAppSettingsRepo, sharedTestOrm } from '../helpers/test-uow'; -const testDb = new Database(':memory:'); -testDb.exec('PRAGMA journal_mode = WAL'); -testDb.exec('PRAGMA foreign_keys = ON'); - -beforeAll(() => { - createTables(testDb); - runMigrations(testDb); -}); +const testDb = createSnapshotTestDb(); const tmpDirs: string[] = []; function makeTmpDir(): string { diff --git a/server/tests/unit/db/atlas-region-crosswalk.test.ts b/server/tests/unit/db/atlas-region-crosswalk.test.ts index c53a7fa5f..46b452963 100644 --- a/server/tests/unit/db/atlas-region-crosswalk.test.ts +++ b/server/tests/unit/db/atlas-region-crosswalk.test.ts @@ -2,122 +2,129 @@ * Unit test for the Atlas region-code reconciliation migration (#1119). * * After Atlas swapped Natural Earth for geoBoundaries, manually-marked regions - * (`visited_regions`) held the old Natural Earth ISO-3166-2 codes. The final migration - * reconciles each row against the shipped admin-1 bundle: valid codes are kept, codes - * whose region NAME still matches are re-coded, renamed-merge cases use a curated - * crosswalk, and anything else is left untouched. We exercise the real migration by - * running all migrations, seeding rows, rewinding schema_version by one, and re-running - * so only the last (reconciliation) migration fires. + * (`visited_regions`) held the old Natural Earth ISO-3166-2 codes. The + * migration reconciles each row against the shipped admin-1 bundle: valid + * codes are kept, codes whose region NAME still matches are re-coded, + * renamed-merge cases use a curated crosswalk, and anything else is left + * untouched. Ported off the legacy runner (Task 0 triage: PORT — the numbered + * MikroORM migration below has its own class but no dedicated test) onto the + * real `Migration20200101021500_atlas_dropped_natural_earth_for_geoboundaries`: + * migrate to the step immediately before it, seed rows with raw SQL, apply + * just that one migration, assert. */ -import { describe, it, expect } from 'vitest'; -import Database from 'better-sqlite3'; -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; -import { createUser } from '../../helpers/factories'; +import { describe, it, expect, afterEach } from 'vitest'; +import type { MikroORM } from '@mikro-orm/sqlite'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; -function freshDb() { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA foreign_keys = ON'); - createTables(db); - runMigrations(db); - return db; +const TARGET = 'Migration20200101021500_atlas_dropped_natural_earth_for_geoboundaries'; + +let seq = 0; +let orm: MikroORM; + +/** A fresh ORM migrated to the step immediately before the reconciliation. */ +async function ormBeforeTarget(): Promise { + const o = await createMigrationOrm(); + const names = await pendingNames(o); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); // sanity: the migration must exist in the chain + await migrateTo(o, names[idx - 1]); + return o; } -function mark(db: Database.Database, userId: number, code: string, name: string, country = 'NO') { - db.prepare( - 'INSERT INTO visited_regions (user_id, region_code, region_name, country_code) VALUES (?, ?, ?, ?)' - ).run(userId, code, name, country); +async function createUser(): Promise { + const username = `u${++seq}`; + await rawExec(orm, 'INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)', [ + username, `${username}@example.test`, 'x', 'user', + ]); + const rows = await rawQuery<{ id: number }>(orm, 'SELECT last_insert_rowid() as id'); + return rows[0].id; } -// The visited_regions reconciliation (#1119) is pinned at schema version 135. -// Migrations added afterwards are appended AFTER it (append-only), so it is no -// longer the last migration. Rewind to just before the reconciliation and -// re-run: the later migrations are idempotent, so only the reconciliation has -// any effect on the seeded rows here. -const RECONCILIATION_VERSION = 135; -function rerunLastMigration(db: Database.Database) { - db.prepare('UPDATE schema_version SET version = ?').run(RECONCILIATION_VERSION - 1); - runMigrations(db); +async function mark(userId: number, code: string, name: string, country = 'NO'): Promise { + await rawExec(orm, 'INSERT INTO visited_regions (user_id, region_code, region_name, country_code) VALUES (?, ?, ?, ?)', [ + userId, code, name, country, + ]); } +async function runReconciliation(): Promise { + await migrateTo(orm, TARGET); +} + +afterEach(async () => { + await orm?.close(true); +}); + describe('Atlas region-code reconciliation migration', () => { - it('CROSSWALK-001: remaps a renamed-merge county via the curated crosswalk', () => { - const db = freshDb(); - const { user } = createUser(db); - mark(db, user.id, 'NO-05', 'Oppland'); // merged into Innlandet, name changed + it('CROSSWALK-001: remaps a renamed-merge county via the curated crosswalk', async () => { + orm = await ormBeforeTarget(); + const userId = await createUser(); + await mark(userId, 'NO-05', 'Oppland'); // merged into Innlandet, name changed - rerunLastMigration(db); + await runReconciliation(); - const rows = db.prepare('SELECT region_code, region_name FROM visited_regions WHERE user_id = ?').all(user.id); + const rows = await rawQuery(orm, 'SELECT region_code, region_name FROM visited_regions WHERE user_id = ?', [userId]); expect(rows).toEqual([{ region_code: 'NO-34', region_name: 'Innlandet' }]); - db.close(); }); - it('CROSSWALK-002: merges two old counties that map to the same new region (no UNIQUE clash)', () => { - const db = freshDb(); - const { user } = createUser(db); - mark(db, user.id, 'NO-04', 'Hedmark'); // → Innlandet - mark(db, user.id, 'NO-05', 'Oppland'); // → Innlandet + it('CROSSWALK-002: merges two old counties that map to the same new region (no UNIQUE clash)', async () => { + orm = await ormBeforeTarget(); + const userId = await createUser(); + await mark(userId, 'NO-04', 'Hedmark'); // → Innlandet + await mark(userId, 'NO-05', 'Oppland'); // → Innlandet - rerunLastMigration(db); + await runReconciliation(); - const rows = db.prepare('SELECT region_code FROM visited_regions WHERE user_id = ?').all(user.id); + const rows = await rawQuery(orm, 'SELECT region_code FROM visited_regions WHERE user_id = ?', [userId]); expect(rows).toEqual([{ region_code: 'NO-34' }]); - db.close(); }); - it('CROSSWALK-003: leaves a still-valid code untouched', () => { - const db = freshDb(); - const { user } = createUser(db); - mark(db, user.id, 'NO-03', 'Oslo'); // present in the new bundle + it('CROSSWALK-003: leaves a still-valid code untouched', async () => { + orm = await ormBeforeTarget(); + const userId = await createUser(); + await mark(userId, 'NO-03', 'Oslo'); // present in the new bundle - rerunLastMigration(db); + await runReconciliation(); - const rows = db.prepare('SELECT region_code, region_name FROM visited_regions WHERE user_id = ?').all(user.id); + const rows = await rawQuery(orm, 'SELECT region_code, region_name FROM visited_regions WHERE user_id = ?', [userId]); expect(rows).toEqual([{ region_code: 'NO-03', region_name: 'Oslo' }]); - db.close(); }); - it('CROSSWALK-004: re-codes a stale code whose region NAME still matches the bundle', () => { + it('CROSSWALK-004: re-codes a stale code whose region NAME still matches the bundle', async () => { // Not in any crosswalk: a bogus code but a name ("Oslo") that the bundle still carries // for NO → reconciled to the bundle's code for that name (NO-03) by the name-match path. - const db = freshDb(); - const { user } = createUser(db); - mark(db, user.id, 'NO-99', 'Oslo'); + orm = await ormBeforeTarget(); + const userId = await createUser(); + await mark(userId, 'NO-99', 'Oslo'); - rerunLastMigration(db); + await runReconciliation(); - const rows = db.prepare('SELECT region_code, region_name FROM visited_regions WHERE user_id = ?').all(user.id); + const rows = await rawQuery(orm, 'SELECT region_code, region_name FROM visited_regions WHERE user_id = ?', [userId]); expect(rows).toEqual([{ region_code: 'NO-03', region_name: 'Oslo' }]); - db.close(); }); - it('CROSSWALK-005: leaves an unresolvable row as-is (no code, no name, no crosswalk match)', () => { - const db = freshDb(); - const { user } = createUser(db); - mark(db, user.id, 'ZZ-99', 'Nowhere', 'ZZ'); + it('CROSSWALK-005: leaves an unresolvable row as-is (no code, no name, no crosswalk match)', async () => { + orm = await ormBeforeTarget(); + const userId = await createUser(); + await mark(userId, 'ZZ-99', 'Nowhere', 'ZZ'); - rerunLastMigration(db); + await runReconciliation(); - const rows = db.prepare('SELECT region_code, region_name FROM visited_regions WHERE user_id = ?').all(user.id); + const rows = await rawQuery(orm, 'SELECT region_code, region_name FROM visited_regions WHERE user_id = ?', [userId]); expect(rows).toEqual([{ region_code: 'ZZ-99', region_name: 'Nowhere' }]); - db.close(); }); - it('CROSSWALK-006: does not touch bucket_list or visited_countries (no region identifier there)', () => { - const db = freshDb(); - const { user } = createUser(db); - db.prepare('INSERT INTO bucket_list (user_id, name, country_code) VALUES (?, ?, ?)').run(user.id, 'Oppland', 'NO'); - db.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'NO'); - mark(db, user.id, 'NO-05', 'Oppland'); // ensure the migration actually runs its body + it('CROSSWALK-006: does not touch bucket_list or visited_countries (no region identifier there)', async () => { + orm = await ormBeforeTarget(); + const userId = await createUser(); + await rawExec(orm, 'INSERT INTO bucket_list (user_id, name, country_code) VALUES (?, ?, ?)', [userId, 'Oppland', 'NO']); + await rawExec(orm, 'INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)', [userId, 'NO']); + await mark(userId, 'NO-05', 'Oppland'); // ensure the migration actually runs its body - rerunLastMigration(db); + await runReconciliation(); - const bucket = db.prepare('SELECT name, country_code FROM bucket_list WHERE user_id = ?').all(user.id); + const bucket = await rawQuery(orm, 'SELECT name, country_code FROM bucket_list WHERE user_id = ?', [userId]); expect(bucket).toEqual([{ name: 'Oppland', country_code: 'NO' }]); // free-text name untouched - const countries = db.prepare('SELECT country_code FROM visited_countries WHERE user_id = ?').all(user.id); + const countries = await rawQuery(orm, 'SELECT country_code FROM visited_countries WHERE user_id = ?', [userId]); expect(countries).toEqual([{ country_code: 'NO' }]); - db.close(); }); }); diff --git a/server/tests/unit/db/booked-night-reseat.test.ts b/server/tests/unit/db/booked-night-reseat.test.ts index 58797af18..3c67444e5 100644 --- a/server/tests/unit/db/booked-night-reseat.test.ts +++ b/server/tests/unit/db/booked-night-reseat.test.ts @@ -16,14 +16,11 @@ import { describe, it, expect } from 'vitest'; import Database from 'better-sqlite3'; import { createTables } from '../../../src/db/schema'; import { runMigrations } from '../../../src/db/migrations'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; import { reseatBookedNights } from '../../../src/db/reseat-booked-nights'; function freshDb() { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA foreign_keys = ON'); - createTables(db); - runMigrations(db); + const db = createSnapshotTestDb(); db.prepare("INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'u', 'u@test.local', 'x', 'user')").run(); db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run(); db.prepare("INSERT INTO days (id, trip_id, day_number, date) VALUES (1, 1, 1, '2026-10-02')").run(); @@ -202,9 +199,24 @@ describe('booked night reseat', () => { }); it('RESEAT-009: the migration runs the step on a database being upgraded', () => { - // Seeded through the tables the base schema has, so the step fires on its normal - // pass: the backfill for older bookings appends the night last first, then the - // reseat brings it to the front. + // Plan 4 Task 5c FINDING: unlike ruling 7's claim, `reseatBookedNights` is + // NOT invoked from inside any numbered MikroORM migration — only from the + // legacy `db/migrations.ts` array (its last step, #242). Grepped the whole + // `src/db/migrations/` tree for `reseat`/`reseatBookedNights` and every + // check-in/seat-ordering wording: no hit. The two numbered migrations that + // DO touch booked nights near the end of the chain + // (`Migration20200101034900_give_every_stay_booked_before_this_release`, + // `Migration20200101035000_the_same_sweep_once_more_for_the`) both call + // `attachStayStopsToCheckInDay` (creates the day stop), a DIFFERENT legacy + // step (#229/#230) from the reseat/reorder step (#242) this test exercises. + // So this one case is left on the legacy `createTables`+`runMigrations` + // builder deliberately, NOT swapped: there is no numbered-migration target + // to port it onto. Flagged for the controller/Task 6 — this is a real "no + // equivalent found" gap (ruling 10), not an oversight: an install upgrading + // through the numbered chain never gets this one-time reorder applied, and + // this file will still show up in Task 6's "zero test files import + // db/schema or db/migrations" precondition grep until that gap is resolved + // one way or another. const db = new Database(':memory:'); db.exec('PRAGMA journal_mode = WAL'); db.exec('PRAGMA foreign_keys = ON'); diff --git a/server/tests/unit/db/budget-ticket-json-migration.test.ts b/server/tests/unit/db/budget-ticket-json-migration.test.ts index ec47799bb..380656be0 100644 --- a/server/tests/unit/db/budget-ticket-json-migration.test.ts +++ b/server/tests/unit/db/budget-ticket-json-migration.test.ts @@ -9,119 +9,116 @@ * The second half covers the databases that ran the LIKE version before it was * repaired — a fixed step never replays, so the damage is undone by a migration * of its own at the end of the array. + * + * Ported off the legacy runner (Task 0 triage: PORT — both migrations) onto the + * real `Migration20200101030600_free_the_note_column_on_budget_items` (forward) + * and `Migration20200101031700_give_back_the_notes_the_ticketjson_step` + * (recovery): migrate to the step immediately before each, seed rows with raw + * SQL, apply just that one migration, assert. */ import { describe, it, expect } from 'vitest'; -import Database from 'better-sqlite3'; -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; +import type { MikroORM } from '@mikro-orm/sqlite'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; -function makeDbWithNotes(): Database.Database { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA busy_timeout = 5000'); - db.exec('PRAGMA foreign_keys = ON'); - createTables(db); - // Minimal FK chain: user -> trip -> budget_items rows. - db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run(); - db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run(); - db.prepare( - 'INSERT INTO budget_items (id, trip_id, name, note) VALUES (1, 1, ?, ?), (2, 1, ?, ?)', - ).run('Dinner', 'TICKETJSON:{"items":[]}', 'Museum', 'ticketjson: buy at the door'); - return db; +const FORWARD = 'Migration20200101030600_free_the_note_column_on_budget_items'; +const RECOVERY = 'Migration20200101031700_give_back_the_notes_the_ticketjson_step'; + +async function ormBefore(target: string): Promise<{ orm: MikroORM; names: string[]; idx: number }> { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const idx = names.indexOf(target); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + return { orm, names, idx }; } -describe('budget_items ticket_json migration', () => { - it('moves a real receipt into ticket_json and clears the note', () => { - const db = makeDbWithNotes(); - try { - runMigrations(db); - const row = db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = 1').get() as { - note: string | null; - ticket_json: string | null; - }; - expect(row).toEqual({ note: null, ticket_json: '{"items":[]}' }); - } finally { - db.close(); - } - }); +const readRow = (orm: MikroORM, id: number) => + rawQuery<{ note: string | null; ticket_json: string | null }>(orm, 'SELECT note, ticket_json FROM budget_items WHERE id = ?', [id]).then((r) => r[0]); - it('leaves a lowercase note alone (LIKE would have eaten it)', () => { - const db = makeDbWithNotes(); +describe('budget_items ticket_json migration', () => { + async function ormWithNotes(): Promise { + const { orm } = await ormBefore(FORWARD); + // Minimal FK chain: user -> trip -> budget_items rows. + await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')"); + await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')"); + await rawExec( + orm, + 'INSERT INTO budget_items (id, trip_id, name, note) VALUES (1, 1, ?, ?), (2, 1, ?, ?)', + ['Dinner', 'TICKETJSON:{"items":[]}', 'Museum', 'ticketjson: buy at the door'], + ); + return orm; + } + + it('moves a real receipt into ticket_json and clears the note', async () => { + const orm = await ormWithNotes(); try { - runMigrations(db); - const row = db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = 2').get() as { - note: string | null; - ticket_json: string | null; - }; - expect(row).toEqual({ note: 'ticketjson: buy at the door', ticket_json: null }); + await migrateTo(orm, FORWARD); + expect(await readRow(orm, 1)).toEqual({ note: null, ticket_json: '{"items":[]}' }); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); + + it('leaves a lowercase note alone (LIKE would have eaten it)', async () => { + const orm = await ormWithNotes(); + try { + await migrateTo(orm, FORWARD); + expect(await readRow(orm, 2)).toEqual({ note: 'ticketjson: buy at the door', ticket_json: null }); + } finally { + await orm.close(true); + } + }, 30000); }); describe('recovering what the case-insensitive match destroyed', () => { /** - * A database that already ran the buggy step: migrated to the tip, then wound - * back to just before the recovery step so it runs again — which is exactly - * what an existing install does on the next boot. The wind-back target is the - * recovery step's ABSOLUTE version (the array is append-only and - * index-addressed, so it never moves); anything appended after it replays too, - * which every later migration must tolerate anyway. + * A database that already ran the buggy step: migrate to just before the + * recovery migration, then seed rows in the SHAPE the buggy LIKE-based step + * would have left behind — exactly what an existing install carries into the + * recovery step on its next boot. */ - function makeDamagedDb(): Database.Database { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA busy_timeout = 5000'); - db.exec('PRAGMA foreign_keys = ON'); - createTables(db); - runMigrations(db); - db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run(); - db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run(); + async function ormWithDamage(): Promise { + const { orm } = await ormBefore(RECOVERY); + await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')"); + await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')"); // Row 1: what the LIKE match left behind for "ticketjson: buy at the door". // Row 2: an actual receipt. Row 3: a receipt on a row whose owner has since // written a note. - db.prepare('INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)') - .run(1, 1, 'Museum', null, ' buy at the door'); - db.prepare('INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)') - .run(2, 1, 'Dinner', null, '{"items":[{"name":"Beer","price":"4.50","parts":[1]}]}'); - db.prepare('INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)') - .run(3, 1, 'Taxi', 'split at the hotel', '{"items":[]}'); - - // 196 = the version just before the recovery step (migration #197). - db.prepare('UPDATE schema_version SET version = ?').run(196); - return db; + await rawExec(orm, 'INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)', [ + 1, 1, 'Museum', null, ' buy at the door', + ]); + await rawExec(orm, 'INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)', [ + 2, 1, 'Dinner', null, '{"items":[{"name":"Beer","price":"4.50","parts":[1]}]}', + ]); + await rawExec(orm, 'INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)', [ + 3, 1, 'Taxi', 'split at the hotel', '{"items":[]}', + ]); + return orm; } - const read = (db: Database.Database, id: number) => - db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = ?').get(id) as { - note: string | null; - ticket_json: string | null; - }; - - it('puts a chopped note back where it came from', () => { - const db = makeDamagedDb(); + it('puts a chopped note back where it came from', async () => { + const orm = await ormWithDamage(); try { - runMigrations(db); - expect(read(db, 1)).toEqual({ note: ' buy at the door', ticket_json: null }); + await migrateTo(orm, RECOVERY); + expect(await readRow(orm, 1)).toEqual({ note: ' buy at the door', ticket_json: null }); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); - it('leaves a genuine receipt alone', () => { - const db = makeDamagedDb(); + it('leaves a genuine receipt alone', async () => { + const orm = await ormWithDamage(); try { - runMigrations(db); - expect(read(db, 2)).toEqual({ + await migrateTo(orm, RECOVERY); + expect(await readRow(orm, 2)).toEqual({ note: null, ticket_json: '{"items":[{"name":"Beer","price":"4.50","parts":[1]}]}', }); // A note written since the damage means the row was not chopped, so it is // not a candidate at all. - expect(read(db, 3)).toEqual({ note: 'split at the hotel', ticket_json: '{"items":[]}' }); + expect(await readRow(orm, 3)).toEqual({ note: 'split at the hotel', ticket_json: '{"items":[]}' }); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); }); diff --git a/server/tests/unit/db/instance-api-key-backfill.test.ts b/server/tests/unit/db/instance-api-key-backfill.test.ts index a8be1280a..d91ee3f54 100644 --- a/server/tests/unit/db/instance-api-key-backfill.test.ts +++ b/server/tests/unit/db/instance-api-key-backfill.test.ts @@ -10,132 +10,155 @@ * promotion is skipped, because the instance row outranks everybody's own * column and nobody may be moved onto a stranger's key by an upgrade. * - * Seeded before runMigrations rather than by rewinding schema_version - * afterwards: createTables already brings users.role and both key columns, so - * the backfill fires on its normal pass and finds the rows. That keeps this - * file independent of where the entry sits in the append-only array, so - * appending the next migration does not drag it along. The one guard that does - * have to track the tail is tests/integration/leg-mode-incoming.test.ts, which - * says so in place. + * Ported off the legacy runner (Task 0 triage: PORT) onto the real + * `Migration20200101031100_1939`: migrate to the step immediately before it, + * seed rows with raw SQL, apply just that one migration, assert. */ import { describe, it, expect } from 'vitest'; -import Database from 'better-sqlite3'; -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; +import type { MikroORM } from '@mikro-orm/sqlite'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; -function freshDb() { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA foreign_keys = ON'); - createTables(db); - return db; +const TARGET = 'Migration20200101031100_1939'; + +async function ormBeforeTarget(): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + return orm; } -function seedUser( - db: Database.Database, +async function seedUser( + orm: MikroORM, id: number, role: 'admin' | 'user', keys: { maps?: string; unsplash?: string } = {}, -) { - db.prepare( +): Promise { + await rawExec( + orm, `INSERT INTO users (id, username, email, password_hash, role, maps_api_key, unsplash_api_key) - VALUES (?, ?, ?, 'x', ?, ?, ?)` - ).run(id, `u${id}`, `u${id}@test.local`, role, keys.maps ?? null, keys.unsplash ?? null); + VALUES (?, ?, ?, 'x', ?, ?, ?)`, + [id, `u${id}`, `u${id}@test.local`, role, keys.maps ?? null, keys.unsplash ?? null], + ); } -const setting = (db: Database.Database, key: string) => - (db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value; +async function setting(orm: MikroORM, key: string): Promise { + const rows = await rawQuery<{ value: string }>(orm, 'SELECT value FROM app_settings WHERE key = ?', [key]); + return rows[0]?.value; +} describe('instance API-key backfill migration', () => { - it('KEYFILL-001: copies the one key the install was searching with and keeps the column', () => { - const db = freshDb(); - seedUser(db, 1, 'admin', { maps: 'the-admin-google', unsplash: 'the-admin-unsplash' }); - seedUser(db, 2, 'user'); + it('KEYFILL-001: copies the one key the install was searching with and keeps the column', async () => { + const orm = await ormBeforeTarget(); + try { + await seedUser(orm, 1, 'admin', { maps: 'the-admin-google', unsplash: 'the-admin-unsplash' }); + await seedUser(orm, 2, 'user'); - runMigrations(db); + await migrateTo(orm, TARGET); - expect(setting(db, 'maps_api_key')).toBe('the-admin-google'); - expect(setting(db, 'unsplash_api_key')).toBe('the-admin-unsplash'); - // Nothing is taken away: the columns are still the per-user fallback. - const row = db.prepare('SELECT maps_api_key FROM users WHERE id = 1').get() as { maps_api_key: string }; - expect(row.maps_api_key).toBe('the-admin-google'); - db.close(); - }); + expect(await setting(orm, 'maps_api_key')).toBe('the-admin-google'); + expect(await setting(orm, 'unsplash_api_key')).toBe('the-admin-unsplash'); + // Nothing is taken away: the columns are still the per-user fallback. + const rows = await rawQuery<{ maps_api_key: string }>(orm, 'SELECT maps_api_key FROM users WHERE id = 1'); + expect(rows[0].maps_api_key).toBe('the-admin-google'); + } finally { + await orm.close(true); + } + }, 30000); - it('KEYFILL-002: skips an admin whose column is empty and takes the next one', () => { - const db = freshDb(); - seedUser(db, 1, 'admin', { maps: '' }); - seedUser(db, 2, 'admin', { maps: 'the-only-real-key' }); + it('KEYFILL-002: skips an admin whose column is empty and takes the next one', async () => { + const orm = await ormBeforeTarget(); + try { + await seedUser(orm, 1, 'admin', { maps: '' }); + await seedUser(orm, 2, 'admin', { maps: 'the-only-real-key' }); - runMigrations(db); + await migrateTo(orm, TARGET); - expect(setting(db, 'maps_api_key')).toBe('the-only-real-key'); - db.close(); - }); + expect(await setting(orm, 'maps_api_key')).toBe('the-only-real-key'); + } finally { + await orm.close(true); + } + }, 30000); - it('KEYFILL-003: never overwrites a value the admin has already saved instance-wide', () => { - const db = freshDb(); - seedUser(db, 1, 'admin', { maps: 'old-column-key' }); - db.prepare("INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'already-instance-wide')").run(); + it('KEYFILL-003: never overwrites a value the admin has already saved instance-wide', async () => { + const orm = await ormBeforeTarget(); + try { + await seedUser(orm, 1, 'admin', { maps: 'old-column-key' }); + await rawExec(orm, "INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'already-instance-wide')"); - runMigrations(db); + await migrateTo(orm, TARGET); - expect(setting(db, 'maps_api_key')).toBe('already-instance-wide'); - db.close(); - }); + expect(await setting(orm, 'maps_api_key')).toBe('already-instance-wide'); + } finally { + await orm.close(true); + } + }, 30000); - it('KEYFILL-004: ignores a non-admin key and writes no row at all', () => { - const db = freshDb(); - seedUser(db, 1, 'user', { maps: 'members-own-key' }); + it('KEYFILL-004: ignores a non-admin key and writes no row at all', async () => { + const orm = await ormBeforeTarget(); + try { + await seedUser(orm, 1, 'user', { maps: 'members-own-key' }); - runMigrations(db); + await migrateTo(orm, TARGET); - // A member's key stays theirs — the resolver still finds it for them, and - // promoting it would hand their billing to the whole instance. - expect(setting(db, 'maps_api_key')).toBeUndefined(); - db.close(); - }); + // A member's key stays theirs — the resolver still finds it for them, and + // promoting it would hand their billing to the whole instance. + expect(await setting(orm, 'maps_api_key')).toBeUndefined(); + } finally { + await orm.close(true); + } + }, 30000); - it('KEYFILL-005: writes nothing on an install that never had a key', () => { - const db = freshDb(); - seedUser(db, 1, 'admin'); + it('KEYFILL-005: writes nothing on an install that never had a key', async () => { + const orm = await ormBeforeTarget(); + try { + await seedUser(orm, 1, 'admin'); - runMigrations(db); + await migrateTo(orm, TARGET); - expect(setting(db, 'maps_api_key')).toBeUndefined(); - expect(setting(db, 'unsplash_api_key')).toBeUndefined(); - db.close(); - }); + expect(await setting(orm, 'maps_api_key')).toBeUndefined(); + expect(await setting(orm, 'unsplash_api_key')).toBeUndefined(); + } finally { + await orm.close(true); + } + }, 30000); - it('KEYFILL-006: leaves a column alone once a member holds a key of their own', () => { - const db = freshDb(); - seedUser(db, 1, 'admin', { maps: 'admins-own-google', unsplash: 'admins-own-unsplash' }); - seedUser(db, 7, 'user', { maps: 'members-own-google' }); + it('KEYFILL-006: leaves a column alone once a member holds a key of their own', async () => { + const orm = await ormBeforeTarget(); + try { + await seedUser(orm, 1, 'admin', { maps: 'admins-own-google', unsplash: 'admins-own-unsplash' }); + await seedUser(orm, 7, 'user', { maps: 'members-own-google' }); - runMigrations(db); + await migrateTo(orm, TARGET); - // Member 7 pays for their own Google key. Promoting the admin's would put - // every one of their searches on his key and his bill, because the instance - // row is resolved before their own column. - expect(setting(db, 'maps_api_key')).toBeUndefined(); - // Decided per column: nobody else has an Unsplash key, so that one really - // was the whole install's and stays it. - expect(setting(db, 'unsplash_api_key')).toBe('admins-own-unsplash'); - const row = db.prepare('SELECT maps_api_key FROM users WHERE id = 7').get() as { maps_api_key: string }; - expect(row.maps_api_key).toBe('members-own-google'); - db.close(); - }); + // Member 7 pays for their own Google key. Promoting the admin's would put + // every one of their searches on his key and his bill, because the instance + // row is resolved before their own column. + expect(await setting(orm, 'maps_api_key')).toBeUndefined(); + // Decided per column: nobody else has an Unsplash key, so that one really + // was the whole install's and stays it. + expect(await setting(orm, 'unsplash_api_key')).toBe('admins-own-unsplash'); + const rows = await rawQuery<{ maps_api_key: string }>(orm, 'SELECT maps_api_key FROM users WHERE id = 7'); + expect(rows[0].maps_api_key).toBe('members-own-google'); + } finally { + await orm.close(true); + } + }, 30000); - it('KEYFILL-007: two admins with their own keys both keep them', () => { - const db = freshDb(); - seedUser(db, 1, 'admin', { maps: 'first-admin-google' }); - seedUser(db, 2, 'admin', { maps: 'second-admin-google' }); + it('KEYFILL-007: two admins with their own keys both keep them', async () => { + const orm = await ormBeforeTarget(); + try { + await seedUser(orm, 1, 'admin', { maps: 'first-admin-google' }); + await seedUser(orm, 2, 'admin', { maps: 'second-admin-google' }); - runMigrations(db); + await migrateTo(orm, TARGET); - expect(setting(db, 'maps_api_key')).toBeUndefined(); - const rows = db.prepare('SELECT maps_api_key FROM users ORDER BY id').all() as { maps_api_key: string }[]; - expect(rows.map((r) => r.maps_api_key)).toEqual(['first-admin-google', 'second-admin-google']); - db.close(); - }); + expect(await setting(orm, 'maps_api_key')).toBeUndefined(); + const rows = await rawQuery<{ maps_api_key: string }>(orm, 'SELECT maps_api_key FROM users ORDER BY id'); + expect(rows.map((r) => r.maps_api_key)).toEqual(['first-admin-google', 'second-admin-google']); + } finally { + await orm.close(true); + } + }, 30000); }); diff --git a/server/tests/unit/db/migration-version-atomicity.test.ts b/server/tests/unit/db/migration-version-atomicity.test.ts deleted file mode 100644 index 919cce579..000000000 --- a/server/tests/unit/db/migration-version-atomicity.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * The schema_version bump must commit with the migration that earned it. - * - * If it lands in a statement of its own, a crash between the two leaves the - * schema advanced and the version stale, and the next boot replays a step that - * is not idempotent (an INSERT INTO app_settings, say) and exits 1 forever. - */ -import { describe, it, expect, vi } from 'vitest'; -import Database from 'better-sqlite3'; -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; - -function migratedDb(): Database.Database { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA busy_timeout = 5000'); - db.exec('PRAGMA foreign_keys = ON'); - createTables(db); - runMigrations(db); - return db; -} - -describe('migration version bump atomicity', () => { - it('MIGRATE-ATOMIC-001: writes schema_version inside the migration transaction', () => { - const db = migratedDb(); - try { - const { version } = db.prepare('SELECT version FROM schema_version LIMIT 1').get() as { version: number }; - // Rewind one slot so exactly the last migration replays. - db.prepare('UPDATE schema_version SET version = ?').run(version - 1); - - const realPrepare = db.prepare.bind(db); - const inTransaction: boolean[] = []; - vi.spyOn(db, 'prepare').mockImplementation(((sql: string) => { - const stmt = realPrepare(sql); - if (sql.includes('UPDATE schema_version SET version')) { - const realRun = stmt.run.bind(stmt); - stmt.run = ((...args: unknown[]) => { - inTransaction.push(db.inTransaction); - return realRun(...(args as never[])); - }) as typeof stmt.run; - } - return stmt; - }) as typeof db.prepare); - - runMigrations(db); - - expect(inTransaction).toEqual([true]); - const after = db.prepare('SELECT version FROM schema_version LIMIT 1').get() as { version: number }; - expect(after.version).toBe(version); - } finally { - vi.restoreAllMocks(); - db.close(); - } - }); -}); diff --git a/server/tests/unit/db/reservation-ingest-state-migration.test.ts b/server/tests/unit/db/reservation-ingest-state-migration.test.ts index c69f85b97..1446143a3 100644 --- a/server/tests/unit/db/reservation-ingest-state-migration.test.ts +++ b/server/tests/unit/db/reservation-ingest-state-migration.test.ts @@ -5,52 +5,61 @@ * automated ingest can park a booking for review without publishing it. Every * row that exists before the ALTER has to come out 'live', or the migration * would empty a calendar subscription that works today. + * + * Ported off the legacy runner (Task 0 triage: PORT) onto the real + * `Migration20200101031900_reservations_an_automated_ingest_parked_for_review`: + * migrate to the step immediately before it, seed rows with raw SQL, apply + * just that one migration, assert. The replay case runs the migration class + * directly a second time (bypassing the Migrator's own "already applied, skip" + * bookkeeping) to prove the `addColumnIfMissing` guard is what the legacy + * test's schema_version rewind was really exercising. */ import { describe, it, expect } from 'vitest'; -import Database from 'better-sqlite3'; -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; +import type { MikroORM } from '@mikro-orm/sqlite'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery, runMigrationDirect } from '../../helpers/migration-step'; +import { Migration20200101031900_reservations_an_automated_ingest_parked_for_review as TargetMigration } from '../../../src/db/migrations/Migration20200101031900_reservations_an_automated_ingest_parked_for_review'; -function dbWithReservations(): Database.Database { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA busy_timeout = 5000'); - db.exec('PRAGMA foreign_keys = ON'); - createTables(db); - db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run(); - db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run(); - db.prepare("INSERT INTO reservations (id, trip_id, title, type) VALUES (1, 1, 'Old Flight', 'flight')").run(); - return db; +const TARGET = 'Migration20200101031900_reservations_an_automated_ingest_parked_for_review'; + +async function ormWithSeededReservation(): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')"); + await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')"); + await rawExec(orm, "INSERT INTO reservations (id, trip_id, title, type) VALUES (1, 1, 'Old Flight', 'flight')"); + return orm; } describe('reservations ingest_state migration', () => { - it('MIGRATE-INGEST-001: every pre-existing row comes out live', () => { - const db = dbWithReservations(); + it('MIGRATE-INGEST-001: every pre-existing row comes out live', async () => { + const orm = await ormWithSeededReservation(); try { - runMigrations(db); - const row = db.prepare('SELECT ingest_state FROM reservations WHERE id = 1').get() as { ingest_state: string }; - expect(row.ingest_state).toBe('live'); + await migrateTo(orm, TARGET); + const rows = await rawQuery<{ ingest_state: string }>(orm, 'SELECT ingest_state FROM reservations WHERE id = 1'); + expect(rows[0].ingest_state).toBe('live'); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); - it('MIGRATE-INGEST-002: running the migration twice is a no-op', () => { - const db = dbWithReservations(); + it('MIGRATE-INGEST-002: running the migration twice is a no-op', async () => { + const orm = await ormWithSeededReservation(); try { - runMigrations(db); - // Rewind the version so the step replays against a table that already has - // the column. Without the pragma_table_info guard the ALTER throws and - // runMigrations exits the process. - const version = (db.prepare('SELECT version FROM schema_version').get() as { version: number }).version; - db.prepare('UPDATE schema_version SET version = ?').run(version - 1); - runMigrations(db); + await migrateTo(orm, TARGET); + // Run the migration class directly a second time against a table that + // already has the column. Without the pragma_table_info guard the ALTER + // throws. + await runMigrationDirect(orm, TargetMigration); - const cols = db.prepare("SELECT name FROM pragma_table_info('reservations') WHERE name = 'ingest_state'").all(); + const cols = await rawQuery(orm, "SELECT name FROM pragma_table_info('reservations') WHERE name = 'ingest_state'"); expect(cols).toHaveLength(1); - expect((db.prepare('SELECT version FROM schema_version').get() as { version: number }).version).toBe(version); + const rows = await rawQuery<{ ingest_state: string }>(orm, 'SELECT ingest_state FROM reservations WHERE id = 1'); + expect(rows[0].ingest_state).toBe('live'); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); }); diff --git a/server/tests/unit/db/roadtrip-preferences-migration.test.ts b/server/tests/unit/db/roadtrip-preferences-migration.test.ts index cd9a040a0..a8baf7d60 100644 --- a/server/tests/unit/db/roadtrip-preferences-migration.test.ts +++ b/server/tests/unit/db/roadtrip-preferences-migration.test.ts @@ -1,44 +1,59 @@ -import { runMigrations } from '../../../src/db/migrations'; -import { createTables } from '../../../src/db/schema'; - -import Database from 'better-sqlite3'; +/** + * Boot migration: per-trip road-trip preferences, seeded from whatever the trip + * owner had set globally so an existing trip keeps behaving the way it did. + * + * Ported off the legacy runner (Task 0 triage: PORT) onto the real + * `Migration20200101033900_create_roadtrip_preferences`: migrate to the step + * immediately before it, seed rows with raw SQL, apply just that one migration, + * assert. The replay case runs the migration class directly a second time + * (bypassing the Migrator's own "already applied, skip" bookkeeping) to prove + * the `INSERT OR IGNORE` is what keeps a later trip override from being + * clobbered on a replay — exactly what the legacy test's schema_version rewind + * was exercising. + */ import { describe, expect, it } from 'vitest'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery, runMigrationDirect } from '../../helpers/migration-step'; +import { Migration20200101033900_create_roadtrip_preferences as TargetMigration } from '../../../src/db/migrations/Migration20200101033900_create_roadtrip_preferences'; -// The preferences table and its one-time inheritance are pinned at schema -// version 219. Anything added later is appended after it (append-only), so it -// stops being the last migration as soon as the next one lands. Rewind to just -// before it and re-run: the steps after it are idempotent, so only this one -// touches the rows seeded here. -const PREFERENCES_VERSION = 219; +const TARGET = 'Migration20200101033900_create_roadtrip_preferences'; describe('trip driving preferences migration', () => { - it('inherits owner values once, tolerates nulls and preserves trip overrides on replay', () => { - const db = new Database(':memory:'); + it('inherits owner values once, tolerates nulls and preserves trip overrides on replay', async () => { + const orm = await createMigrationOrm(); try { - createTables(db); - runMigrations(db); - db.exec( + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + + await rawExec( + orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x'), (2, 'member', 'member@test', 'x')", ); - db.exec("INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'First'), (11, 2, 'Second')"); - db.exec( + await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'First'), (11, 2, 'Second')"); + await rawExec( + orm, "INSERT INTO settings (user_id, key, value) VALUES (1, 'roadtrip_range_km', '120'), (2, 'roadtrip_range_km', '300'), (1, 'roadtrip_day_start', '\"08:00\"'), (1, 'roadtrip_day_end', NULL), (1, 'routing_base_url', '\"https://private.test\"')", ); - db.prepare('UPDATE schema_version SET version = ?').run(PREFERENCES_VERSION - 1); - runMigrations(db); - expect(db.prepare('SELECT key, value FROM roadtrip_preferences WHERE trip_id = 10 ORDER BY key').all()).toEqual([ + + await migrateTo(orm, TARGET); + + expect(await rawQuery(orm, 'SELECT key, value FROM roadtrip_preferences WHERE trip_id = 10 ORDER BY key')).toEqual([ { key: 'roadtrip_day_start', value: '"08:00"' }, { key: 'roadtrip_range_km', value: '120' }, ]); - expect(db.prepare('SELECT value FROM roadtrip_preferences WHERE trip_id = 11').get()).toEqual({ value: '300' }); - db.exec("UPDATE roadtrip_preferences SET value = '200' WHERE trip_id = 10 AND key = 'roadtrip_range_km'"); - db.prepare('UPDATE schema_version SET version = ?').run(PREFERENCES_VERSION - 1); - runMigrations(db); + expect((await rawQuery(orm, 'SELECT value FROM roadtrip_preferences WHERE trip_id = 11'))[0]).toEqual({ value: '300' }); + + await rawExec(orm, "UPDATE roadtrip_preferences SET value = '200' WHERE trip_id = 10 AND key = 'roadtrip_range_km'"); + // Replay: the migration class runs directly a second time, bypassing the + // Migrator's bookkeeping — INSERT OR IGNORE must leave the override alone. + await runMigrationDirect(orm, TargetMigration); + expect( - db.prepare("SELECT value FROM roadtrip_preferences WHERE trip_id = 10 AND key = 'roadtrip_range_km'").get(), + (await rawQuery(orm, "SELECT value FROM roadtrip_preferences WHERE trip_id = 10 AND key = 'roadtrip_range_km'"))[0], ).toEqual({ value: '200' }); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); }); diff --git a/server/tests/unit/db/seeds-admin.test.ts b/server/tests/unit/db/seeds-admin.test.ts index cd25e827e..6dacaa0f4 100644 --- a/server/tests/unit/db/seeds-admin.test.ts +++ b/server/tests/unit/db/seeds-admin.test.ts @@ -1,13 +1,18 @@ /** - * First-run admin seeding (seedAdminAccount). + * First-run admin seeding — the live MikroORM `AdminSeeder` (`db/seeders/AdminSeeder.ts`), + * not the retired `db/seeds.ts::seedAdminAccount` this file used to test (that function + * has no production caller any more — `db/orm.ts`'s own comment says it "replaces + * createTables() → runMigrations() → runSeeds()"). Same behavior, same env reads + * (`readEnv().adminBootstrap`), redirected to the seeder that actually runs at boot. * * Covers the #1339 fix: ADMIN_EMAIL/ADMIN_PASSWORD only take effect on first run * (empty database). Setting them once a user exists must no longer be silent — it * has to warn — and a partial config (only one of the two) must warn too instead * of quietly falling back to a generated password. */ -import { seedAdminAccount } from '../../../src/db/seeds'; -import { createTestDb } from '../../helpers/test-db'; +import { AdminSeeder } from '../../../src/db/seeders/AdminSeeder'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; import type Database from 'better-sqlite3'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; @@ -24,12 +29,14 @@ function insertExistingUser(db: Database.Database): void { ).run(); } -describe('seedAdminAccount — first-run admin', () => { +describe('AdminSeeder — first-run admin', () => { let db: Database.Database; + let t: TestOrm; let saved: Record; - beforeEach(() => { - db = createTestDb(); + beforeEach(async () => { + db = createSnapshotTestDb(); + t = await createTestOrm(db); saved = {}; for (const k of ENV_KEYS) { saved[k] = process.env[k]; @@ -37,7 +44,8 @@ describe('seedAdminAccount — first-run admin', () => { } }); - afterEach(() => { + afterEach(async () => { + await t.close(); db.close(); for (const k of ENV_KEYS) { if (saved[k] === undefined) delete process.env[k]; @@ -46,12 +54,12 @@ describe('seedAdminAccount — first-run admin', () => { vi.restoreAllMocks(); }); - it('creates the admin from ADMIN_EMAIL/ADMIN_PASSWORD on an empty database', () => { + it('creates the admin from ADMIN_EMAIL/ADMIN_PASSWORD on an empty database', async () => { process.env.ADMIN_EMAIL = 'me@example.com'; process.env.ADMIN_PASSWORD = 'S3cret-pw'; const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - seedAdminAccount(db); + await new AdminSeeder().run(t.em); const user = db .prepare('SELECT email, role, must_change_password FROM users WHERE email = ?') @@ -62,13 +70,13 @@ describe('seedAdminAccount — first-run admin', () => { expect(warn).not.toHaveBeenCalled(); }); - it('warns and creates nothing when ADMIN_* is set but a user already exists', () => { + it('warns and creates nothing when ADMIN_* is set but a user already exists', async () => { insertExistingUser(db); process.env.ADMIN_EMAIL = 'new@example.com'; process.env.ADMIN_PASSWORD = 'whatever'; const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - seedAdminAccount(db); + await new AdminSeeder().run(t.em); expect(countUsers(db)).toBe(1); expect(db.prepare('SELECT 1 FROM users WHERE email = ?').get('new@example.com')).toBeUndefined(); @@ -76,21 +84,21 @@ describe('seedAdminAccount — first-run admin', () => { expect(msg).toContain('only apply on first run'); }); - it('stays silent when no admin env is set and a user already exists', () => { + it('stays silent when no admin env is set and a user already exists', async () => { insertExistingUser(db); const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - seedAdminAccount(db); + await new AdminSeeder().run(t.em); expect(countUsers(db)).toBe(1); expect(warn).not.toHaveBeenCalled(); }); - it('warns about a partial config and falls back to a generated password', () => { + it('warns about a partial config and falls back to a generated password', async () => { process.env.ADMIN_EMAIL = 'me@example.com'; // ADMIN_PASSWORD intentionally missing const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - seedAdminAccount(db); + await new AdminSeeder().run(t.em); // Falls back to the default local admin, NOT the provided email. expect(db.prepare('SELECT 1 FROM users WHERE email = ?').get('admin@trek.local')).toBeDefined(); diff --git a/server/tests/unit/db/trip-access.test.ts b/server/tests/unit/db/trip-access.test.ts index f432d3b3f..ab7a869cd 100644 --- a/server/tests/unit/db/trip-access.test.ts +++ b/server/tests/unit/db/trip-access.test.ts @@ -9,7 +9,7 @@ */ import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'; import { createSnapshotTestDb } from '../../helpers/db-mock'; -import { CAN_ACCESS_TRIP_SQL, buildDbMock, createTestDb, resetTestDb } from '../../helpers/test-db'; +import { CAN_ACCESS_TRIP_SQL, buildDbMock, resetTestDb } from '../../helpers/test-db'; import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; import { Trips } from '../../../src/db/entities/Trips.entity'; import type { TripsRepository } from '../../../src/db/repositories/Trips.repository'; @@ -81,7 +81,7 @@ describe('TripsRepository.findAccessible (formerly canAccessTrip)', () => { */ describe('the buildDbMock stand-in for canAccessTrip', () => { it('hands back the trip currency, like the real one', async () => { - const dbmockDb = createTestDb(); + const dbmockDb = createSnapshotTestDb(); try { const owner = Number( dbmockDb.prepare("INSERT INTO users (username, email, password_hash, role) VALUES ('m', 'm@example.test', 'x', 'user')") diff --git a/server/tests/unit/db/trip-days-backfill-migration.test.ts b/server/tests/unit/db/trip-days-backfill-migration.test.ts index 5fa058936..fa31671a4 100644 --- a/server/tests/unit/db/trip-days-backfill-migration.test.ts +++ b/server/tests/unit/db/trip-days-backfill-migration.test.ts @@ -1,170 +1,176 @@ /** - * Boot migration: days a trip lost past the old 365-day limit (#2403). + * Boot migrations: days a trip lost past the old 365-day limit (#2403). * * generateDays used to clip the day rows while the trip kept its full end - * date. The migration appends the missing dated days to a trip whose dated - * rows are still the unbroken run from its start date, keeps content-bearing - * dateless days behind them, and leaves every other trip alone. + * date. The backfill migration appends the missing dated days to a trip whose + * dated rows are still the unbroken run from its start date, keeps + * content-bearing dateless days behind them, and leaves every other trip + * alone. A second, separate migration rebuilds `roadtrip_day_boundaries` to + * drop the day_number CHECK that mirrored the old limit. + * + * Task 0's triage flagged this as "likely PORT, confirm a single migration + * covers both legacy steps 240 and 241 before porting" — it does NOT: they are + * two separate numbered migrations. Ported off the legacy runner onto both: + * `Migration20200101040000_trips_longer_than_a_year_lost_every` (step 240, + * backfill) and `Migration20200101040100_the_road_trip_day_boundaries_carried_the` + * (step 241, rebuild). Migrate to the step immediately before each, seed rows + * with raw SQL, apply just that one migration, assert. */ -import { runMigrations } from '../../../src/db/migrations'; -import { createTables } from '../../../src/db/schema'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery, runMigrationDirect } from '../../helpers/migration-step'; +import type { MikroORM } from '@mikro-orm/sqlite'; -import Database from 'better-sqlite3'; import { describe, it, expect } from 'vitest'; +import { Migration20200101040000_trips_longer_than_a_year_lost_every as BackfillMigration } from '../../../src/db/migrations/Migration20200101040000_trips_longer_than_a_year_lost_every'; -/** Positions of the two #2403 steps in the migration array (the number the boot log prints). */ -const BACKFILL_VERSION = 240; -const REBUILD_VERSION = 241; +const BACKFILL = 'Migration20200101040000_trips_longer_than_a_year_lost_every'; +const REBUILD = 'Migration20200101040100_the_road_trip_day_boundaries_carried_the'; function dayAfter(start: string, n: number) { return new Date(Date.parse(start + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10); } -function freshDb(): Database.Database { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA busy_timeout = 5000'); - db.exec('PRAGMA foreign_keys = ON'); - createTables(db); - runMigrations(db); - db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run(); - return db; +async function ormBefore(target: string): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const idx = names.indexOf(target); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + return orm; } /** A trip the old code produced: `dated` day rows from start_date, whatever the end date says. */ -function seedClippedTrip(db: Database.Database, id: number, start: string, end: string, dated: number) { - db.prepare('INSERT INTO trips (id, user_id, title, start_date, end_date) VALUES (?, 1, ?, ?, ?)').run( - id, - `T${id}`, - start, - end, +async function seedClippedTrip(orm: MikroORM, id: number, start: string, end: string, dated: number): Promise { + await rawExec(orm, 'INSERT INTO trips (id, user_id, title, start_date, end_date) VALUES (?, 1, ?, ?, ?)', [id, `T${id}`, start, end]); + const rows: string[] = []; + const params: unknown[] = []; + for (let i = 0; i < dated; i++) { + rows.push('(?, ?, ?)'); + params.push(id, i + 1, dayAfter(start, i)); + } + if (rows.length) await rawExec(orm, `INSERT INTO days (trip_id, day_number, date) VALUES ${rows.join(', ')}`, params); +} + +async function days(orm: MikroORM, tripId: number) { + return rawQuery<{ id: number; day_number: number; date: string | null }>( + orm, 'SELECT id, day_number, date FROM days WHERE trip_id = ? ORDER BY day_number', [tripId], ); - const insert = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)'); - for (let i = 0; i < dated; i++) insert.run(id, i + 1, dayAfter(start, i)); } -function days(db: Database.Database, tripId: number) { - return db.prepare('SELECT id, day_number, date FROM days WHERE trip_id = ? ORDER BY day_number').all(tripId) as { - id: number; - day_number: number; - date: string | null; - }[]; -} - -/** Rewind schema_version so the given step (and everything after it) replays. */ -function replayFrom(db: Database.Database, version: number) { - db.prepare('UPDATE schema_version SET version = ?').run(version - 1); - runMigrations(db); +async function seedOwner(orm: MikroORM): Promise { + await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')"); } describe('trip days backfill migration (#2403)', () => { - it('MIGRATE-DAYS-001: appends the days a clipped trip is missing, in order and dated', () => { - const db = freshDb(); + it('MIGRATE-DAYS-001: appends the days a clipped trip is missing, in order and dated', async () => { + const orm = await ormBefore(BACKFILL); try { - seedClippedTrip(db, 1, '2025-01-26', '2026-01-28', 365); - const before = days(db, 1); - replayFrom(db, BACKFILL_VERSION); + await seedOwner(orm); + await seedClippedTrip(orm, 1, '2025-01-26', '2026-01-28', 365); + const before = await days(orm, 1); - const after = days(db, 1); + await migrateTo(orm, BACKFILL); + + const after = await days(orm, 1); expect(after).toHaveLength(368); // The rows that were there keep their ids and numbers. expect(after.slice(0, 365).map((d) => d.id)).toEqual(before.map((d) => d.id)); expect(after.map((d) => d.day_number)).toEqual(after.map((_, i) => i + 1)); expect(after.slice(365).map((d) => d.date)).toEqual(['2026-01-26', '2026-01-27', '2026-01-28']); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); - it('MIGRATE-DAYS-002: content-bearing dateless days stay behind the dated ones', () => { - const db = freshDb(); + it('MIGRATE-DAYS-002: content-bearing dateless days stay behind the dated ones', async () => { + const orm = await ormBefore(BACKFILL); try { - seedClippedTrip(db, 1, '2025-01-26', '2026-01-28', 365); - const spare = Number( - db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (1, 366, NULL)').run().lastInsertRowid, - ); - db.prepare("INSERT INTO day_notes (day_id, trip_id, text) VALUES (?, 1, 'keep me')").run(spare); - replayFrom(db, BACKFILL_VERSION); + await seedOwner(orm); + await seedClippedTrip(orm, 1, '2025-01-26', '2026-01-28', 365); + await rawExec(orm, 'INSERT INTO days (trip_id, day_number, date) VALUES (1, 366, NULL)'); + const spareRow = await rawQuery<{ id: number }>(orm, 'SELECT last_insert_rowid() as id'); + const spare = spareRow[0].id; + await rawExec(orm, "INSERT INTO day_notes (day_id, trip_id, text) VALUES (?, 1, 'keep me')", [spare]); - const after = days(db, 1); + await migrateTo(orm, BACKFILL); + + const after = await days(orm, 1); expect(after).toHaveLength(369); expect(after[367]).toMatchObject({ day_number: 368, date: '2026-01-28' }); expect(after[368]).toMatchObject({ id: spare, day_number: 369, date: null }); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); - it('MIGRATE-DAYS-003: leaves trips alone that were never clipped, were re-dated by hand, or exceed the new limit', () => { - const db = freshDb(); + it('MIGRATE-DAYS-003: leaves trips alone that were never clipped, were re-dated by hand, or exceed the new limit', async () => { + const orm = await ormBefore(BACKFILL); try { + await seedOwner(orm); // Complete already. - seedClippedTrip(db, 1, '2026-07-01', '2026-07-07', 7); + await seedClippedTrip(orm, 1, '2026-07-01', '2026-07-07', 7); // Longer than a year but its days no longer start on start_date. - seedClippedTrip(db, 2, '2025-01-26', '2026-01-28', 365); - db.prepare("UPDATE days SET date = '2024-12-31' WHERE trip_id = 2 AND day_number = 1").run(); + await seedClippedTrip(orm, 2, '2025-01-26', '2026-01-28', 365); + await rawExec(orm, "UPDATE days SET date = '2024-12-31' WHERE trip_id = 2 AND day_number = 1"); // Past the new limit: still refused, so still not extended. - seedClippedTrip(db, 3, '2020-01-01', '2030-01-01', 365); + await seedClippedTrip(orm, 3, '2020-01-01', '2030-01-01', 365); // Dateless trip. - db.prepare("INSERT INTO trips (id, user_id, title) VALUES (4, 1, 'no dates')").run(); - db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (4, 1, NULL)').run(); - const snapshot = [1, 2, 3, 4].map((id) => days(db, id)); - replayFrom(db, BACKFILL_VERSION); - expect([1, 2, 3, 4].map((id) => days(db, id))).toEqual(snapshot); - } finally { - db.close(); - } - }); + await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (4, 1, 'no dates')"); + await rawExec(orm, 'INSERT INTO days (trip_id, day_number, date) VALUES (4, 1, NULL)'); + const snapshot = await Promise.all([1, 2, 3, 4].map((id) => days(orm, id))); - it('MIGRATE-DAYS-004: running it twice changes nothing more', () => { - const db = freshDb(); - try { - seedClippedTrip(db, 1, '2025-01-26', '2026-01-28', 365); - replayFrom(db, BACKFILL_VERSION); - const once = days(db, 1); - replayFrom(db, BACKFILL_VERSION); - expect(days(db, 1)).toEqual(once); + await migrateTo(orm, BACKFILL); + + const after = await Promise.all([1, 2, 3, 4].map((id) => days(orm, id))); + expect(after).toEqual(snapshot); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); + + it('MIGRATE-DAYS-004: running it twice changes nothing more', async () => { + const orm = await ormBefore(BACKFILL); + try { + await seedOwner(orm); + await seedClippedTrip(orm, 1, '2025-01-26', '2026-01-28', 365); + await migrateTo(orm, BACKFILL); + const once = await days(orm, 1); + // Replay: the migration class runs directly a second time, bypassing the + // Migrator's own "already applied, skip" bookkeeping. + await runMigrationDirect(orm, BackfillMigration); + expect(await days(orm, 1)).toEqual(once); + } finally { + await orm.close(true); + } + }, 30000); }); describe('road-trip day boundary rebuild (#2403)', () => { - it('MIGRATE-DAYS-005: keeps existing boundaries and accepts a day past the old 366 ceiling', () => { - const db = freshDb(); + it('MIGRATE-DAYS-005: keeps existing boundaries and accepts a day past the old 366 ceiling', async () => { + const orm = await ormBefore(REBUILD); try { - // The table as every installation before this migration has it. - db.exec(` - DROP TABLE roadtrip_day_boundaries; - CREATE TABLE roadtrip_day_boundaries ( - trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, - day_number INTEGER NOT NULL CHECK (day_number BETWEEN 1 AND 366), - from_assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE, - to_assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE CASCADE, - fraction REAL NOT NULL CHECK (fraction BETWEEN 0 AND 1), - PRIMARY KEY (trip_id, day_number) - )`); - seedClippedTrip(db, 1, '2025-01-01', '2027-06-30', 911); - db.prepare('INSERT INTO places (trip_id, name) VALUES (1, ?), (1, ?)').run('A', 'B'); - db.prepare('INSERT INTO day_assignments (day_id, place_id) VALUES (1, 1), (2, 2)').run(); - const boundary = db.prepare( - 'INSERT INTO roadtrip_day_boundaries (trip_id, day_number, from_assignment_id, to_assignment_id, fraction) VALUES (1, ?, 1, 2, 0.5)', - ); - boundary.run(2); - expect(() => boundary.run(400)).toThrow(/CHECK/); + // At this point in the chain `roadtrip_day_boundaries` is still in the + // shape migration 33800 created it in — the OLD CHECK (1..366) — exactly + // "the table as every installation before this migration has it". + await seedOwner(orm); + await seedClippedTrip(orm, 1, '2025-01-01', '2027-06-30', 911); + await rawExec(orm, 'INSERT INTO places (trip_id, name) VALUES (1, ?), (1, ?)', ['A', 'B']); + await rawExec(orm, 'INSERT INTO day_assignments (day_id, place_id) VALUES (1, 1), (2, 2)'); + const insertBoundary = (dayNumber: number) => + rawExec(orm, 'INSERT INTO roadtrip_day_boundaries (trip_id, day_number, from_assignment_id, to_assignment_id, fraction) VALUES (1, ?, 1, 2, 0.5)', [dayNumber]); + await insertBoundary(2); + await expect(insertBoundary(400)).rejects.toThrow(/CHECK/); - replayFrom(db, REBUILD_VERSION); + await migrateTo(orm, REBUILD); - boundary.run(400); - const rows = db.prepare('SELECT day_number, fraction FROM roadtrip_day_boundaries ORDER BY day_number').all(); + await insertBoundary(400); + const rows = await rawQuery(orm, 'SELECT day_number, fraction FROM roadtrip_day_boundaries ORDER BY day_number'); expect(rows).toEqual([ { day_number: 2, fraction: 0.5 }, { day_number: 400, fraction: 0.5 }, ]); - expect(() => boundary.run(0)).toThrow(/CHECK/); + await expect(insertBoundary(0)).rejects.toThrow(/CHECK/); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); }); diff --git a/server/tests/unit/db/trip-files-prefix-migration.test.ts b/server/tests/unit/db/trip-files-prefix-migration.test.ts index e47e4317b..b960b6684 100644 --- a/server/tests/unit/db/trip-files-prefix-migration.test.ts +++ b/server/tests/unit/db/trip-files-prefix-migration.test.ts @@ -4,40 +4,39 @@ * Collab note attachments historically stored 'files/' while the file * manager stored bare names in the same column; the storage layer addresses * objects as category + bare name, so existing prefixed rows are normalized - * once at boot (storage slice 2). + * once at boot (storage slice 2). Ported off the legacy runner (Task 0 + * triage: PORT) onto the real `Migration20200101031600_storage_slice_2`: + * migrate to the step immediately before it, seed rows with raw SQL, apply + * just that one migration, assert. */ import { describe, it, expect } from 'vitest'; -import Database from 'better-sqlite3'; -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; -function makeDbWithRows(): Database.Database { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA busy_timeout = 5000'); - db.exec('PRAGMA foreign_keys = ON'); - createTables(db); - // Minimal FK chain: user → trip → trip_files rows. - db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run(); - db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run(); - db.prepare( - "INSERT INTO trip_files (trip_id, filename, original_name) VALUES (1, 'files/aaa.pdf', 'a.pdf'), (1, 'bbb.pdf', 'b.pdf')", - ).run(); - return db; -} +const TARGET = 'Migration20200101031600_storage_slice_2'; describe('trip_files files/-prefix migration', () => { - it('strips the files/ prefix from legacy collab rows and leaves bare rows alone', () => { - const db = makeDbWithRows(); + it('strips the files/ prefix from legacy collab rows and leaves bare rows alone', async () => { + const orm = await createMigrationOrm(); try { - runMigrations(db); - const names = db - .prepare('SELECT filename FROM trip_files ORDER BY id') - .all() - .map((r) => (r as { filename: string }).filename); - expect(names).toEqual(['aaa.pdf', 'bbb.pdf']); + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + + // Minimal FK chain: user → trip → trip_files rows. + await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')"); + await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')"); + await rawExec( + orm, + "INSERT INTO trip_files (trip_id, filename, original_name) VALUES (1, 'files/aaa.pdf', 'a.pdf'), (1, 'bbb.pdf', 'b.pdf')", + ); + + await migrateTo(orm, TARGET); + + const rows = await rawQuery<{ filename: string }>(orm, 'SELECT filename FROM trip_files ORDER BY id'); + expect(rows.map((r) => r.filename)).toEqual(['aaa.pdf', 'bbb.pdf']); } finally { - db.close(); + await orm.close(true); } - }); + }, 30000); }); diff --git a/server/tests/unit/demo/demo-seed.test.ts b/server/tests/unit/demo/demo-seed.test.ts index a2cfe6aa4..18ace932a 100644 --- a/server/tests/unit/demo/demo-seed.test.ts +++ b/server/tests/unit/demo/demo-seed.test.ts @@ -14,7 +14,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import type Database from 'better-sqlite3'; -import { createTestDb } from '../../helpers/test-db'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; import { createTestOrm } from '../../helpers/test-orm'; import { withRequestContext } from '../../../src/nest/database/request-context'; @@ -36,7 +36,7 @@ describe('demo seeding', () => { const realPass = process.env.DEMO_ADMIN_PASS; beforeEach(() => { - db = createTestDb(); + db = createSnapshotTestDb(); vi.spyOn(console, 'log').mockImplementation(() => undefined); }); diff --git a/server/tests/unit/plugins/operator-egress.test.ts b/server/tests/unit/plugins/operator-egress.test.ts index 043313607..388094497 100644 --- a/server/tests/unit/plugins/operator-egress.test.ts +++ b/server/tests/unit/plugins/operator-egress.test.ts @@ -12,20 +12,17 @@ * - it is always the ADMIN, never an end user, who widens it; * - changing the set RE-SPAWNS the plugin, because the child's guard is install-once. */ -import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; -const { testDb, dbMock } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - const db = new Database(':memory:'); - return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: async () => null } }; +vi.mock('../../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: async () => null }; }); -vi.mock('../../../src/db/database', () => dbMock); -import { db as dbConn } from '../../../src/db/database'; +import { db as testDb } from '../../../src/db/database'; import { DatabaseService } from '../../../src/nest/database/database.service'; vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} })); -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service'; import { createPluginRuntime } from '../../helpers/plugin-host'; import { parseManifest, ManifestError } from '../../../src/nest/plugins/install/manifest'; @@ -49,12 +46,11 @@ function install(id: string, operatorEgress: boolean, perms: string[] = ['http:o let rt: PluginRuntimeService; -beforeAll(() => { createTables(testDb); runMigrations(testDb); }); beforeEach(async () => { testDb.prepare('DELETE FROM plugins').run(); testDb.prepare('DELETE FROM plugin_egress_hosts').run(); testDb.prepare('DELETE FROM plugin_actions').run(); - rt = await createPluginRuntime(new DatabaseService(dbConn)); + rt = await createPluginRuntime(new DatabaseService(testDb)); }); describe('operator-supplied egress hosts', () => { @@ -181,8 +177,8 @@ describe('the admin list surfaces operator egress (so the chip can be shown)', ( // list() resolves required-addon dependencies through AddonsService, so it gets a real // one over the same DB. These fixtures declare no dependencies, so it is never consulted. const listPlugins = async () => { - const dbs = new DatabaseService(dbConn); - const orm = await sharedTestOrm(dbConn); + const dbs = new DatabaseService(testDb); + const orm = await sharedTestOrm(testDb); const service = new PluginsService( dbs, await createTestAddonsService(testDb, dbs), diff --git a/server/tests/unit/plugins/plugin-instance-settings.test.ts b/server/tests/unit/plugins/plugin-instance-settings.test.ts index e962175f3..0019c53ec 100644 --- a/server/tests/unit/plugins/plugin-instance-settings.test.ts +++ b/server/tests/unit/plugins/plugin-instance-settings.test.ts @@ -13,18 +13,15 @@ import os from 'node:os'; import path from 'node:path'; import type { Request } from 'express'; -const { testDb, dbMock } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - const db = new Database(':memory:'); - return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: async () => null } }; +vi.mock('../../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: async () => null }; }); -vi.mock('../../../src/db/database', () => dbMock); -import { db as dbConn } from '../../../src/db/database'; +import { db as testDb } from '../../../src/db/database'; import { DatabaseService } from '../../../src/nest/database/database.service'; vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} })); -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; import { PluginsService } from '../../../src/nest/plugins/plugins.service'; import { PluginsController } from '../../../src/nest/plugins/plugins.controller'; import { PluginConsentRequired, type PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service'; @@ -81,7 +78,7 @@ let pluginErrorLogRepo: PluginErrorLogRepository; let pluginCapabilityAuditRepo: PluginCapabilityAuditRepository; const svc = () => new PluginsService( - new DatabaseService(dbConn), + new DatabaseService(testDb), addonsService, pluginsRepo, pluginEgressHostsRepo, @@ -112,10 +109,8 @@ async function installFixturePlugin(opts: { settings: Array { - createTables(testDb); - runMigrations(testDb); - addonsService = await createTestAddonsService(testDb, new DatabaseService(dbConn)); - const orm = await sharedTestOrm(dbConn); + addonsService = await createTestAddonsService(testDb, new DatabaseService(testDb)); + const orm = await sharedTestOrm(testDb); pluginsRepo = orm.repo(Plugins); pluginEgressHostsRepo = orm.repo(PluginEgressHosts); pluginSettingsFieldsRepo = orm.repo(PluginSettingsFields); @@ -258,13 +253,13 @@ describe('required settings are enforced on save', () => { describe('respawn on save (runtime)', () => { it('INS-004 — an inactive plugin is left alone (no respawn, reports false)', async () => { install('p'); - const rt = await createPluginRuntime(new DatabaseService(dbConn)); + const rt = await createPluginRuntime(new DatabaseService(testDb)); await expect(rt.respawnIfActive('p')).resolves.toBe(false); }); it('INS-005 — an active plugin is stopped and re-activated so the child re-reads config', async () => { install('p'); - const rt = await createPluginRuntime(new DatabaseService(dbConn)); + const rt = await createPluginRuntime(new DatabaseService(testDb)); const calls: string[] = []; vi.spyOn(rt, 'isActive').mockReturnValue(true); vi.spyOn(rt, 'activate').mockImplementation(async () => { calls.push('activate'); }); @@ -380,7 +375,7 @@ describe('defaults reach the child at spawn', () => { const s = svc(); await s.updateInstanceConfig('fixture-id', { api_url: 'https://mine.example' }); - const rt = await createPluginRuntime(new DatabaseService(dbConn)); + const rt = await createPluginRuntime(new DatabaseService(testDb)); const sup = (rt as unknown as { supervisor: { activate: (...a: unknown[]) => Promise } }).supervisor; const activate = vi.spyOn(sup, 'activate').mockResolvedValue(undefined); @@ -409,7 +404,7 @@ describe('instance-scope actions (admin)', () => { } const adminReq = { user: { id: 42 } } as unknown as Request; async function controller(invoke = vi.fn(async () => ({ ok: true, message: 'pong' }))) { - const rt = await createPluginRuntime(new DatabaseService(dbConn)); + const rt = await createPluginRuntime(new DatabaseService(testDb)); // isActive normally reflects the supervisor's live child map, which nothing here // spawns — so it's stubbed to read the same DB status the test itself flips, // mirroring what an actually-activated plugin would report. diff --git a/server/tests/unit/plugins/plugin-oauth.service.test.ts b/server/tests/unit/plugins/plugin-oauth.service.test.ts index 5189e1f4b..832fce8b0 100644 --- a/server/tests/unit/plugins/plugin-oauth.service.test.ts +++ b/server/tests/unit/plugins/plugin-oauth.service.test.ts @@ -32,6 +32,7 @@ vi.mock('node:dns/promises', () => { }); import Database from 'better-sqlite3'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; import { PluginOAuthService } from '../../../src/nest/plugins/oauth/plugin-oauth.service'; import { sharedTestOrm } from '../../helpers/test-uow'; import { Plugins } from '../../../src/db/entities/Plugins.entity'; @@ -48,14 +49,8 @@ const CFG = { }; function freshDb(cfg: Record = CFG) { - const d = new Database(':memory:'); - d.exec(` - CREATE TABLE plugins (id TEXT PRIMARY KEY, config TEXT, status TEXT); - CREATE TABLE plugin_settings_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER, default_value TEXT); - CREATE TABLE plugin_oauth_tokens (plugin_id TEXT, user_id INTEGER, access_token TEXT, refresh_token TEXT, expires_at INTEGER, scope TEXT, updated_at TEXT, PRIMARY KEY (plugin_id, user_id)); - CREATE TABLE plugin_oauth_state (state TEXT PRIMARY KEY, plugin_id TEXT, user_id INTEGER, verifier TEXT, created_at INTEGER); - `); - d.prepare("INSERT INTO plugins (id, config, status) VALUES ('p', ?, 'active')").run(JSON.stringify(cfg)); + const d = createSnapshotTestDb(); + d.prepare("INSERT INTO plugins (id, name, config, status) VALUES ('p', 'p', ?, 'active')").run(JSON.stringify(cfg)); return d; } diff --git a/server/tests/unit/plugins/plugin-user-settings.test.ts b/server/tests/unit/plugins/plugin-user-settings.test.ts index c98bae1be..c313f10f6 100644 --- a/server/tests/unit/plugins/plugin-user-settings.test.ts +++ b/server/tests/unit/plugins/plugin-user-settings.test.ts @@ -18,6 +18,7 @@ vi.mock('../../../src/db/database', () => ({ get db() { return getDb.current; } import { db as dbConn } from '../../../src/db/database'; import { DatabaseService } from '../../../src/nest/database/database.service'; import { createTestAddonsService } from '../../helpers/test-addons'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; import Database from 'better-sqlite3'; import { PluginsService } from '../../../src/nest/plugins/plugins.service'; @@ -57,11 +58,7 @@ async function userSettings(): Promise { } function freshDb() { - const d = new Database(':memory:'); - d.exec(` - CREATE TABLE plugin_settings_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, field_key TEXT, label TEXT, input_type TEXT, placeholder TEXT, hint TEXT, required INTEGER, secret INTEGER, scope TEXT, options TEXT, default_value TEXT, sort_order INTEGER); - CREATE TABLE plugin_user_config (plugin_id TEXT, user_id INTEGER, config TEXT, updated_at TEXT, PRIMARY KEY (plugin_id, user_id)); - `); + const d = createSnapshotTestDb(); // p: a user-scope api key (secret) + a user-scope pref (not secret) + an INSTANCE field. const ins = d.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, input_type, required, secret, scope, sort_order) VALUES (?,?,?,?,?,?,?)'); ins.run('p', 'apiKey', 'text', 1, 1, 'user', 0); diff --git a/server/tests/unit/plugins/plugins-service.test.ts b/server/tests/unit/plugins/plugins-service.test.ts index e9d8b69cd..4ab91c887 100644 --- a/server/tests/unit/plugins/plugins-service.test.ts +++ b/server/tests/unit/plugins/plugins-service.test.ts @@ -4,23 +4,12 @@ */ import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest'; -const { testDb } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - const db = new Database(':memory:'); - db.exec(`CREATE TABLE plugins ( - id TEXT PRIMARY KEY, name TEXT, description TEXT, type TEXT, icon TEXT, version TEXT, - status TEXT, enabled INTEGER DEFAULT 0, last_error TEXT, reviewed_at TEXT, source_repo TEXT, config TEXT DEFAULT '{}', permissions TEXT DEFAULT '[]', granted_permissions TEXT DEFAULT '[]', capabilities TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', operator_egress INTEGER DEFAULT 0, updated_at TEXT, - author_pubkey TEXT, update_block_code TEXT, update_block_detail TEXT, update_block_version TEXT, - trek_range TEXT, sort_order INTEGER DEFAULT 0, update_hold INTEGER NOT NULL DEFAULT 0); - CREATE TABLE plugin_settings_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER, required INTEGER DEFAULT 0, input_type TEXT DEFAULT 'text', default_value TEXT, sort_order INTEGER DEFAULT 0); - CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT DEFAULT '2026-01-01'); - CREATE TABLE plugin_actions (plugin_id TEXT, action_key TEXT, label TEXT, hint TEXT, danger INTEGER DEFAULT 0, sort_order INTEGER DEFAULT 0, scope TEXT DEFAULT 'user', PRIMARY KEY (plugin_id, action_key)); - CREATE TABLE plugin_egress_hosts (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, host TEXT, created_at TEXT DEFAULT (datetime('now'))); - CREATE TABLE plugin_user_config (plugin_id TEXT, user_id INTEGER, config TEXT DEFAULT '{}', updated_at TEXT DEFAULT (datetime('now')), PRIMARY KEY (plugin_id, user_id));`); - return { testDb: db }; +vi.mock('../../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { db }; }); -vi.mock('../../../src/db/database', () => ({ db: testDb })); -import { db as dbConn } from '../../../src/db/database'; +import { db as testDb } from '../../../src/db/database'; import { DatabaseService } from '../../../src/nest/database/database.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; @@ -43,7 +32,7 @@ import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env // (over the same connection) rather than reconstructed at every call site. let addonsService: AddonsService; beforeAll(async () => { - addonsService = await createTestAddonsService(testDb, new DatabaseService(dbConn)); + addonsService = await createTestAddonsService(testDb, new DatabaseService(testDb)); }); /** @@ -55,7 +44,7 @@ beforeAll(async () => { async function makeService(): Promise { const orm = await sharedTestOrm(testDb); return new PluginsService( - new DatabaseService(dbConn), + new DatabaseService(testDb), addonsService, orm.repo(Plugins), orm.repo(PluginEgressHosts), @@ -408,7 +397,7 @@ describe('PluginsService instance config', () => { describe('PluginsService error log', () => { beforeEach(() => testDb.exec('DELETE FROM plugin_error_log')); it('lists and clears a plugin error log', async () => { - testDb.prepare("INSERT INTO plugin_error_log (plugin_id, level, message) VALUES ('p','error','boom')").run(); + testDb.prepare("INSERT INTO plugin_error_log (plugin_id, level, message, ts) VALUES ('p','error','boom','2026-01-01')").run(); const svc = await makeService(); expect(await svc.errors('p')).toEqual([{ ts: '2026-01-01', level: 'error', message: 'boom' }]); await svc.clearErrors('p'); diff --git a/server/tests/unit/plugins/settings-isolation.test.ts b/server/tests/unit/plugins/settings-isolation.test.ts index 5b6594afb..b5ddc189a 100644 --- a/server/tests/unit/plugins/settings-isolation.test.ts +++ b/server/tests/unit/plugins/settings-isolation.test.ts @@ -11,20 +11,17 @@ */ import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; -const { testDb, dbMock } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - const db = new Database(':memory:'); - return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: async () => null } }; +vi.mock('../../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: async () => null }; }); -vi.mock('../../../src/db/database', () => dbMock); -import { db as dbConn } from '../../../src/db/database'; +import { db as testDb } from '../../../src/db/database'; import { DatabaseService } from '../../../src/nest/database/database.service'; import { AuditService } from '../../../src/nest/audit/audit.service'; import { createTestAddonsService } from '../../helpers/test-addons'; vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} })); -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; import { createUser } from '../../helpers/factories'; import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service'; import { parseManifest, ManifestError } from '../../../src/nest/plugins/install/manifest'; @@ -74,12 +71,10 @@ function setUserConfig(pluginId: string, config: Record) { } beforeAll(async () => { - createTables(testDb); - runMigrations(testDb); // Plan 3j Task 4 — `userSettings()` above now needs repositories, so the ORM this // file eventually built only inside PSET-007 is built here instead, before any // test runs (PSET-001..006 call `userSettings()` with no ORM of their own). - t = await createTestOrm(dbConn); + t = await createTestOrm(testDb); }); beforeEach(() => { testDb.prepare('DELETE FROM plugin_settings_fields').run(); @@ -164,9 +159,9 @@ describe('a plugin channel label is bounded by the host', () => { ).run(JSON.stringify({ notificationChannel: { title: '🎉'.repeat(5) + 'A'.repeat(500) } })); const rt = new PluginRuntimeService( - new DatabaseService(dbConn), + new DatabaseService(testDb), new AuditService(t.repo(AuditLog), t.repo(Users)), - await createTestAddonsService(dbConn), + await createTestAddonsService(testDb), userSettings(), t.repo(Plugins), t.repo(PluginErrorLog), diff --git a/server/tests/unit/services/conflictUpdate.test.ts b/server/tests/unit/services/conflictUpdate.test.ts index da2dde6cf..70b8076aa 100644 --- a/server/tests/unit/services/conflictUpdate.test.ts +++ b/server/tests/unit/services/conflictUpdate.test.ts @@ -5,18 +5,15 @@ */ import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; -const { testDb, dbMock } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA foreign_keys = ON'); - db.exec('PRAGMA busy_timeout = 5000'); +vi.mock('../../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../../helpers/db-mock'); + const db = createSnapshotTestDb(); function getPlaceWithTags(placeId: number | string) { const p = db.prepare('SELECT * FROM places WHERE id = ?').get(placeId); if (!p) return null; return { ...(p as object), category: null, tags: [] }; } - const mock = { + return { db, closeDb: () => {}, reinitialize: () => {}, @@ -24,18 +21,14 @@ const { testDb, dbMock } = vi.hoisted(() => { canAccessTrip: async () => null, isOwner: async () => false, }; - return { testDb: db, dbMock: mock }; }); - -vi.mock('../../../src/db/database', () => dbMock); vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret', ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2', updateJwtSecret: () => {}, })); -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; +import { db as testDb } from '../../../src/db/database'; import { resetTestDb } from '../../helpers/test-db'; import { createUser, createTrip } from '../../helpers/factories'; import { accommodationsOver } from '../../helpers/accommodations-service'; @@ -161,11 +154,6 @@ beforeAll(async () => { ); }); -beforeAll(() => { - createTables(testDb); - runMigrations(testDb); -}); - beforeEach(() => { resetTestDb(testDb); }); diff --git a/server/tests/unit/services/migration.test.ts b/server/tests/unit/services/migration.test.ts index 053101a00..cf49833d8 100644 --- a/server/tests/unit/services/migration.test.ts +++ b/server/tests/unit/services/migration.test.ts @@ -1,234 +1,142 @@ /** - * Unit tests for migration 69 (normalized notification preferences). - * Covers MIGR-001 to MIGR-004. - */ -import { describe, it, expect, beforeEach, afterAll } from 'vitest'; -import Database from 'better-sqlite3'; -import { createTables } from '../../../src/db/schema'; - -function buildFreshDb() { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA foreign_keys = ON'); - return db; -} - -/** - * Run all migrations up to (but NOT including) migration 69, then return the db. - * This allows us to set up old-schema data and test that migration 69 handles it. + * Unit tests for migration 69/71 — normalized per-user per-channel + * notification preferences. Covers MIGR-001 to MIGR-004b. * - * We do this by running only the schema tables that existed before migration 69, - * seeding old data, then running migration 69 in isolation. + * Previously a hand-inlined reimplementation of the migration's SQL over a + * bespoke minimal schema, entirely decoupled from both the legacy runner and + * the real migration (its `createTables` import was unused dead code). Ported + * (Task 0/Task 5c triage: PORT — a genuine numbered-migration equivalent + * exists but had no dedicated test) onto the real + * `Migration20200101011800_normalized_per_user_per_channel_notification_preferences`: + * migrate to the step immediately before it, seed rows with raw SQL, apply + * just that one migration, assert. */ -function setupPreMigration69Db() { - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA foreign_keys = ON'); +import { describe, it, expect } from 'vitest'; +import type { MikroORM } from '@mikro-orm/sqlite'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; - // Create schema_version and users table (bare minimum) - db.exec(` - CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL DEFAULT 0); - INSERT INTO schema_version (version) VALUES (0); +const TARGET = 'Migration20200101011800_normalized_per_user_per_channel_notification_preferences'; - CREATE TABLE IF NOT EXISTS users ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - username TEXT NOT NULL UNIQUE, - password TEXT NOT NULL, - email TEXT, - role TEXT NOT NULL DEFAULT 'user' - ); - - CREATE TABLE IF NOT EXISTS app_settings ( - key TEXT PRIMARY KEY, - value TEXT - ); - - CREATE TABLE IF NOT EXISTS notification_preferences ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, - notify_trip_invite INTEGER DEFAULT 1, - notify_booking_change INTEGER DEFAULT 1, - notify_trip_reminder INTEGER DEFAULT 1, - notify_vacay_invite INTEGER DEFAULT 1, - notify_photos_shared INTEGER DEFAULT 1, - notify_collab_message INTEGER DEFAULT 1, - notify_packing_tagged INTEGER DEFAULT 1, - notify_webhook INTEGER DEFAULT 1, - UNIQUE(user_id) - ); - `); - - return db; +async function ormBeforeTarget(): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + return orm; } -/** - * Extract and run only migration 69 (index 68) from the migrations array. - * We do this by importing migrations and calling the last one directly. - */ -function runMigration69(db: ReturnType): void { - // Migration 69 logic extracted inline for isolation - db.exec(` - CREATE TABLE IF NOT EXISTS notification_channel_preferences ( - user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, - event_type TEXT NOT NULL, - channel TEXT NOT NULL, - enabled INTEGER NOT NULL DEFAULT 1, - PRIMARY KEY (user_id, event_type, channel) - ); - CREATE INDEX IF NOT EXISTS idx_ncp_user ON notification_channel_preferences(user_id); - `); - - const oldPrefs = db.prepare('SELECT * FROM notification_preferences').all() as Array>; - const eventCols: Record = { - trip_invite: 'notify_trip_invite', - booking_change: 'notify_booking_change', - trip_reminder: 'notify_trip_reminder', - vacay_invite: 'notify_vacay_invite', - photos_shared: 'notify_photos_shared', - collab_message: 'notify_collab_message', - packing_tagged: 'notify_packing_tagged', - }; - const insert = db.prepare( - 'INSERT OR IGNORE INTO notification_channel_preferences (user_id, event_type, channel, enabled) VALUES (?, ?, ?, ?)' - ); - const insertMany = db.transaction((rows: Array<[number, string, string, number]>) => { - for (const [userId, eventType, channel, enabled] of rows) { - insert.run(userId, eventType, channel, enabled); - } - }); - - for (const row of oldPrefs) { - const userId = row.user_id as number; - const webhookEnabled = (row.notify_webhook as number) ?? 0; - const rows: Array<[number, string, string, number]> = []; - for (const [eventType, col] of Object.entries(eventCols)) { - const emailEnabled = (row[col] as number) ?? 1; - if (!emailEnabled) rows.push([userId, eventType, 'email', 0]); - if (!webhookEnabled) rows.push([userId, eventType, 'webhook', 0]); - } - if (rows.length > 0) insertMany(rows); - } - - db.exec(` - INSERT OR IGNORE INTO app_settings (key, value) - SELECT 'notification_channels', value FROM app_settings WHERE key = 'notification_channel'; - `); +async function seedUser(orm: MikroORM, username: string): Promise { + await rawExec(orm, "INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, 'x', 'user')", [ + username, `${username}@example.test`, + ]); + const rows = await rawQuery<{ id: number }>(orm, 'SELECT last_insert_rowid() as id'); + return rows[0].id; } -// ───────────────────────────────────────────────────────────────────────────── -// Migration 69 tests -// ───────────────────────────────────────────────────────────────────────────── - -describe('Migration 69 — normalized notification_channel_preferences', () => { - it('MIGR-001 — notification_channel_preferences table exists after migration', () => { - const db = setupPreMigration69Db(); - runMigration69(db); - - const table = db.prepare( - `SELECT name FROM sqlite_master WHERE type='table' AND name='notification_channel_preferences'` - ).get(); - expect(table).toBeDefined(); - db.close(); - }); - - it('MIGR-002 — old notification_preferences rows with disabled events migrated as enabled=0', () => { - const db = setupPreMigration69Db(); - - // Create a user - const userId = (db.prepare('INSERT INTO users (username, password, role) VALUES (?, ?, ?)').run('testuser', 'hash', 'user')).lastInsertRowid as number; - - // Simulate user who has disabled trip_invite and booking_change email - db.prepare(` - INSERT INTO notification_preferences - (user_id, notify_trip_invite, notify_booking_change, notify_trip_reminder, - notify_vacay_invite, notify_photos_shared, notify_collab_message, notify_packing_tagged, notify_webhook) - VALUES (?, 0, 0, 1, 1, 1, 1, 1, 1) - `).run(userId); - - runMigration69(db); - - const tripInviteEmail = db.prepare( - 'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?' - ).get(userId, 'trip_invite', 'email') as { enabled: number } | undefined; - const bookingEmail = db.prepare( - 'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?' - ).get(userId, 'booking_change', 'email') as { enabled: number } | undefined; - const reminderEmail = db.prepare( - 'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?' - ).get(userId, 'trip_reminder', 'email') as { enabled: number } | undefined; - - // Disabled events should have enabled=0 rows - expect(tripInviteEmail).toBeDefined(); - expect(tripInviteEmail!.enabled).toBe(0); - expect(bookingEmail).toBeDefined(); - expect(bookingEmail!.enabled).toBe(0); - // Enabled events should have no row (no-row = enabled) - expect(reminderEmail).toBeUndefined(); - - db.close(); - }); - - it('MIGR-003 — old notify_webhook=0 creates disabled webhook rows for all 7 events', () => { - const db = setupPreMigration69Db(); - - const userId = (db.prepare('INSERT INTO users (username, password, role) VALUES (?, ?, ?)').run('webhookuser', 'hash', 'user')).lastInsertRowid as number; - - // User has all email enabled but webhook disabled - db.prepare(` - INSERT INTO notification_preferences - (user_id, notify_trip_invite, notify_booking_change, notify_trip_reminder, - notify_vacay_invite, notify_photos_shared, notify_collab_message, notify_packing_tagged, notify_webhook) - VALUES (?, 1, 1, 1, 1, 1, 1, 1, 0) - `).run(userId); - - runMigration69(db); - - const allEvents = ['trip_invite', 'booking_change', 'trip_reminder', 'vacay_invite', 'photos_shared', 'collab_message', 'packing_tagged']; - for (const eventType of allEvents) { - const row = db.prepare( - 'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?' - ).get(userId, eventType, 'webhook') as { enabled: number } | undefined; - expect(row).toBeDefined(); - expect(row!.enabled).toBe(0); - - // Email rows should NOT exist (all email was enabled → no row needed) - const emailRow = db.prepare( - 'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?' - ).get(userId, eventType, 'email'); - expect(emailRow).toBeUndefined(); +describe('Migration 69/71 — normalized notification_channel_preferences', () => { + it('MIGR-001 — notification_channel_preferences table exists after migration', async () => { + const orm = await ormBeforeTarget(); + try { + await migrateTo(orm, TARGET); + const table = await rawQuery(orm, `SELECT name FROM sqlite_master WHERE type='table' AND name='notification_channel_preferences'`); + expect(table[0]).toBeDefined(); + } finally { + await orm.close(true); } + }, 30000); - db.close(); - }); + it('MIGR-002 — old notification_preferences rows with disabled events migrated as enabled=0', async () => { + const orm = await ormBeforeTarget(); + try { + const userId = await seedUser(orm, 'testuser'); + // Simulate user who has disabled trip_invite and booking_change email + await rawExec(orm, ` + INSERT INTO notification_preferences + (user_id, notify_trip_invite, notify_booking_change, notify_trip_reminder, + notify_vacay_invite, notify_photos_shared, notify_collab_message, notify_packing_tagged, notify_webhook) + VALUES (?, 0, 0, 1, 1, 1, 1, 1, 1) + `, [userId]); - it('MIGR-004 — notification_channels key is created in app_settings from notification_channel value', () => { - const db = setupPreMigration69Db(); + await migrateTo(orm, TARGET); - // Simulate existing single-channel setting - db.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?)').run('notification_channel', 'email'); + const read = (eventType: string) => + rawQuery<{ enabled: number }>(orm, 'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?', [userId, eventType, 'email']).then((r) => r[0]); + const tripInviteEmail = await read('trip_invite'); + const bookingEmail = await read('booking_change'); + const reminderEmail = await read('trip_reminder'); - runMigration69(db); + // Disabled events should have enabled=0 rows + expect(tripInviteEmail).toBeDefined(); + expect(tripInviteEmail!.enabled).toBe(0); + expect(bookingEmail).toBeDefined(); + expect(bookingEmail!.enabled).toBe(0); + // Enabled events should have no row (no-row = enabled) + expect(reminderEmail).toBeUndefined(); + } finally { + await orm.close(true); + } + }, 30000); - const plural = db.prepare('SELECT value FROM app_settings WHERE key = ?').get('notification_channels') as { value: string } | undefined; - expect(plural).toBeDefined(); - expect(plural!.value).toBe('email'); + it('MIGR-003 — old notify_webhook=0 creates disabled webhook rows for all 7 events', async () => { + const orm = await ormBeforeTarget(); + try { + const userId = await seedUser(orm, 'webhookuser'); + // User has all email enabled but webhook disabled + await rawExec(orm, ` + INSERT INTO notification_preferences + (user_id, notify_trip_invite, notify_booking_change, notify_trip_reminder, + notify_vacay_invite, notify_photos_shared, notify_collab_message, notify_packing_tagged, notify_webhook) + VALUES (?, 1, 1, 1, 1, 1, 1, 1, 0) + `, [userId]); - db.close(); - }); + await migrateTo(orm, TARGET); - it('MIGR-004b — notification_channels is not duplicated if already exists', () => { - const db = setupPreMigration69Db(); + const allEvents = ['trip_invite', 'booking_change', 'trip_reminder', 'vacay_invite', 'photos_shared', 'collab_message', 'packing_tagged']; + for (const eventType of allEvents) { + const row = (await rawQuery<{ enabled: number }>(orm, 'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?', [userId, eventType, 'webhook']))[0]; + expect(row).toBeDefined(); + expect(row!.enabled).toBe(0); - // Both keys already set (e.g. partial migration or manual edit) - db.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?)').run('notification_channel', 'email'); - db.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?)').run('notification_channels', 'email,webhook'); + // Email rows should NOT exist (all email was enabled → no row needed) + const emailRow = (await rawQuery(orm, 'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?', [userId, eventType, 'email']))[0]; + expect(emailRow).toBeUndefined(); + } + } finally { + await orm.close(true); + } + }, 30000); - runMigration69(db); + it('MIGR-004 — notification_channels key is created in app_settings from notification_channel value', async () => { + const orm = await ormBeforeTarget(); + try { + // Simulate existing single-channel setting + await rawExec(orm, "INSERT INTO app_settings (key, value) VALUES (?, ?)", ['notification_channel', 'email']); - // The existing notification_channels value should be preserved (INSERT OR IGNORE) - const plural = db.prepare('SELECT value FROM app_settings WHERE key = ?').get('notification_channels') as { value: string } | undefined; - expect(plural!.value).toBe('email,webhook'); + await migrateTo(orm, TARGET); - db.close(); - }); + const plural = (await rawQuery<{ value: string }>(orm, 'SELECT value FROM app_settings WHERE key = ?', ['notification_channels']))[0]; + expect(plural).toBeDefined(); + expect(plural!.value).toBe('email'); + } finally { + await orm.close(true); + } + }, 30000); + + it('MIGR-004b — notification_channels is not duplicated if already exists', async () => { + const orm = await ormBeforeTarget(); + try { + // Both keys already set (e.g. partial migration or manual edit) + await rawExec(orm, "INSERT INTO app_settings (key, value) VALUES (?, ?)", ['notification_channel', 'email']); + await rawExec(orm, "INSERT INTO app_settings (key, value) VALUES (?, ?)", ['notification_channels', 'email,webhook']); + + await migrateTo(orm, TARGET); + + // The existing notification_channels value should be preserved (INSERT OR IGNORE) + const plural = (await rawQuery<{ value: string }>(orm, 'SELECT value FROM app_settings WHERE key = ?', ['notification_channels']))[0]; + expect(plural!.value).toBe('email,webhook'); + } finally { + await orm.close(true); + } + }, 30000); }); diff --git a/server/tests/unit/services/trekPhotoMedia.test.ts b/server/tests/unit/services/trekPhotoMedia.test.ts index 83a1fc233..87ac98fbc 100644 --- a/server/tests/unit/services/trekPhotoMedia.test.ts +++ b/server/tests/unit/services/trekPhotoMedia.test.ts @@ -4,31 +4,26 @@ */ import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; -const { testDb, dbMock } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - const db = new Database(':memory:'); +vi.mock('../../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../../helpers/db-mock'); + const db = createSnapshotTestDb(); // FKs off: this suite only checks media_type persistence, not owner/user integrity. db.exec('PRAGMA foreign_keys = OFF'); - const mock = { db, closeDb: () => {}, reinitialize: () => {}, getPlaceWithTags: async () => null, canAccessTrip: async () => null, isOwner: async () => false }; - return { testDb: db, dbMock: mock }; + return { db, closeDb: () => {}, reinitialize: () => {}, getPlaceWithTags: async () => null, canAccessTrip: async () => null, isOwner: async () => false }; }); - -vi.mock('../../../src/db/database', () => dbMock); vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret', ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2', updateJwtSecret: () => {}, })); -import { createTables } from '../../../src/db/schema'; -import { runMigrations } from '../../../src/db/migrations'; +import { db as testDb } from '../../../src/db/database'; import { createUser } from '../../helpers/factories'; import { TrekPhotoRegistrationService } from '../../../src/nest/photos/trek-photos.repository'; import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity'; import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity'; import { JourneyPhotos } from '../../../src/db/entities/JourneyPhotos.entity'; import { DatabaseService } from '../../../src/nest/database/database.service'; -import { db as trekDb } from '../../../src/db/database'; import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; // Was photos.bridge, deleted with the other three that had no consumer outside @@ -40,10 +35,8 @@ const getOrCreateLocalTrekPhoto = (...a: Parameters trekPhotos.resolve(id); beforeAll(async () => { - createTables(testDb); - runMigrations(testDb); t = await createTestOrm(testDb); - trekPhotos = new TrekPhotoRegistrationService(t.repo(TrekPhotos), t.repo(TripPhotos), t.repo(JourneyPhotos), new DatabaseService(trekDb, t.em)); + trekPhotos = new TrekPhotoRegistrationService(t.repo(TrekPhotos), t.repo(TripPhotos), t.repo(JourneyPhotos), new DatabaseService(testDb, t.em)); }); beforeEach(() => { diff --git a/server/tests/unit/services/trimUserWhitespace.test.ts b/server/tests/unit/services/trimUserWhitespace.test.ts index 0ac5afde2..ccc45dd27 100644 --- a/server/tests/unit/services/trimUserWhitespace.test.ts +++ b/server/tests/unit/services/trimUserWhitespace.test.ts @@ -1,122 +1,169 @@ /** - * Unit tests for trimUserWhitespace — the backfill migration that normalises - * leading/trailing whitespace in stored usernames and emails. + * Unit tests for the backfill migration that normalises leading/trailing + * whitespace in stored usernames and emails. * Tests TRIM-MIG-001 through TRIM-MIG-010. + * + * Ported off the legacy runner (Task 0/Task 5c triage: its production + * equivalent is a frozen numbered migration) onto the real + * `Migration20200101020800_trim_leading_trailing_whitespace_from_stored_usernames` + * (the legacy `trimUserWhitespace` export in `db/migrations.ts` was never + * called by any numbered migration — this one reimplements the same logic + * inline, deliberately, since the legacy file is not importable from there): + * migrate to the step immediately before it, seed rows with raw SQL, apply + * just that one migration, assert. */ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import Database from 'better-sqlite3'; -import { trimUserWhitespace } from '../../../src/db/migrations'; +import { describe, it, expect, vi } from 'vitest'; +import type { MikroORM } from '@mikro-orm/sqlite'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; -function makeDb() { - const db = new Database(':memory:'); - db.exec('PRAGMA foreign_keys = ON'); - db.exec(` - CREATE TABLE users ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - username TEXT UNIQUE NOT NULL, - email TEXT UNIQUE NOT NULL, - password_hash TEXT NOT NULL DEFAULT 'x', - role TEXT NOT NULL DEFAULT 'user' - ) - `); - return db; +const TARGET = 'Migration20200101020800_trim_leading_trailing_whitespace_from_stored_usernames'; + +async function ormBeforeTarget(): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + return orm; } -function insert(db: Database.Database, username: string, email: string): number { - const r = db.prepare('INSERT INTO users (username, email) VALUES (?, ?)').run(username, email); - return Number(r.lastInsertRowid); +async function insert(orm: MikroORM, username: string, email: string): Promise { + await rawExec(orm, "INSERT INTO users (username, email, password_hash) VALUES (?, ?, 'x')", [username, email]); + const rows = await rawQuery<{ id: number }>(orm, 'SELECT last_insert_rowid() as id'); + return rows[0].id; } -function row(db: Database.Database, id: number) { - return db.prepare('SELECT username, email FROM users WHERE id = ?').get(id) as { username: string; email: string }; +async function row(orm: MikroORM, id: number): Promise<{ username: string; email: string }> { + const rows = await rawQuery<{ username: string; email: string }>(orm, 'SELECT username, email FROM users WHERE id = ?', [id]); + return rows[0]; } describe('trimUserWhitespace — clean data (no-op)', () => { - it('TRIM-MIG-001 — leaves already-clean rows untouched', () => { - const db = makeDb(); - const id = insert(db, 'alice', 'alice@example.com'); - trimUserWhitespace(db); - expect(row(db, id)).toEqual({ username: 'alice', email: 'alice@example.com' }); - }); + it('TRIM-MIG-001 — leaves already-clean rows untouched', async () => { + const orm = await ormBeforeTarget(); + try { + const id = await insert(orm, 'alice', 'alice@example.com'); + await migrateTo(orm, TARGET); + expect(await row(orm, id)).toEqual({ username: 'alice', email: 'alice@example.com' }); + } finally { + await orm.close(true); + } + }, 30000); }); describe('trimUserWhitespace — non-colliding dirty rows', () => { - it('TRIM-MIG-002 — trims trailing whitespace from username', () => { - const db = makeDb(); - const id = insert(db, 'alice ', 'alice@example.com'); - trimUserWhitespace(db); - expect(row(db, id).username).toBe('alice'); - }); + it('TRIM-MIG-002 — trims trailing whitespace from username', async () => { + const orm = await ormBeforeTarget(); + try { + const id = await insert(orm, 'alice ', 'alice@example.com'); + await migrateTo(orm, TARGET); + expect((await row(orm, id)).username).toBe('alice'); + } finally { + await orm.close(true); + } + }, 30000); - it('TRIM-MIG-003 — trims leading whitespace from username', () => { - const db = makeDb(); - const id = insert(db, ' alice', 'alice@example.com'); - trimUserWhitespace(db); - expect(row(db, id).username).toBe('alice'); - }); + it('TRIM-MIG-003 — trims leading whitespace from username', async () => { + const orm = await ormBeforeTarget(); + try { + const id = await insert(orm, ' alice', 'alice@example.com'); + await migrateTo(orm, TARGET); + expect((await row(orm, id)).username).toBe('alice'); + } finally { + await orm.close(true); + } + }, 30000); - it('TRIM-MIG-004 — trims surrounding whitespace from email', () => { - const db = makeDb(); - const id = insert(db, 'alice', ' alice@example.com '); - trimUserWhitespace(db); - expect(row(db, id).email).toBe('alice@example.com'); - }); + it('TRIM-MIG-004 — trims surrounding whitespace from email', async () => { + const orm = await ormBeforeTarget(); + try { + const id = await insert(orm, 'alice', ' alice@example.com '); + await migrateTo(orm, TARGET); + expect((await row(orm, id)).email).toBe('alice@example.com'); + } finally { + await orm.close(true); + } + }, 30000); - it('TRIM-MIG-005 — emits a console.warn for each trimmed row', () => { - const db = makeDb(); - insert(db, 'bob ', 'bob@example.com'); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - trimUserWhitespace(db); - expect(warn).toHaveBeenCalledWith(expect.stringContaining('[migration] Trimmed username')); - warn.mockRestore(); - }); + it('TRIM-MIG-005 — emits a console.warn for each trimmed row', async () => { + const orm = await ormBeforeTarget(); + try { + await insert(orm, 'bob ', 'bob@example.com'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + await migrateTo(orm, TARGET); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('[migration] Trimmed username')); + warn.mockRestore(); + } finally { + await orm.close(true); + } + }, 30000); }); describe('trimUserWhitespace — username collision handling', () => { - it('TRIM-MIG-006 — renames the dirty row to __migrated_ on collision', () => { - const db = makeDb(); - insert(db, 'carol', 'carol@example.com'); - const dirtyId = insert(db, 'carol ', 'carol2@example.com'); - trimUserWhitespace(db); - expect(row(db, dirtyId).username).toBe(`carol__migrated_${dirtyId}`); - }); + it('TRIM-MIG-006 — renames the dirty row to __migrated_ on collision', async () => { + const orm = await ormBeforeTarget(); + try { + await insert(orm, 'carol', 'carol@example.com'); + const dirtyId = await insert(orm, 'carol ', 'carol2@example.com'); + await migrateTo(orm, TARGET); + expect((await row(orm, dirtyId)).username).toBe(`carol__migrated_${dirtyId}`); + } finally { + await orm.close(true); + } + }, 30000); - it('TRIM-MIG-007 — emits a WHITESPACE COLLISION warning for username collision', () => { - const db = makeDb(); - insert(db, 'dan', 'dan@example.com'); - insert(db, 'dan ', 'dan2@example.com'); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - trimUserWhitespace(db); - expect(warn).toHaveBeenCalledWith(expect.stringContaining('WHITESPACE COLLISION username')); - warn.mockRestore(); - }); + it('TRIM-MIG-007 — emits a WHITESPACE COLLISION warning for username collision', async () => { + const orm = await ormBeforeTarget(); + try { + await insert(orm, 'dan', 'dan@example.com'); + await insert(orm, 'dan ', 'dan2@example.com'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + await migrateTo(orm, TARGET); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('WHITESPACE COLLISION username')); + warn.mockRestore(); + } finally { + await orm.close(true); + } + }, 30000); - it('TRIM-MIG-008 — the renamed value does not conflict with the existing clean row', () => { - const db = makeDb(); - const cleanId = insert(db, 'eve', 'eve@example.com'); - const dirtyId = insert(db, 'eve ', 'eve2@example.com'); - trimUserWhitespace(db); - expect(row(db, cleanId).username).toBe('eve'); - expect(row(db, dirtyId).username).toBe(`eve__migrated_${dirtyId}`); - }); + it('TRIM-MIG-008 — the renamed value does not conflict with the existing clean row', async () => { + const orm = await ormBeforeTarget(); + try { + const cleanId = await insert(orm, 'eve', 'eve@example.com'); + const dirtyId = await insert(orm, 'eve ', 'eve2@example.com'); + await migrateTo(orm, TARGET); + expect((await row(orm, cleanId)).username).toBe('eve'); + expect((await row(orm, dirtyId)).username).toBe(`eve__migrated_${dirtyId}`); + } finally { + await orm.close(true); + } + }, 30000); }); describe('trimUserWhitespace — email collision handling', () => { - it('TRIM-MIG-009 — renames dirty email as __migrated_@ on collision', () => { - const db = makeDb(); - insert(db, 'frank', 'frank@example.com'); - const dirtyId = insert(db, 'frank2', ' frank@example.com '); - trimUserWhitespace(db); - expect(row(db, dirtyId).email).toBe(`frank__migrated_${dirtyId}@example.com`); - }); + it('TRIM-MIG-009 — renames dirty email as __migrated_@ on collision', async () => { + const orm = await ormBeforeTarget(); + try { + await insert(orm, 'frank', 'frank@example.com'); + const dirtyId = await insert(orm, 'frank2', ' frank@example.com '); + await migrateTo(orm, TARGET); + expect((await row(orm, dirtyId)).email).toBe(`frank__migrated_${dirtyId}@example.com`); + } finally { + await orm.close(true); + } + }, 30000); - it('TRIM-MIG-010 — emits a WHITESPACE COLLISION warning for email collision', () => { - const db = makeDb(); - insert(db, 'grace', 'grace@example.com'); - insert(db, 'grace2', 'grace@example.com '); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - trimUserWhitespace(db); - expect(warn).toHaveBeenCalledWith(expect.stringContaining('WHITESPACE COLLISION email')); - warn.mockRestore(); - }); + it('TRIM-MIG-010 — emits a WHITESPACE COLLISION warning for email collision', async () => { + const orm = await ormBeforeTarget(); + try { + await insert(orm, 'grace', 'grace@example.com'); + await insert(orm, 'grace2', 'grace@example.com '); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + await migrateTo(orm, TARGET); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('WHITESPACE COLLISION email')); + warn.mockRestore(); + } finally { + await orm.close(true); + } + }, 30000); });