diff --git a/server/scripts/test-mocks-baseline.json b/server/scripts/test-mocks-baseline.json index 1d6f67d0e..9af72c6e5 100644 --- a/server/scripts/test-mocks-baseline.json +++ b/server/scripts/test-mocks-baseline.json @@ -66,9 +66,6 @@ "tests/unit/mcp/tools-notifications.test.ts": 1, "tests/unit/mcp/tools-packing-advanced.test.ts": 1, "tests/unit/mcp/tools-prompts.test.ts": 1, - "tests/unit/mcp/tools-share.test.ts": 1, - "tests/unit/mcp/tools-tags-maps-weather.test.ts": 1, - "tests/unit/mcp/tools-transit.test.ts": 1, "tests/unit/mcp/tools-transports.test.ts": 1, "tests/unit/mcp/tools-trip-members.test.ts": 1, "tests/unit/mcp/tools-trip-warnings.test.ts": 1, diff --git a/server/scripts/test-new-service-baseline.json b/server/scripts/test-new-service-baseline.json index e5550005b..d32c1d2c9 100644 --- a/server/scripts/test-new-service-baseline.json +++ b/server/scripts/test-new-service-baseline.json @@ -24,7 +24,6 @@ "tests/unit/db/repositories/UserConnections.repository.test.ts": 3, "tests/unit/demo/demo-reset-sessions.test.ts": 3, "tests/unit/mcp/tools-prompts.test.ts": 7, - "tests/unit/mcp/tools-transit.test.ts": 1, "tests/unit/nest-rpc/plugin-guards.test.ts": 1, "tests/unit/nest-rpc/rpc-kit/registry.service.test.ts": 3, "tests/unit/nest/accommodations.service.test.ts": 1, diff --git a/server/tests/postgres/snapshot-suites-baseline.json b/server/tests/postgres/snapshot-suites-baseline.json index 17203bd04..6bb793186 100644 --- a/server/tests/postgres/snapshot-suites-baseline.json +++ b/server/tests/postgres/snapshot-suites-baseline.json @@ -1,9 +1,6 @@ [ "tests/unit/mcp/tools-notifications.test.ts", "tests/unit/mcp/tools-packing-advanced.test.ts", - "tests/unit/mcp/tools-share.test.ts", - "tests/unit/mcp/tools-tags-maps-weather.test.ts", - "tests/unit/mcp/tools-transit.test.ts", "tests/unit/mcp/tools-transports.test.ts", "tests/unit/mcp/tools-trip-members.test.ts", "tests/unit/mcp/tools-trip-warnings.test.ts", diff --git a/server/tests/unit/mcp/tools-share.test.ts b/server/tests/unit/mcp/tools-share.test.ts index b7f31ed35..4d4729ef4 100644 --- a/server/tests/unit/mcp/tools-share.test.ts +++ b/server/tests/unit/mcp/tools-share.test.ts @@ -4,35 +4,30 @@ * legacy src/mcp/tools/trips.ts registrar with the trip DI port. All three * ride the canShareTrips predicate (no declarative trips:share mode exists). */ -import { db as testDb } from '../../../src/db/database'; import { ShareTokens } from '../../../src/db/entities/ShareTokens.entity'; -import { createUser, createTrip } from '../../helpers/factories'; import { findRow } from '../../helpers/factories/rows'; +import { makeTrip } from '../../helpers/factories/trips'; +import { makeUser } from '../../helpers/factories/users'; import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness'; -import { resetTestDb } from '../../helpers/test-db'; -import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; +import { resetDatabase } from '../../helpers/reset-database'; +import { bootTestApp } from '../../helpers/test-app'; +import { MikroORM } from '@mikro-orm/core'; -import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; +import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'; -vi.mock('../../../src/db/database', async () => { - const { createSnapshotTestDb, buildDbMock } = await import('../../helpers/db-mock'); - return buildDbMock(createSnapshotTestDb()); -}); - -beforeEach(() => { - resetTestDb(testDb); +beforeEach(async () => { + await resetDatabase(orm); delete process.env.DEMO_MODE; }); -let orm: TestOrm; +let orm: MikroORM; beforeAll(async () => { - orm = await createTestOrm(testDb); + orm = (await bootTestApp()).get(MikroORM); }); afterAll(async () => { - await orm.close(); - testDb.close(); + await (await bootTestApp()).close(); }); async function withHarness(userId: number, fn: (h: McpHarness) => Promise) { @@ -46,8 +41,8 @@ async function withHarness(userId: number, fn: (h: McpHarness) => Promise) describe('Tool: get_share_link', () => { it('returns null when the trip has no share link, then the token after creation', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id); await withHarness(user.id, async (h) => { const empty = parseToolResult( await h.client.callTool({ name: 'get_share_link', arguments: { tripId: trip.id } }), @@ -64,8 +59,8 @@ describe('Tool: get_share_link', () => { }); it('stores the two narrowing options like the REST route (#1712)', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id); await withHarness(user.id, async (h) => { await h.client.callTool({ name: 'create_share_link', @@ -79,9 +74,9 @@ describe('Tool: get_share_link', () => { }); it('returns access denied for a non-member trip', async () => { - const { user } = createUser(testDb); - const { user: other } = createUser(testDb); - const trip = createTrip(testDb, other.id); + const { user } = await makeUser(orm); + const { user: other } = await makeUser(orm); + const trip = await makeTrip(orm, other.id); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'get_share_link', arguments: { tripId: trip.id } }); expect(result.isError).toBe(true); @@ -91,8 +86,8 @@ describe('Tool: get_share_link', () => { describe('Tool: create_share_link', () => { it('creates with the legacy defaults, then updates in place (created=false)', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id); await withHarness(user.id, async (h) => { const first = parseToolResult( await h.client.callTool({ name: 'create_share_link', arguments: { tripId: trip.id } }), @@ -115,17 +110,17 @@ describe('Tool: create_share_link', () => { }); it('denies without trip access; blocks demo users', async () => { - const { user } = createUser(testDb); - const { user: other } = createUser(testDb); - const foreign = createTrip(testDb, other.id); + const { user } = await makeUser(orm); + const { user: other } = await makeUser(orm); + const foreign = await makeTrip(orm, other.id); await withHarness(user.id, async (h) => { expect((await h.client.callTool({ name: 'create_share_link', arguments: { tripId: foreign.id } })).isError).toBe( true, ); }); process.env.DEMO_MODE = 'true'; - const { user: demo } = createUser(testDb, { email: 'demo@nomad.app' }); - const trip = createTrip(testDb, demo.id); + const { user: demo } = await makeUser(orm, { email: 'demo@nomad.app' }); + const trip = await makeTrip(orm, demo.id); await withHarness(demo.id, async (h) => { expect((await h.client.callTool({ name: 'create_share_link', arguments: { tripId: trip.id } })).isError).toBe( true, @@ -136,8 +131,8 @@ describe('Tool: create_share_link', () => { describe('Tool: delete_share_link', () => { it('revokes the link; denies without access', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id); await withHarness(user.id, async (h) => { await h.client.callTool({ name: 'create_share_link', arguments: { tripId: trip.id } }); const result = parseToolResult( @@ -146,7 +141,7 @@ describe('Tool: delete_share_link', () => { expect(result.success).toBe(true); expect(await findRow(orm, ShareTokens, { trip: trip.id })).toBeNull(); }); - const { user: stranger } = createUser(testDb); + const { user: stranger } = await makeUser(orm); await withHarness(stranger.id, async (h) => { expect((await h.client.callTool({ name: 'delete_share_link', arguments: { tripId: trip.id } })).isError).toBe( true, diff --git a/server/tests/unit/mcp/tools-tags-maps-weather.test.ts b/server/tests/unit/mcp/tools-tags-maps-weather.test.ts index 0ec550467..1fa5894d5 100644 --- a/server/tests/unit/mcp/tools-tags-maps-weather.test.ts +++ b/server/tests/unit/mcp/tools-tags-maps-weather.test.ts @@ -4,26 +4,21 @@ * get_place_details, search_pois, reverse_geocode, resolve_maps_url, * get_weather, get_detailed_weather. */ -import { db as testDb } from '../../../src/db/database'; import { Tags } from '../../../src/db/entities/Tags.entity'; import { MapsService } from '../../../src/nest/maps/maps.service'; import { OsmClient } from '../../../src/nest/maps/providers/osm.client'; import { getWeather, getDetailedWeather } from '../../../src/nest/weather/weather.impl'; -import { createUser } from '../../helpers/factories'; import { makeTag } from '../../helpers/factories/places'; import { findRow } from '../../helpers/factories/rows'; +import { makeUser } from '../../helpers/factories/users'; import { FakeRealtimeService } from '../../helpers/fake-realtime'; import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness'; -import { resetTestDb } from '../../helpers/test-db'; -import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; +import { resetDatabase } from '../../helpers/reset-database'; +import { bootTestApp } from '../../helpers/test-app'; +import { MikroORM } from '@mikro-orm/core'; import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest'; -vi.mock('../../../src/db/database', async () => { - const { createSnapshotTestDb, buildDbMock } = await import('../../helpers/db-mock'); - return buildDbMock(createSnapshotTestDb()); -}); - // The rest of the module stays real: the booted container's WeatherService // starts and stops its cache sweep through it. vi.mock('../../../src/nest/weather/weather.impl', async (importOriginal) => ({ @@ -83,21 +78,20 @@ vi.spyOn(MapsService.prototype, 'resolveGoogleMapsUrl').mockResolvedValue({ name: 'Paris', } as never); -beforeEach(() => { - resetTestDb(testDb); +beforeEach(async () => { + await resetDatabase(orm); broadcastMock.mockClear(); delete process.env.DEMO_MODE; }); -let orm: TestOrm; +let orm: MikroORM; beforeAll(async () => { - orm = await createTestOrm(testDb); + orm = (await bootTestApp(realtime)).get(MikroORM); }); afterAll(async () => { - await orm.close(); - testDb.close(); + await (await bootTestApp(realtime)).close(); }); async function withHarness(userId: number, fn: (h: McpHarness) => Promise) { @@ -115,7 +109,7 @@ async function withHarness(userId: number, fn: (h: McpHarness) => Promise) describe('Tool: list_tags', () => { it('returns empty array initially', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'list_tags', arguments: {} }); const data = parseToolResult(result) as any; @@ -124,8 +118,8 @@ describe('Tool: list_tags', () => { }); it('returns only tags belonging to the current user', async () => { - const { user } = createUser(testDb); - const { user: other } = createUser(testDb); + const { user } = await makeUser(orm); + const { user: other } = await makeUser(orm); await makeTag(orm, user.id, { name: 'My Tag', color: '#ff0000' }); await makeTag(orm, other.id, { name: 'Other Tag', color: '#00ff00' }); await withHarness(user.id, async (h) => { @@ -143,7 +137,7 @@ describe('Tool: list_tags', () => { describe('Tool: create_tag', () => { it('creates a tag and returns the tag object', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'create_tag', @@ -158,7 +152,7 @@ describe('Tool: create_tag', () => { }); it('creates a tag with only a name', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'create_tag', @@ -171,7 +165,7 @@ describe('Tool: create_tag', () => { it('blocks demo user', async () => { process.env.DEMO_MODE = 'true'; - const { user } = createUser(testDb, { email: 'demo@nomad.app' }); + const { user } = await makeUser(orm, { email: 'demo@nomad.app' }); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'create_tag', @@ -188,7 +182,7 @@ describe('Tool: create_tag', () => { describe('Tool: update_tag', () => { it('updates tag name and color', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); const tagId = (await makeTag(orm, user.id, { name: 'Old Name', color: '#aaaaaa' })).id; await withHarness(user.id, async (h) => { const result = await h.client.callTool({ @@ -203,7 +197,7 @@ describe('Tool: update_tag', () => { }); it('returns isError for non-existent tagId', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'update_tag', @@ -215,7 +209,7 @@ describe('Tool: update_tag', () => { it('blocks demo user', async () => { process.env.DEMO_MODE = 'true'; - const { user } = createUser(testDb, { email: 'demo@nomad.app' }); + const { user } = await makeUser(orm, { email: 'demo@nomad.app' }); const tagId = (await makeTag(orm, user.id, { name: 'Demo Tag', color: '#aaaaaa' })).id; await withHarness(user.id, async (h) => { const result = await h.client.callTool({ @@ -234,7 +228,7 @@ describe('Tool: update_tag', () => { describe('Tool: delete_tag', () => { it('removes the tag row', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); const tagId = (await makeTag(orm, user.id, { name: 'To Delete', color: '#cccccc' })).id; await withHarness(user.id, async (h) => { const result = await h.client.callTool({ @@ -248,7 +242,7 @@ describe('Tool: delete_tag', () => { }); it('returns isError for non-existent tagId', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'delete_tag', @@ -260,7 +254,7 @@ describe('Tool: delete_tag', () => { it('blocks demo user', async () => { process.env.DEMO_MODE = 'true'; - const { user } = createUser(testDb, { email: 'demo@nomad.app' }); + const { user } = await makeUser(orm, { email: 'demo@nomad.app' }); const tagId = (await makeTag(orm, user.id, { name: 'Demo Tag', color: '#aaaaaa' })).id; await withHarness(user.id, async (h) => { const result = await h.client.callTool({ @@ -275,7 +269,7 @@ describe('Tool: delete_tag', () => { describe('Tag writes reach every tab of the user', () => { it('MCP-TAGS-001: create_tag, update_tag and delete_tag each ping the tag pickers of every tab', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); realtime.broadcastToUserMock.mockClear(); await withHarness(user.id, async (h) => { const created = parseToolResult( @@ -289,8 +283,8 @@ describe('Tag writes reach every tab of the user', () => { }); it('MCP-TAGS-002: a tag of another user is refused without a ping', async () => { - const { user } = createUser(testDb); - const { user: other } = createUser(testDb); + const { user } = await makeUser(orm); + const { user: other } = await makeUser(orm); const foreign = await makeTag(orm, other.id); realtime.broadcastToUserMock.mockClear(); await withHarness(user.id, async (h) => { @@ -317,13 +311,13 @@ describe('Tags tools: scope gating', () => { } it('registers all four tag tools with null scopes (full access)', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); const names = await listToolNames(user.id, null); for (const tool of TAG_TOOLS) expect(names).toContain(tool); }); it('registers only list_tags with places:read', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); const names = await listToolNames(user.id, ['places:read']); expect(names).toContain('list_tags'); expect(names).not.toContain('create_tag'); @@ -332,13 +326,13 @@ describe('Tags tools: scope gating', () => { }); it('registers all four tag tools with places:write (write implies read)', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); const names = await listToolNames(user.id, ['places:write']); for (const tool of TAG_TOOLS) expect(names).toContain(tool); }); it('registers no tag tools for an unrelated scope', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); const names = await listToolNames(user.id, ['budget:read']); for (const tool of TAG_TOOLS) expect(names).not.toContain(tool); }); @@ -350,7 +344,7 @@ describe('Tags tools: scope gating', () => { describe('Tool: get_place_details', () => { it('returns details from mocked service', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'get_place_details', @@ -370,7 +364,7 @@ describe('Tool: get_place_details', () => { // to stay on the lean lookup: nothing an existing caller does may start costing // more (#31). it('takes the lean path when expand is not asked for', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(MapsService.prototype.getPlaceDetails).mockClear(); vi.mocked(MapsService.prototype.getPlaceDetailsExpanded).mockClear(); @@ -382,7 +376,7 @@ describe('Tool: get_place_details', () => { }); it('explicitly passing expand: false also stays on the lean path', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(MapsService.prototype.getPlaceDetailsExpanded).mockClear(); await withHarness(user.id, async (h) => { @@ -395,7 +389,7 @@ describe('Tool: get_place_details', () => { }); it('expand routes to the expanded lookup and returns reviews and the summary', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(MapsService.prototype.getPlaceDetails).mockClear(); vi.mocked(MapsService.prototype.getPlaceDetailsExpanded).mockClear(); @@ -418,7 +412,7 @@ describe('Tool: get_place_details', () => { }); it('forwards refresh so a stale expanded payload can be re-fetched', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(MapsService.prototype.getPlaceDetailsExpanded).mockClear(); await withHarness(user.id, async (h) => { @@ -436,7 +430,7 @@ describe('Tool: get_place_details', () => { }); it('refuses a non-boolean expand', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(MapsService.prototype.getPlaceDetailsExpanded).mockClear(); await withHarness(user.id, async (h) => { @@ -456,7 +450,7 @@ describe('Tool: get_place_details', () => { describe('Tool: search_nearby_places', () => { it('lists what the index holds around the point, nearest first with the distance', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); trekNearbyMock.mockClear(); trekNearbyMock.mockResolvedValueOnce([ { gers: 'n-2', name: 'Farther', lat: 48.8611, lng: 2.3364, address: null, contact: null }, @@ -477,7 +471,7 @@ describe('Tool: search_nearby_places', () => { }); it('asks the index in the language the tool was given, as the REST route does (#2592)', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); trekNearbyMock.mockClear(); trekNearbyMock.mockResolvedValueOnce([ { gers: 'n-1', name: 'Closer', lat: 35.7104, lng: 139.8119, address: null, contact: null }, @@ -493,7 +487,7 @@ describe('Tool: search_nearby_places', () => { }); it('refuses a circle wider than the REST route allows', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'search_nearby_places', @@ -515,7 +509,7 @@ describe('Tool: search_pois', () => { // the drop-through: an empty index page must reach Overpass rather than come // back as an empty POI list. it('returns the POIs of a category inside the bbox', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(OsmClient.prototype.searchOverpassPois).mockClear(); trekNearbyMock.mockClear(); @@ -538,7 +532,7 @@ describe('Tool: search_pois', () => { // 'openstreetmap' because the client switches on it and these are the same // places; where they were read is this method's business, not the pill's. it('answers from the TREK Places index and leaves Overpass alone', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(OsmClient.prototype.searchOverpassPois).mockClear(); trekNearbyMock.mockClear(); trekNearbyMock.mockResolvedValueOnce([ @@ -592,7 +586,7 @@ describe('Tool: search_pois', () => { // The index searches a disc, so a viewport wider than 40km is narrowed there // as well — and says so, the same way the Overpass path does. it('reports a viewport the index had to narrow as clamped', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); trekNearbyMock.mockClear(); trekNearbyMock.mockResolvedValueOnce([ { @@ -621,7 +615,7 @@ describe('Tool: search_pois', () => { }); it('passes no language through when none is given', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(OsmClient.prototype.searchOverpassPois).mockClear(); trekNearbyMock.mockClear(); @@ -634,7 +628,7 @@ describe('Tool: search_pois', () => { // The enum is built from CATEGORY_OSM_FILTERS, so a category with no OSM tag // mapping never reaches Overpass in the first place. it('refuses a category that has no OSM mapping', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(OsmClient.prototype.searchOverpassPois).mockClear(); await withHarness(user.id, async (h) => { @@ -648,7 +642,7 @@ describe('Tool: search_pois', () => { }); it('refuses a bbox edge outside the coordinate range', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(OsmClient.prototype.searchOverpassPois).mockClear(); await withHarness(user.id, async (h) => { @@ -662,7 +656,7 @@ describe('Tool: search_pois', () => { }); it('answers isError when every Overpass mirror is unreachable', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(OsmClient.prototype.searchOverpassPois).mockRejectedValueOnce(new Error('all mirrors failed')); await withHarness(user.id, async (h) => { @@ -676,7 +670,7 @@ describe('Tool: search_pois', () => { // failure is logged and Overpass failing under it is still what reaches the // caller. it('answers isError when the index fails and every Overpass mirror is unreachable', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); trekNearbyMock.mockRejectedValueOnce(new Error('index down')); vi.mocked(OsmClient.prototype.searchOverpassPois).mockRejectedValueOnce(new Error('all mirrors failed')); @@ -696,7 +690,7 @@ describe('Tool: search_pois', () => { describe('Tool: reverse_geocode', () => { it('returns result from mocked service', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'reverse_geocode', @@ -715,7 +709,7 @@ describe('Tool: reverse_geocode', () => { describe('Tool: resolve_maps_url', () => { it('returns result from mocked service', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'resolve_maps_url', @@ -735,7 +729,7 @@ describe('Tool: resolve_maps_url', () => { describe('Tool: get_weather', () => { it('returns weather from mocked service', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'get_weather', @@ -755,7 +749,7 @@ describe('Tool: get_weather', () => { describe('Tool: get_detailed_weather', () => { it('returns detailed weather from mocked service', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'get_detailed_weather', @@ -779,7 +773,7 @@ describe('Tool: get_detailed_weather', () => { describe('Weather tools: provider failure', () => { it('get_weather answers isError with the upstream message', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(getWeather).mockRejectedValueOnce(new Error('Open-Meteo unreachable')); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ @@ -792,7 +786,7 @@ describe('Weather tools: provider failure', () => { }); it('get_weather falls back to a generic message when the rejection is not an Error', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); // A non-Error rejection has no .message, which is the only way the ?? fallback // fires — `new Error('')` still carries an (empty) message and passes through. vi.mocked(getWeather).mockRejectedValueOnce('boom' as unknown as Error); @@ -807,7 +801,7 @@ describe('Weather tools: provider failure', () => { }); it('get_detailed_weather answers isError with the upstream message', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.mocked(getDetailedWeather).mockRejectedValueOnce(new Error('rate limited')); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ @@ -829,7 +823,7 @@ describe('Weather tools: provider failure', () => { describe('Tool: search_airports', () => { it('returns matches for a city name, capped by limit', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'search_airports', arguments: { query: 'zurich', limit: 5 } }); const data = parseToolResult(result) as { airports: { iata: string }[] }; @@ -841,7 +835,7 @@ describe('Tool: search_airports', () => { }); it('applies the default limit of 10 when none is given', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'search_airports', arguments: { query: 'a' } }); const data = parseToolResult(result) as { airports: unknown[] }; @@ -850,7 +844,7 @@ describe('Tool: search_airports', () => { }); it('returns an empty list for a query that matches nothing', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'search_airports', arguments: { query: 'zzzzzznotanairport' } }); const data = parseToolResult(result) as { airports: unknown[] }; @@ -861,7 +855,7 @@ describe('Tool: search_airports', () => { describe('Tool: get_airport', () => { it('returns the airport for a known IATA code, lowercase input included', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'get_airport', arguments: { iata: 'zrh' } }); const data = parseToolResult(result) as { airport: { iata: string; tz: string } }; @@ -871,7 +865,7 @@ describe('Tool: get_airport', () => { }); it('answers isError for an unknown code rather than a null airport', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, async (h) => { const result = await h.client.callTool({ name: 'get_airport', arguments: { iata: 'QQQ' } }); expect((result as { isError?: boolean }).isError).toBe(true); @@ -895,7 +889,7 @@ describe('Tool: get_place_details (admin kill switch)', () => { }); it('fetches nothing when an admin has turned Place Details off', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.spyOn(MapsService.prototype, 'detailsDisabled').mockResolvedValue(true); vi.mocked(MapsService.prototype.getPlaceDetails).mockClear(); vi.mocked(MapsService.prototype.getPlaceDetailsExpanded).mockClear(); @@ -914,7 +908,7 @@ describe('Tool: get_place_details (admin kill switch)', () => { }); it('the switch also stops the expensive expanded path', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.spyOn(MapsService.prototype, 'detailsDisabled').mockResolvedValue(true); vi.mocked(MapsService.prototype.getPlaceDetailsExpanded).mockClear(); @@ -929,7 +923,7 @@ describe('Tool: get_place_details (admin kill switch)', () => { }); it('leaves the lookup alone while the switch is on', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); vi.spyOn(MapsService.prototype, 'detailsDisabled').mockResolvedValue(false); vi.mocked(MapsService.prototype.getPlaceDetails).mockClear(); diff --git a/server/tests/unit/mcp/tools-transit.test.ts b/server/tests/unit/mcp/tools-transit.test.ts index c90a74bbc..a3cda58bc 100644 --- a/server/tests/unit/mcp/tools-transit.test.ts +++ b/server/tests/unit/mcp/tools-transit.test.ts @@ -1,47 +1,39 @@ -import { db as testDb } from '../../../src/db/database'; import { BudgetItems } from '../../../src/db/entities/BudgetItems.entity'; import { Days } from '../../../src/db/entities/Days.entity'; import { Reservations } from '../../../src/db/entities/Reservations.entity'; +import { withRequestContext } from '../../../src/nest/database/request-context'; import { invalidatePermissionsCache } from '../../../src/nest/permissions/permissions-cache'; import { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import { ReservationsService } from '../../../src/nest/reservations/reservations.service'; import type { TransitPlace } from '../../../src/nest/transit/transit.helpers'; import { TransitService } from '../../../src/nest/transit/transit.service'; -import { addTripMember, createDay, createTrip, createUser } from '../../helpers/factories'; import { countRows, findRow } from '../../helpers/factories/rows'; +import { addTripMember, makeDay, makeTrip } from '../../helpers/factories/trips'; +import { makeUser } from '../../helpers/factories/users'; import { FakeRealtimeService } from '../../helpers/fake-realtime'; import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness'; -import { resetTestDb } from '../../helpers/test-db'; -import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; -import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow'; +import { resetDatabase } from '../../helpers/reset-database'; +import { bootTestApp } from '../../helpers/test-app'; +import { MikroORM } from '@mikro-orm/core'; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -vi.mock('../../../src/db/database', async () => { - const { createSnapshotTestDb, buildDbMock } = await import('../../helpers/db-mock'); - return buildDbMock(createSnapshotTestDb()); -}); - const realtime = new FakeRealtimeService(); const broadcastMock = realtime.broadcastMock; -// savePermissions is no longer bridged; write through a service instance — the -// permissions cache is module-scoped, so the MCP _shared checkPermission path -// sees the write immediately. +// savePermissions is no longer bridged; write through the container's own +// PermissionsService, so the MCP _shared checkPermission path sees the write +// immediately. -let permissionsService: PermissionsService; -let savePermissions: typeof permissionsService.savePermissions; +let savePermissions: PermissionsService['savePermissions']; beforeAll(async () => { - permissionsService = new PermissionsService( - await createTestAppSettingsRepo(testDb), - await createTestUnitOfWork(testDb), - ); - savePermissions = permissionsService.savePermissions.bind(permissionsService); + const permissionsService = (await bootTestApp(realtime)).get(PermissionsService); + savePermissions = (settings) => withRequestContext(orm, () => permissionsService.savePermissions(settings)); }); // The transit tools live on the DI-discovered transit.mcp.ts since the transit // fold; the test registry builds a real TransitService (and injects a real -// ReservationsService over the mocked db proxy), so stub the provider methods +// ReservationsService over the real database module), so stub the provider methods // on the prototype (no auto-restore in the vitest config — these survive // across tests, exactly like the old module mocks did). const geocodeMock = vi.spyOn(TransitService.prototype, 'geocode'); @@ -107,7 +99,7 @@ const itinerary = { }; beforeEach(async () => { - resetTestDb(testDb); + await resetDatabase(orm); geocodeMock.mockReset(); planMock.mockReset(); broadcastMock.mockReset(); @@ -117,15 +109,14 @@ beforeEach(async () => { await invalidatePermissionsCache(); }); -let orm: TestOrm; +let orm: MikroORM; beforeAll(async () => { - orm = await createTestOrm(testDb); + orm = (await bootTestApp(realtime)).get(MikroORM); }); afterAll(async () => { - await orm.close(); - testDb.close(); + await (await bootTestApp(realtime)).close(); }); /** The trip's day, on the given date or the first one; fails the test when there is none. */ @@ -148,7 +139,7 @@ async function withHarness(userId: number, scopes: string[] | null, fn: (harness describe('MCP transit tools', () => { it.each(['google', 'transitous'] as const)('preserves the %s route provider', async (provider) => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); planMock.mockResolvedValue({ itineraries: [itinerary], provider }); await withHarness(user.id, ['geo:read'], async (harness) => { const routes = parseToolResult( @@ -163,7 +154,7 @@ describe('MCP transit tools', () => { }); }); it('registers search tools for geo scope and create tool for reservations scope', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); await withHarness(user.id, ['geo:read'], async (harness) => { const names = (await harness.client.listTools()).tools.map((tool) => tool.name); expect(names).toContain('search_transit_stops'); @@ -180,7 +171,7 @@ describe('MCP transit tools', () => { }); it('forwards stop and route searches and replaces provider endpoint names', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); // `from` is a tool-input place (name/lat/lng). A geocode result is a TransitPlace, // which also carries `type` and `area`; the stop search only reads the name back out, // so the fixture stays as it is instead of growing fields nothing here looks at. @@ -229,8 +220,8 @@ describe('MCP transit tools', () => { }); it('persists a selected itinerary with local dates, endpoints, and transit metadata', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); const day = await dayOf(trip.id, '2026-12-03'); await withHarness(user.id, ['reservations:write'], async (harness) => { const result = parseToolResult( @@ -262,8 +253,8 @@ describe('MCP transit tools', () => { }); it('files the fare as a linked expense and mirrors it in the metadata', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); const day = await dayOf(trip.id, '2026-12-03'); await withHarness(user.id, ['reservations:write'], async (harness) => { const result = parseToolResult( @@ -281,8 +272,8 @@ describe('MCP transit tools', () => { }); it('files the fare under the given budget category, and records none for a free journey', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); const day = await dayOf(trip.id, '2026-12-03'); await withHarness(user.id, ['reservations:write'], async (harness) => { const paid = parseToolResult( @@ -304,8 +295,8 @@ describe('MCP transit tools', () => { }); it('records Google as the provider of a journey planned while Google answers searches (#2850)', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); const day = await dayOf(trip.id, '2026-12-03'); const active = vi.spyOn(TransitService.prototype, 'activeProvider').mockResolvedValue('google'); try { @@ -327,8 +318,8 @@ describe('MCP transit tools', () => { it.each(['google', 'transitous'] as const)( 'saves the %s fallback source from search rather than the configured primary', async (provider) => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); const day = await dayOf(trip.id, '2026-12-03'); const primary = provider === 'google' ? 'transitous' : 'google'; const active = vi.spyOn(TransitService.prototype, 'activeProvider').mockResolvedValue(primary); @@ -364,8 +355,8 @@ describe('MCP transit tools', () => { ); it('rejects an unknown itinerary provider before creating a journey', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); const day = await dayOf(trip.id, '2026-12-03'); await withHarness(user.id, ['reservations:write'], async (harness) => { const result = await harness.client.callTool({ @@ -385,10 +376,10 @@ describe('MCP transit tools', () => { }); it('rejects dateless, mismatched, and out-of-range journey dates', async () => { - const { user } = createUser(testDb); - const datelessTrip = createTrip(testDb, user.id); - const datelessDay = createDay(testDb, datelessTrip.id); - const datedTrip = createTrip(testDb, user.id, { start_date: '2026-12-02', end_date: '2026-12-03' }); + const { user } = await makeUser(orm); + const datelessTrip = await makeTrip(orm, user.id); + const datelessDay = await makeDay(orm, datelessTrip.id); + const datedTrip = await makeTrip(orm, user.id, { start_date: '2026-12-02', end_date: '2026-12-03' }); const datedDay = await dayOf(datedTrip.id, '2026-12-02'); await withHarness(user.id, ['reservations:write'], async (harness) => { const dateless = await harness.client.callTool({ @@ -425,8 +416,8 @@ describe('MCP transit tools', () => { }); it('rejects malformed provider data before persistence', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); const day = await dayOf(trip.id); const allWalk = { ...itinerary, legs: [itinerary.legs[0]] }; await withHarness(user.id, ['reservations:write'], async (harness) => { @@ -544,14 +535,14 @@ describe('MCP transit tools', () => { }); it('enforces demo, trip access, and reservation permissions', async () => { - const { user: owner } = createUser(testDb); - const { user: demo } = createUser(testDb, { email: 'demo@trek.app' }); - const { user: stranger } = createUser(testDb); - const { user: member } = createUser(testDb); - const trip = createTrip(testDb, owner.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); + const { user: owner } = await makeUser(orm); + const { user: demo } = await makeUser(orm, { email: 'demo@trek.app' }); + const { user: stranger } = await makeUser(orm); + const { user: member } = await makeUser(orm); + const trip = await makeTrip(orm, owner.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); const day = await dayOf(trip.id); - addTripMember(testDb, trip.id, demo.id); - addTripMember(testDb, trip.id, member.id); + await addTripMember(orm, trip.id, demo.id); + await addTripMember(orm, trip.id, member.id); process.env.DEMO_MODE = 'true'; await withHarness(demo.id, ['reservations:write'], async (harness) => { @@ -589,8 +580,8 @@ describe('MCP transit tools', () => { }); it('uses scheduled times when realtime stop times are unavailable', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); const day = await dayOf(trip.id); const scheduledOnly = { ...itinerary, @@ -619,8 +610,8 @@ describe('MCP transit tools', () => { // GTFS, for one, routes Trondheim → Ålesund over AIRPLANE legs. Those itineraries must survive // the search and be persistable, exactly as they are in the web app. it('accepts provider leg modes outside the requestable mode whitelist', async () => { - const { user } = createUser(testDb); - const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); const day = await dayOf(trip.id); const flying = { ...itinerary, @@ -651,7 +642,7 @@ describe('MCP transit tools', () => { }); it('reports how many provider itineraries failed validation', async () => { - const { user } = createUser(testDb); + const { user } = await makeUser(orm); const walkOnly = { ...itinerary, legs: [itinerary.legs[0]] }; planMock.mockResolvedValue({ itineraries: [itinerary, walkOnly], provider: 'transitous' });