The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
test(server): fit the session, transaction and seeding specs together
Maurice8c6696496165
diff --git a/server/tests/unit/demo/demo-reset-sessions.test.ts b/server/tests/unit/demo/demo-reset-sessions.test.tsindex 6be82a225..ba33ffe9d 100644--- a/server/tests/unit/demo/demo-reset-sessions.test.ts+++ b/server/tests/unit/demo/demo-reset-sessions.test.ts@@ -7,41 +7,18 @@* Without carrying the active rows across the swap, every demo visitor and* the demo admin would get a 401 on the hour.*- * The connection lifecycle is stubbed the way demo-reset-path.test.ts stubs- * it, and the stubbed `reinitialize()` stands in for the file swap by+ * The database port is a stand-in whose `replace()` plays the file swap by* emptying `user_sessions`, which is exactly what the baseline brings back.* The reads and writes around it run for real against the snapshot schema.*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import fs from 'node:fs';-import path from 'node:path';import type Database from 'better-sqlite3';import { createSnapshotTestDb } from '../../helpers/db-mock';import { createTestOrm, type TestOrm } from '../../helpers/test-orm';-import { createUser } from '../../helpers/factories';+import { makeUser } from '../../helpers/factories/users';+import { countRows, deleteRows, findRows } from '../../helpers/factories/rows';import { withRequestContext } from '../../../src/nest/database/request-context';--const LIVE_DB = path.join(path.sep, 'srv', 'trek', 'travel.db');--const { handleStub, swap, databaseModule } = vi.hoisted(() => {- const handleStub = { name: '' };- const swap: { run: () => void } = { run: () => undefined };- return {- handleStub,- swap,- databaseModule: {- getRawConnection: () => handleStub,- closeDb: vi.fn(),- reinitialize: vi.fn(async () => {- swap.run();- }),- },- };-});-vi.mock('../../../src/db/database', () => databaseModule);--const BASELINE = path.resolve(__dirname, '..', '..', '..', 'data', 'travel-baseline.db');-+import type { DatabaseBackupStrategy } from '../../../src/nest/database/database-backup.interface';import { resetDemoUser } from '../../../src/demo/demo-reset';import { SessionsService } from '../../../src/nest/sessions/sessions.service';import { verifyJwtAndLoadUser } from '../../../src/nest/auth/jwt-verify';@@ -51,18 +28,24 @@ import { UserSessions } from '../../../src/db/entities/UserSessions.entity';describe('demo reset and the signed-in sessions', () => {let ormDb: Database.Database;let t: TestOrm;+ /** What the baseline swap does to the live rows; the default empties user_sessions. */+ let swap: () => Promise<void>;+ let database: DatabaseBackupStrategy;beforeEach(async () => {- handleStub.name = LIVE_DB;vi.spyOn(console, 'log').mockImplementation(() => undefined);ormDb = createSnapshotTestDb();t = await createTestOrm(ormDb);- swap.run = () => {- ormDb.exec('DELETE FROM user_sessions');+ swap = async () => {+ await deleteRows(t, UserSessions);};- vi.spyOn(fs, 'copyFileSync').mockImplementation(() => undefined);- vi.spyOn(fs, 'unlinkSync').mockImplementation(() => undefined);- vi.spyOn(fs, 'existsSync').mockImplementation(((p: fs.PathLike) => String(p) === BASELINE) as typeof fs.existsSync);+ database = {+ checkpoint: vi.fn(async () => undefined),+ replace: vi.fn(async () => {+ await swap();+ return { reopenError: undefined };+ }),+ } as unknown as DatabaseBackupStrategy;});afterEach(async () => {@@ -74,47 +57,48 @@ describe('demo reset and the signed-in sessions', () => {const verify = (token: string) => verifyJwtAndLoadUser(token, t.repo(Users), t.repo(UserSessions));it('DEMORESET-SESS-001: a session signed in before the reset still authenticates after it', async () => {- const { user } = createUser(ormDb, { email: '[email protected]' });+ const { user } = await makeUser(t, { email: '[email protected]' });const sessions = new SessionsService(t.repo(UserSessions));const token = await sessions.issue({ id: user.id, pv: 0 }, undefined, { userAgent: 'Visitor' });expect((await verify(token))?.id).toBe(user.id);- await withRequestContext(t.orm, () => resetDemoUser());+ await withRequestContext(t.orm, () => resetDemoUser(database));t.clear();- expect(databaseModule.reinitialize).toHaveBeenCalled();+ expect(database.replace).toHaveBeenCalled();expect((await verify(token))?.id).toBe(user.id);- expect(ormDb.prepare('SELECT user_id, user_agent, revoked_at FROM user_sessions').all()).toEqual([+ const rows = await findRows(t, UserSessions);+ expect(rows.map(({ user_id, user_agent, revoked_at }) => ({ user_id, user_agent, revoked_at }))).toEqual([{ user_id: user.id, user_agent: 'Visitor', revoked_at: null },]);});it('DEMORESET-SESS-002: a session that had already ended stays ended', async () => {- const { user } = createUser(ormDb, { email: '[email protected]' });+ const { user } = await makeUser(t, { email: '[email protected]' });const sessions = new SessionsService(t.repo(UserSessions));const token = await sessions.issue({ id: user.id, pv: 0 });await sessions.revokeAll(user.id);- await withRequestContext(t.orm, () => resetDemoUser());+ await withRequestContext(t.orm, () => resetDemoUser(database));t.clear();expect(await verify(token)).toBeNull();- expect(ormDb.prepare('SELECT COUNT(*) AS n FROM user_sessions').get()).toEqual({ n: 0 });+ expect(await countRows(t, UserSessions)).toBe(0);});it('DEMORESET-SESS-003: a session whose account the baseline does not hold is not brought back', async () => {- const { user } = createUser(ormDb, { email: '[email protected]' });+ const { user } = await makeUser(t, { email: '[email protected]' });const sessions = new SessionsService(t.repo(UserSessions));const token = await sessions.issue({ id: user.id, pv: 0 });- swap.run = () => {- ormDb.exec('DELETE FROM user_sessions');- ormDb.prepare('DELETE FROM users WHERE id = ?').run(user.id);+ swap = async () => {+ await deleteRows(t, UserSessions);+ await deleteRows(t, Users, { id: user.id });};- await withRequestContext(t.orm, () => resetDemoUser());+ await withRequestContext(t.orm, () => resetDemoUser(database));t.clear();expect(await verify(token)).toBeNull();- expect(ormDb.prepare('SELECT COUNT(*) AS n FROM user_sessions').get()).toEqual({ n: 0 });+ expect(await countRows(t, UserSessions)).toBe(0);});});diff --git a/server/tests/unit/nest/addons.service.test.ts b/server/tests/unit/nest/addons.service.test.tsindex 26536c1c3..c8a950a6e 100644--- a/server/tests/unit/nest/addons.service.test.ts+++ b/server/tests/unit/nest/addons.service.test.ts@@ -420,7 +420,7 @@ describe('AddonsService addon/feature flags', () => {await expect(svc.updateCollabFeatures({ chat: false, notes: false })).rejects.toThrow('disk full');- expect(rawAppSetting('collab_chat_enabled')?.value).not.toBe('false');+ expect((await storedAppSetting('collab_chat_enabled'))?.value).not.toBe('false');expect(await svc.getCollabFeatures()).toEqual({ chat: true, notes: true, links: true, polls: true, whatsnext: true });setValueSpy.mockRestore();});diff --git a/server/tests/unit/nest/backup.impl.test.ts b/server/tests/unit/nest/backup.impl.test.tsindex c423a0b5a..1a25280a1 100644--- a/server/tests/unit/nest/backup.impl.test.ts+++ b/server/tests/unit/nest/backup.impl.test.ts@@ -2,7 +2,7 @@* Unit tests for backupService.* Covers BACKUP-031 to BACKUP-060.*/-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, onTestFinished } from 'vitest';// ---------------------------------------------------------------------------// Hoisted mocks — must be defined before any vi.mock() calls@@ -1405,7 +1405,7 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {fsMock.rmSync.mockReturnValue(undefined);fsMock.existsSync.mockImplementation((p: string) => !String(p).includes('uploads') && !String(p).endsWith('.encryption_key'));- const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');+ const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');expect(result).toEqual({ success: true });expect(callOrder).toEqual(['read', 'closeDb', 'reinitialize', 'restore']);@@ -1430,14 +1430,14 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {fsMock.rmSync.mockReturnValue(undefined);fsMock.existsSync.mockImplementation((p: string) => !String(p).includes('uploads') && !String(p).endsWith('.encryption_key'));- const unreadable = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');+ const unreadable = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');expect(unreadable).toEqual({ success: true });expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('could not read the active sessions (no such table: user_sessions)'));expect(sessionsRepo.restoreCarried).not.toHaveBeenCalled();setupSuccessfulExtraction();setupAllTablesPresent();- const unwritable = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');+ const unwritable = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');expect(unwritable).toEqual({ success: true });expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('could not keep the active sessions (database is locked)'));});diff --git a/server/tests/unit/nest/immich.service.test.ts b/server/tests/unit/nest/immich.service.test.tsindex 5671ea0bd..dc86dff07 100644--- a/server/tests/unit/nest/immich.service.test.ts+++ b/server/tests/unit/nest/immich.service.test.ts@@ -47,8 +47,7 @@ import type { MemoriesAccessService } from '../../../src/nest/memories/memories-import fs from 'node:fs';import path from 'node:path';import { makeStorageFixture } from '../../helpers/storage-fixture';-import { createTestUnitOfWork, createTestUsersRepo } from '../../helpers/test-uow';-import { createTestUsersRepo, sharedTestOrm } from '../../helpers/test-uow';+import { createTestUnitOfWork, createTestUsersRepo, sharedTestOrm } from '../../helpers/test-uow';import { deleteRows, upsertRow } from '../../helpers/factories/rows';import { readUser } from '../../helpers/factories/users';import { Users } from '../../../src/db/entities/Users.entity';@@ -195,14 +194,14 @@ describe('saveImmichSettings', () => {});it('IMMICH-052: writes auto_upload with the connection, and keeps it when the flag is absent', async () => {- const autoUpload = () => (testDb.prepare('SELECT immich_auto_upload FROM users WHERE id = ?').get(USER) as { immich_auto_upload: number }).immich_auto_upload;+ const autoUpload = async () => (await readUser(await sharedTestOrm(testDb), USER)).immich_auto_upload;await svc.saveImmichSettings(USER, 'https://new.test', 'k2', null, undefined, true);- expect(autoUpload()).toBe(1);+ expect(await autoUpload()).toBe(1);await svc.saveImmichSettings(USER, 'https://new.test', 'k2', null);- expect(autoUpload()).toBe(1);+ expect(await autoUpload()).toBe(1);await svc.saveImmichSettings(USER, undefined, undefined, null, undefined, false);- expect(autoUpload()).toBe(0);+ expect(await autoUpload()).toBe(0);});it('IMMICH-053: a refused URL writes no auto_upload either', async () => {@@ -210,7 +209,7 @@ describe('saveImmichSettings', () => {await svc.saveImmichSettings(USER, 'http://169.254.169.254', 'k', null, undefined, true);- expect(testDb.prepare('SELECT immich_auto_upload FROM users WHERE id = ?').get(USER)).toEqual({ immich_auto_upload: 0 });+ expect((await readUser(await sharedTestOrm(testDb), USER)).immich_auto_upload).toBe(0);});it('IMMICH-054: a failing auto_upload write rolls the new connection back with it', async () => {diff --git a/server/tests/unit/nest/reservations.service.test.ts b/server/tests/unit/nest/reservations.service.test.tsindex ec6339608..31bb98b13 100644--- a/server/tests/unit/nest/reservations.service.test.ts+++ b/server/tests/unit/nest/reservations.service.test.ts@@ -714,8 +714,8 @@ describe('ReservationsService (DI-native, real SQL)', () => {});it('RESV-TX-001: updateWithCost rolls the booking edit back when its cost write fails', async () => {- const { trip, res } = linkedItem({ category: 'other' });- testDb.prepare("UPDATE reservations SET title = 'Old', type = 'other' WHERE id = ?").run(res.id);+ const { trip, res } = await linkedItem({ category: 'other' });+ await updateRows(orm, Reservations, { id: res.id }, { title: 'Old', type: 'other' });const current = (await svc.getReservation(String(res.id), String(trip.id)))!;budget.updateBudgetItem.mockRejectedValueOnce(new Error('boom'));@@ -723,13 +723,13 @@ describe('ReservationsService (DI-native, real SQL)', () => {await expect(svc.updateWithCost(String(res.id), String(trip.id), { title: 'New', type: 'flight' } as never, current, undefined)).rejects.toThrow('boom');- expect(testDb.prepare('SELECT title, type FROM reservations WHERE id = ?').get(res.id)).toEqual({ title: 'Old', type: 'other' });+ expect(await findRow(orm, Reservations, { id: res.id })).toMatchObject({ title: 'Old', type: 'other' });expect(broadcast).not.toHaveBeenCalled();});it('RESV-TX-006: updateWithCost rolls the booking edit back when the new price cannot be written', async () => {- const { trip, res, item } = linkedItem({ total_price: 100 });- testDb.prepare("UPDATE reservations SET title = 'Old' WHERE id = ?").run(res.id);+ const { trip, res, item } = await linkedItem({ total_price: 100 });+ await updateRows(orm, Reservations, { id: res.id }, { title: 'Old' });const current = (await svc.getReservation(String(res.id), String(trip.id)))!;budget.updateBudgetItem.mockRejectedValueOnce(new Error('boom'));@@ -737,13 +737,13 @@ describe('ReservationsService (DI-native, real SQL)', () => {await expect(svc.updateWithCost(String(res.id), String(trip.id), { title: 'New' } as never, current, { total_price: 250 })).rejects.toThrow('boom');- expect(testDb.prepare('SELECT title FROM reservations WHERE id = ?').get(res.id)).toEqual({ title: 'Old' });- expect(testDb.prepare('SELECT total_price FROM budget_items WHERE id = ?').get(item.id)).toEqual({ total_price: 100 });+ expect(await findRow(orm, Reservations, { id: res.id })).toMatchObject({ title: 'Old' });+ expect(await findRow(orm, BudgetItems, { id: item.id })).toMatchObject({ total_price: 100 });expect(broadcast).not.toHaveBeenCalled();});it('RESV-TX-002: updateWithCost hands the cost events back instead of sending them inside the write', async () => {- const { trip, res, item } = linkedItem();+ const { trip, res, item } = await linkedItem();const current = (await svc.getReservation(String(res.id), String(trip.id)))!;budget.updateBudgetItem.mockReturnValue({ id: item.id });@@ -775,7 +775,7 @@ describe('ReservationsService (DI-native, real SQL)', () => {await expect(svc.createWithCost(String(trip.id), { title: 'Hotel', type: 'other' } as never, { total_price: 200 })).rejects.toThrow('boom');- expect(testDb.prepare('SELECT COUNT(*) AS n FROM reservations WHERE trip_id = ?').get(trip.id)).toEqual({ n: 0 });+ expect(await countRows(orm, Reservations, { trip: trip.id })).toBe(0);expect(broadcast).not.toHaveBeenCalled();});diff --git a/server/tests/unit/services/airtrailImport.test.ts b/server/tests/unit/services/airtrailImport.test.tsindex e29bc08c7..fa797eb42 100644--- a/server/tests/unit/services/airtrailImport.test.ts+++ b/server/tests/unit/services/airtrailImport.test.ts@@ -286,7 +286,7 @@ describe('importAirtrailFlights writes a booking with its link', () => {spy.mockRestore();quiet.mockRestore();}- expect(tripReservations(tripId)).toEqual([]);+ expect(await tripReservations(tripId)).toEqual([]);expect(broadcast).not.toHaveBeenCalled();});@@ -303,7 +303,7 @@ describe('importAirtrailFlights writes a booking with its link', () => {spy.mockRestore();quiet.mockRestore();}- expect(tripReservations(tripId)).toEqual([]);+ expect(await tripReservations(tripId)).toEqual([]);expect(broadcast).not.toHaveBeenCalled();});});