Skip to content

armgit / TREK

Public Imported from GitHub
0

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

test(server): seed the plugin settings, tag, rating, day and receipt specs through the factories

Mauricea7fe990c6e03
diff --git a/server/tests/e2e/receipt-scan.e2e.test.ts b/server/tests/e2e/receipt-scan.e2e.test.ts
index f9ed94495..e5db16c7d 100644
--- a/server/tests/e2e/receipt-scan.e2e.test.ts
+++ b/server/tests/e2e/receipt-scan.e2e.test.ts
@@ -37,12 +37,18 @@ import { PermissionsService } from '../../src/nest/permissions/permissions.servi
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
-import { createTestMikroOrmModule } from '../helpers/test-orm';
+import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
+import { Addons } from '../../src/db/entities/Addons.entity';
+import { makeUser } from '../helpers/factories/users';
+import { makeTrip } from '../helpers/factories/trips';
+import { updateRows, upsertRow } from '../helpers/factories/rows';
-function setVision(vision: string) {
- db.prepare("UPDATE addons SET config = ? WHERE id = 'llm_parsing'").run(
- JSON.stringify({ provider: 'openai', model: 'gpt-4.1-mini', apiKey: '', vision }),
- );
+let orm: TestOrm;
+
+async function setVision(vision: string): Promise<void> {
+ await updateRows(orm, Addons, { id: 'llm_parsing' }, {
+ config: { provider: 'openai', model: 'gpt-4.1-mini', apiKey: '', vision },
+ });
}
/** The provider's chat-completions answer, carrying `payload` as its content. */
@@ -80,36 +86,29 @@ describe('Photos through AI Parsing e2e', () => {
}
beforeAll(async () => {
- db.prepare(
- "INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (1, 'e2e-user', '[email protected]', 'x', 'user', 0)",
- ).run();
- tripId = Number(db.prepare("INSERT INTO trips (user_id, title) VALUES (1, 'Lyon')").run().lastInsertRowid);
+ orm = await createTestOrm(db);
+ // Pinned id: sessionCookie(1) signs for exactly this user.
+ await makeUser(orm, { id: 1, username: 'e2e-user', email: '[email protected]' });
+ tripId = (await makeTrip(orm, 1, { title: 'Lyon' })).id;
// A trip user 1 is no member of: the real access lookup answers 404 for it.
- db.prepare(
- "INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (2, 'e2e-other', '[email protected]', 'x', 'user', 0)",
- ).run();
- foreignTripId = Number(db.prepare("INSERT INTO trips (user_id, title) VALUES (2, 'Elsewhere')").run().lastInsertRowid);
- db.prepare(
- `INSERT INTO addons (id, name, type, enabled, config) VALUES ('llm_parsing', 'AI Parsing', 'integration', 1, '{}')
- ON CONFLICT(id) DO UPDATE SET enabled = 1`,
- ).run();
- db.prepare(
- `INSERT INTO addons (id, name, type, enabled) VALUES ('budget', 'Costs', 'trip', 1)
- ON CONFLICT(id) DO UPDATE SET enabled = 1`,
- ).run();
+ await makeUser(orm, { id: 2, username: 'e2e-other', email: '[email protected]' });
+ foreignTripId = (await makeTrip(orm, 2, { title: 'Elsewhere' })).id;
+ await upsertRow(orm, Addons, { id: 'llm_parsing', name: 'AI Parsing', type: 'integration', enabled: true, config: {} }, ['enabled']);
+ await upsertRow(orm, Addons, { id: 'budget', name: 'Costs', type: 'trip', enabled: true }, ['enabled']);
photo = Buffer.from(await new Jimp({ width: 40, height: 60, color: 0xffffffff }).getBuffer('image/png'));
app = await build();
vi.spyOn(app.get(PermissionsService), 'checkPermission').mockResolvedValue(true);
server = app.getHttpServer();
});
- beforeEach(() => {
+ beforeEach(async () => {
safeFetchLlm.mockReset();
- setVision('on');
+ await setVision('on');
});
afterAll(async () => {
await app.close();
+ await orm.close();
});
describe('GET /api/llm/capabilities', () => {
@@ -119,7 +118,7 @@ describe('Photos through AI Parsing e2e', () => {
it('answers the instance setting, and no for a cloud model on Automatic', async () => {
expect((await request(server).get('/api/llm/capabilities').set('Cookie', sessionCookie(1))).body).toEqual({ images: true });
- setVision('auto');
+ await setVision('auto');
expect((await request(server).get('/api/llm/capabilities').set('Cookie', sessionCookie(1))).body).toEqual({ images: false });
expect(safeFetchLlm).not.toHaveBeenCalled();
});
@@ -145,7 +144,7 @@ describe('Photos through AI Parsing e2e', () => {
});
it('refuses a photo with 400 when the model reads no images', async () => {
- setVision('off');
+ await setVision('off');
const res = await upload();
expect(res.status).toBe(400);
expect(res.body.error).toBe('The configured AI model does not read photos');
@@ -186,19 +185,19 @@ describe('Photos through AI Parsing e2e', () => {
it('refuses a file that is not a photo, and any photo when the model reads no images', async () => {
expect((await scan('bill.pdf')).status).toBe(400);
- setVision('off');
+ await setVision('off');
expect((await scan()).status).toBe(400);
expect(safeFetchLlm).not.toHaveBeenCalled();
});
it('404 while Costs is off', async () => {
- db.prepare("UPDATE addons SET enabled = 0 WHERE id = 'budget'").run();
+ await updateRows(orm, Addons, { id: 'budget' }, { enabled: false });
try {
const res = await scan();
expect(res.status).toBe(404);
expect(res.body.error).toBe('Costs addon is not enabled');
} finally {
- db.prepare("UPDATE addons SET enabled = 1 WHERE id = 'budget'").run();
+ await updateRows(orm, Addons, { id: 'budget' }, { enabled: true });
}
});
});
diff --git a/server/tests/unit/db/repositories/Days.repository.test.ts b/server/tests/unit/db/repositories/Days.repository.test.ts
index a1e0bce63..2880d5eac 100644
--- a/server/tests/unit/db/repositories/Days.repository.test.ts
+++ b/server/tests/unit/db/repositories/Days.repository.test.ts
@@ -2,6 +2,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
+import { findRow, updateRows } from '../../../helpers/factories/rows';
import { createDay, createDayAccommodation, createDayAssignment, createDayNote, createPlace, createTrip, createUser } from '../../../helpers/factories';
import { Days } from '../../../../src/db/entities/Days.entity';
import type { DaysRepository } from '../../../../src/db/repositories/Days.repository';
@@ -17,7 +18,9 @@ beforeAll(async () => {
beforeEach(() => { resetTestDb(testDb); t.clear(); });
afterAll(async () => { await t.close(); testDb.close(); });
+/** The SELECT * row as the database holds it: the oracle the repository's rows are compared with key for key. */
function rawDay(id: number): unknown {
+ // test-sql-allow: the raw row is the oracle the ORM's rows are held against, key for key.
return testDb.prepare('SELECT * FROM days WHERE id = ?').get(id);
}
@@ -236,22 +239,22 @@ describe('DaysRepository.insertDayCopy (TP39)', () => {
const src = createTrip(testDb, user.id);
const dst = createTrip(testDb, user.id);
const srcDay = createDay(testDb, src.id, { date: '2026-03-01', title: 'Arrival' });
- testDb.prepare('UPDATE days SET notes = ? WHERE id = ?').run('Bring passport', srcDay.id);
+ await updateRows(t, Days, { id: srcDay.id }, { notes: 'Bring passport' });
const newId = await days.insertDayCopy({
trip_id: dst.id, day_number: srcDay.day_number, date: srcDay.date, notes: 'Bring passport', title: srcDay.title,
});
- const row = testDb.prepare('SELECT trip_id, day_number, date, notes, title FROM days WHERE id = ?').get(newId);
- expect(row).toEqual({ trip_id: dst.id, day_number: srcDay.day_number, date: '2026-03-01', notes: 'Bring passport', title: 'Arrival' });
+ const row = await findRow(t, Days, { id: newId });
+ expect(row).toMatchObject({ trip_id: dst.id, day_number: srcDay.day_number, date: '2026-03-01', notes: 'Bring passport', title: 'Arrival' });
});
it('DAYREPO-026: null date/notes/title are written as NULL, not coerced', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const newId = await days.insertDayCopy({ trip_id: trip.id, day_number: 1, date: null, notes: null, title: null });
- const row = testDb.prepare('SELECT date, notes, title FROM days WHERE id = ?').get(newId);
- expect(row).toEqual({ date: null, notes: null, title: null });
+ const row = await findRow(t, Days, { id: newId });
+ expect(row).toMatchObject({ date: null, notes: null, title: null });
});
});
@@ -264,6 +267,7 @@ describe('DaysRepository.listForPublicApi (Plan 4 Task 1, public-api.service.ts:
const day1 = createDay(testDb, trip.id, { day_number: 1, date: '2026-06-01' });
createDay(testDb, other.id, { day_number: 1 });
+ // test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb.prepare('SELECT id, day_number, date, title, notes FROM days WHERE trip_id = ? ORDER BY day_number ASC').all(trip.id);
const rows = await days.listForPublicApi(trip.id);
expect(rows).toEqual(legacy);
@@ -290,9 +294,10 @@ describe('DaysRepository.listPlanDays (RPL1, roadtrip-plan.service.ts::context)'
const other = createTrip(testDb, user.id);
const day2 = createDay(testDb, trip.id, { day_number: 2, date: '2026-06-02', title: 'Day 2' });
const day1 = createDay(testDb, trip.id, { day_number: 1, date: '2026-06-01', title: null });
- testDb.prepare('UPDATE days SET default_transport_mode = ? WHERE id = ?').run('walking', day2.id);
+ await updateRows(t, Days, { id: day2.id }, { default_transport_mode: 'walking' });
createDay(testDb, other.id, { day_number: 1 });
+ // test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb.prepare('SELECT id, day_number, date, title, default_transport_mode FROM days WHERE trip_id = ? ORDER BY day_number ASC').all(trip.id);
const rows = await days.listPlanDays(trip.id);
expect(rows).toEqual(legacy);
@@ -327,6 +332,7 @@ describe('DaysRepository.listForDayGrid (TP77, trips.service.ts::generateDays)',
createDayNote(testDb, withNote.id, trip.id);
createDayAccommodation(testDb, trip.id, place.id, withStay.id, withStay.id);
+ // test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb.prepare(`
SELECT d.id, d.day_number, d.date,
EXISTS (SELECT 1 FROM day_assignments da WHERE da.day_id = d.id)
@@ -363,6 +369,7 @@ describe('DaysRepository.listDayGridStays (TP78, trips.service.ts::generateDays)
// `end_day_id IN` half alone, so that half cannot be dropped unnoticed.
createDayAccommodation(testDb, other.id, otherPlace.id, foreign.id, d1.id);
+ // test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb.prepare(`
SELECT dac.start_day_id, dac.end_day_id FROM day_accommodations dac
WHERE dac.start_day_id IN (SELECT id FROM days WHERE trip_id = ?)
diff --git a/server/tests/unit/db/repositories/PlaceRatings.repository.test.ts b/server/tests/unit/db/repositories/PlaceRatings.repository.test.ts
index 2e03f0717..9a88f7935 100644
--- a/server/tests/unit/db/repositories/PlaceRatings.repository.test.ts
+++ b/server/tests/unit/db/repositories/PlaceRatings.repository.test.ts
@@ -8,6 +8,9 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
+import { countRows, findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
+import { Places } from '../../../../src/db/entities/Places.entity';
+import { dbNow } from '../../../../src/db/types/db-timestamp.type';
import { createPlace, createTrip, createUser } from '../../../helpers/factories';
import { PlaceRatings } from '../../../../src/db/entities/PlaceRatings.entity';
import type { PlaceRatingsRepository } from '../../../../src/db/repositories/PlaceRatings.repository';
@@ -23,8 +26,8 @@ beforeAll(async () => {
beforeEach(() => { resetTestDb(testDb); t.clear(); });
afterAll(async () => { await t.close(); testDb.close(); });
-function rate(placeId: number, userId: number, rating: number, createdAt: string): void {
- testDb.prepare('INSERT INTO place_ratings (place_id, user_id, rating, created_at) VALUES (?, ?, ?, ?)').run(placeId, userId, rating, createdAt);
+async function rate(placeId: number, userId: number, rating: number, createdAt: string): Promise<void> {
+ await insertRow(t, PlaceRatings, { place: placeId, user: userId, rating, created_at: createdAt });
}
async function withQueryCount<T>(fn: () => Promise<T>): Promise<{ value: T; queries: number }> {
@@ -51,8 +54,8 @@ describe('PlaceRatingsRepository.listForPlaces', () => {
const { user: voterB } = createUser(testDb, { username: 'beta' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
- rate(place.id, voterA.id, 4, '2026-01-01 00:00:00');
- rate(place.id, voterB.id, 2, '2026-01-02 00:00:00');
+ await rate(place.id, voterA.id, 4, '2026-01-01 00:00:00');
+ await rate(place.id, voterB.id, 2, '2026-01-02 00:00:00');
const rows = await placeRatings.listForPlaces([place.id]);
expect(rows).toEqual([
@@ -67,8 +70,8 @@ describe('PlaceRatingsRepository.listForPlaces', () => {
const trip = createTrip(testDb, owner.id);
const placeA = createPlace(testDb, trip.id, { name: 'A' });
const placeB = createPlace(testDb, trip.id, { name: 'B' });
- rate(placeA.id, voter.id, 5, '2026-01-01 00:00:00');
- rate(placeB.id, voter.id, 1, '2026-01-01 00:00:00');
+ await rate(placeA.id, voter.id, 5, '2026-01-01 00:00:00');
+ await rate(placeB.id, voter.id, 1, '2026-01-01 00:00:00');
const rows = await placeRatings.listForPlaces([placeA.id, placeB.id]);
expect(rows.map((r) => r.place_id).sort()).toEqual([placeA.id, placeB.id].sort());
@@ -93,12 +96,12 @@ describe('PlaceRatingsRepository.listForPlaces', () => {
const { user: voter } = createUser(testDb, { username: 'fresh-voter' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
- rate(place.id, seedVoter.id, 1, '2026-01-01 00:00:00');
+ await rate(place.id, seedVoter.id, 1, '2026-01-01 00:00:00');
// rule 20: the FIRST, wider setup read passes `disableIdentityMap: false`
// explicitly and carries the column the later write targets (`rating`) —
// `find({})` with the base default merged in populates nothing.
await t.repo(PlaceRatings).find({}, { disableIdentityMap: false });
- rate(place.id, voter.id, 3, '2026-01-02 00:00:00');
+ await rate(place.id, voter.id, 3, '2026-01-02 00:00:00');
const rows = await placeRatings.listForPlaces([place.id]);
expect(rows).toEqual([
{ place_id: place.id, user_id: seedVoter.id, username: 'seed-voter', avatar: null, rating: 1 },
@@ -119,15 +122,14 @@ describe('PlaceRatingsRepository.upsertRating (PL51)', () => {
const place = createPlace(testDb, trip.id);
await placeRatings.upsertRating(place.id, voter.id, 5);
- let rows = testDb.prepare('SELECT rating FROM place_ratings WHERE place_id = ? AND user_id = ?').all(place.id, voter.id) as { rating: number }[];
+ let rows = (await findRows(t, PlaceRatings, { place: place.id, user: voter.id })).map((r) => ({ rating: r.rating }));
expect(rows).toEqual([{ rating: 5 }]);
await placeRatings.upsertRating(place.id, voter.id, 2);
- rows = testDb.prepare('SELECT rating FROM place_ratings WHERE place_id = ? AND user_id = ?').all(place.id, voter.id) as { rating: number }[];
+ rows = (await findRows(t, PlaceRatings, { place: place.id, user: voter.id })).map((r) => ({ rating: r.rating }));
expect(rows).toEqual([{ rating: 2 }]);
// Exactly one row for the (place, user) pair — the composite unique key held, not a duplicate insert.
- const count = testDb.prepare('SELECT COUNT(*) AS n FROM place_ratings WHERE place_id = ? AND user_id = ?').get(place.id, voter.id) as { n: number };
- expect(count.n).toBe(1);
+ expect(await countRows(t, PlaceRatings, { place: place.id, user: voter.id })).toBe(1);
});
it('UPSERTRATINGREPO-002 (PL51 ruling): a re-vote never touches places.updated_at — a vote must not 409 another member\'s If-Match', async () => {
@@ -135,13 +137,13 @@ describe('PlaceRatingsRepository.upsertRating (PL51)', () => {
const { user: voter } = createUser(testDb, { username: 'voter2' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
- testDb.prepare("UPDATE places SET updated_at = datetime('now', '-1 hour') WHERE id = ?").run(place.id);
- const before = (testDb.prepare('SELECT updated_at FROM places WHERE id = ?').get(place.id) as { updated_at: string }).updated_at;
+ await updateRows(t, Places, { id: place.id }, { updated_at: dbNow(new Date(Date.now() - 60 * 60 * 1000)) });
+ const before = (await findRow(t, Places, { id: place.id }))?.updated_at;
await placeRatings.upsertRating(place.id, voter.id, 4);
await placeRatings.upsertRating(place.id, voter.id, 1); // the conflict path
- const after = (testDb.prepare('SELECT updated_at FROM places WHERE id = ?').get(place.id) as { updated_at: string }).updated_at;
+ const after = (await findRow(t, Places, { id: place.id }))?.updated_at;
expect(after).toBe(before);
});
@@ -153,7 +155,7 @@ describe('PlaceRatingsRepository.upsertRating (PL51)', () => {
const place = createPlace(testDb, trip.id);
await placeRatings.upsertRating(place.id, voterA.id, 5);
await placeRatings.upsertRating(place.id, voterB.id, 1);
- const rows = testDb.prepare('SELECT user_id, rating FROM place_ratings WHERE place_id = ? ORDER BY user_id').all(place.id);
+ const rows = (await findRows(t, PlaceRatings, { place: place.id }, { user: 'asc' })).map((r) => ({ user_id: r.user_id, rating: r.rating }));
expect(rows).toEqual([
{ user_id: Math.min(voterA.id, voterB.id), rating: voterA.id < voterB.id ? 5 : 1 },
{ user_id: Math.max(voterA.id, voterB.id), rating: voterA.id < voterB.id ? 1 : 5 },
@@ -171,7 +173,7 @@ describe('PlaceRatingsRepository.deleteRating (PL50)', () => {
await placeRatings.upsertRating(place.id, voterA.id, 5);
await placeRatings.upsertRating(place.id, voterB.id, 3);
await placeRatings.deleteRating(place.id, voterA.id);
- expect(testDb.prepare('SELECT user_id FROM place_ratings WHERE place_id = ?').all(place.id)).toEqual([{ user_id: voterB.id }]);
+ expect((await findRows(t, PlaceRatings, { place: place.id })).map((r) => ({ user_id: r.user_id }))).toEqual([{ user_id: voterB.id }]);
});
it('DELETERATINGREPO-002: deleting a vote that does not exist is a no-op, not a throw', async () => {
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 91f491ed7..1e76cdbeb 100644
--- a/server/tests/unit/mcp/tools-tags-maps-weather.test.ts
+++ b/server/tests/unit/mcp/tools-tags-maps-weather.test.ts
@@ -45,6 +45,10 @@ vi.mock('../../../src/nest/maps/trek-places.client', async (importOriginal) => (
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
+import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
+import { findRow } from '../../helpers/factories/rows';
+import { makeTag } from '../../helpers/factories/places';
+import { Tags } from '../../../src/db/entities/Tags.entity';
import { MapsService } from '../../../src/nest/maps/maps.service';
import { getWeather, getDetailedWeather } from '../../../src/nest/weather/weather.impl';
@@ -84,7 +88,14 @@ beforeEach(() => {
delete process.env.DEMO_MODE;
});
-afterAll(() => {
+let orm: TestOrm;
+
+beforeAll(async () => {
+ orm = await createTestOrm(testDb);
+});
+
+afterAll(async () => {
+ await orm.close();
testDb.close();
});
@@ -110,8 +121,8 @@ describe('Tool: list_tags', () => {
it('returns only tags belonging to the current user', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
- testDb.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(user.id, 'My Tag', '#ff0000');
- testDb.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(other.id, 'Other Tag', '#00ff00');
+ 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) => {
const result = await h.client.callTool({ name: 'list_tags', arguments: {} });
const data = parseToolResult(result) as any;
@@ -173,8 +184,7 @@ describe('Tool: create_tag', () => {
describe('Tool: update_tag', () => {
it('updates tag name and color', async () => {
const { user } = createUser(testDb);
- const r = testDb.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(user.id, 'Old Name', '#aaaaaa');
- const tagId = r.lastInsertRowid as number;
+ 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({
name: 'update_tag',
@@ -201,15 +211,14 @@ describe('Tool: update_tag', () => {
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: '[email protected]' });
- const r = testDb.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(user.id, 'Demo Tag', '#aaaaaa');
- const tagId = r.lastInsertRowid as number;
+ 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({
name: 'update_tag',
arguments: { tagId, name: 'Blocked' },
});
expect(result.isError).toBe(true);
- expect(testDb.prepare('SELECT name FROM tags WHERE id = ?').get(tagId)).toEqual({ name: 'Demo Tag' });
+ expect((await findRow(orm, Tags, { id: tagId }))?.name).toBe('Demo Tag');
});
});
});
@@ -221,8 +230,7 @@ describe('Tool: update_tag', () => {
describe('Tool: delete_tag', () => {
it('removes the tag row', async () => {
const { user } = createUser(testDb);
- const r = testDb.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(user.id, 'To Delete', '#cccccc');
- const tagId = r.lastInsertRowid as number;
+ 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({
name: 'delete_tag',
@@ -230,7 +238,7 @@ describe('Tool: delete_tag', () => {
});
const data = parseToolResult(result) as any;
expect(data.success).toBe(true);
- expect(testDb.prepare('SELECT id FROM tags WHERE id = ?').get(tagId)).toBeUndefined();
+ expect(await findRow(orm, Tags, { id: tagId })).toBeNull();
});
});
@@ -248,15 +256,14 @@ describe('Tool: delete_tag', () => {
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: '[email protected]' });
- const r = testDb.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(user.id, 'Demo Tag', '#aaaaaa');
- const tagId = r.lastInsertRowid as number;
+ 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({
name: 'delete_tag',
arguments: { tagId },
});
expect(result.isError).toBe(true);
- expect(testDb.prepare('SELECT id FROM tags WHERE id = ?').get(tagId)).toBeDefined();
+ expect(await findRow(orm, Tags, { id: tagId })).not.toBeNull();
});
});
});
diff --git a/server/tests/unit/plugins/settings-isolation.test.ts b/server/tests/unit/plugins/settings-isolation.test.ts
index 7d5d4a3f6..0eb9918c0 100644
--- a/server/tests/unit/plugins/settings-isolation.test.ts
+++ b/server/tests/unit/plugins/settings-isolation.test.ts
@@ -26,6 +26,9 @@ import { createUser } from '../../helpers/factories';
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
import { parseManifest, ManifestError } from '../../../src/nest/plugins/install/manifest';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
+import { deleteRows, insertRow, upsertRow } from '../../helpers/factories/rows';
+import { makePluginSettingsField, setPluginUserConfig } from '../../helpers/factories/plugins';
+import { readUserSetting } from '../../helpers/factories/settings';
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
import { Users } from '../../../src/db/entities/Users.entity';
import { Plugins } from '../../../src/db/entities/Plugins.entity';
@@ -60,14 +63,15 @@ afterAll(async () => {
await t?.close();
});
-function declareField(pluginId: string, key: string, opts: { required?: boolean; secret?: boolean } = {}) {
- testDb.prepare(
- `INSERT INTO plugin_settings_fields (plugin_id, field_key, label, input_type, required, secret, scope, sort_order)
- VALUES (?, ?, ?, 'text', ?, ?, 'user', 0)`,
- ).run(pluginId, key, key, opts.required ? 1 : 0, opts.secret ? 1 : 0);
+const orm = () => t as TestOrm;
+
+async function declareField(pluginId: string, key: string, opts: { required?: boolean; secret?: boolean } = {}) {
+ await makePluginSettingsField(orm(), pluginId, key, {
+ label: key, input_type: 'text', required: opts.required ? 1 : 0, secret: opts.secret ? 1 : 0, scope: 'user', sort_order: 0,
+ });
}
-function setUserConfig(pluginId: string, config: Record<string, unknown>) {
- testDb.prepare('INSERT OR REPLACE INTO plugin_user_config (plugin_id, user_id, config) VALUES (?, ?, ?)').run(pluginId, uid, JSON.stringify(config));
+async function setUserConfig(pluginId: string, config: Record<string, unknown>) {
+ await setPluginUserConfig(orm(), pluginId, uid, config);
}
beforeAll(async () => {
@@ -76,31 +80,30 @@ beforeAll(async () => {
// test runs (PSET-001..006 call `userSettings()` with no ORM of their own).
t = await createTestOrm(testDb);
});
-beforeEach(() => {
- testDb.prepare('DELETE FROM plugin_settings_fields').run();
- testDb.prepare('DELETE FROM plugin_user_config').run();
- testDb.prepare('DELETE FROM settings').run();
- testDb.prepare('DELETE FROM users').run();
+beforeEach(async () => {
+ await deleteRows(orm(), PluginSettingsFields);
+ await deleteRows(orm(), PluginUserConfig);
+ await deleteRows(orm(), Settings);
+ await deleteRows(orm(), Users);
uid = createUser(testDb).user.id;
});
describe('plugin settings are isolated from core and from each other', () => {
it('PSET-001 — a plugin declaring "webhook_url" cannot touch the CORE settings row', async () => {
- testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'webhook_url', 'https://core.example.com/real')").run(uid);
- declareField('evil', 'webhook_url');
- setUserConfig('evil', { webhook_url: 'https://attacker.example.com' });
+ await insertRow(orm(), Settings, { user: uid, key: 'webhook_url', value: 'https://core.example.com/real' });
+ await declareField('evil', 'webhook_url');
+ await setUserConfig('evil', { webhook_url: 'https://attacker.example.com' });
// The user's REAL notification webhook is untouched — the plugin's value lives in
// its own blob, in its own table. The namespacing is structural, not by key naming.
- const core = testDb.prepare("SELECT value FROM settings WHERE user_id = ? AND key = 'webhook_url'").get(uid) as { value: string };
- expect(core.value).toBe('https://core.example.com/real');
+ expect(await readUserSetting(orm(), uid, 'webhook_url')).toBe('https://core.example.com/real');
expect(await userSettings().readAll('evil', uid)).toEqual({ webhook_url: 'https://attacker.example.com' });
});
it('PSET-002 — plugin A cannot read plugin B’s config, even with the same key name', async () => {
- declareField('a', 'token', { secret: true });
- declareField('b', 'token', { secret: true });
- setUserConfig('b', { token: 'B-SECRET' });
+ await declareField('a', 'token', { secret: true });
+ await declareField('b', 'token', { secret: true });
+ await setUserConfig('b', { token: 'B-SECRET' });
expect(await userSettings().readAll('a', uid)).toEqual({});
expect(await userSettings().readOne('a', uid, 'token')).toBeUndefined();
@@ -108,9 +111,9 @@ describe('plugin settings are isolated from core and from each other', () => {
});
it('PSET-003 — a plugin only ever sees its own DECLARED keys', async () => {
- declareField('p', 'declared');
+ await declareField('p', 'declared');
// An undeclared key that somehow reached the blob is not handed to the plugin.
- setUserConfig('p', { declared: 'yes', sneaked: 'no' });
+ await setUserConfig('p', { declared: 'yes', sneaked: 'no' });
expect(await userSettings().readAll('p', uid)).toEqual({ declared: 'yes' });
});
});
@@ -119,7 +122,7 @@ describe('settings keys cannot resolve off the prototype chain', () => {
it.each(['__proto__', 'constructor', 'prototype'])(
'PSET-004 — a REQUIRED field named "%s" is NOT reported as configured',
async (key) => {
- declareField('evil', key, { required: true });
+ await declareField('evil', key, { required: true });
// The user has configured nothing at all.
expect(await userSettings().hasRequired('evil', uid)).toBe(false);
expect(await userSettings().readAll('evil', uid)).toEqual({});
@@ -127,9 +130,9 @@ describe('settings keys cannot resolve off the prototype chain', () => {
);
it('PSET-005 — a genuinely configured required field still reports configured', async () => {
- declareField('good', 'appToken', { required: true, secret: true });
+ await declareField('good', 'appToken', { required: true, secret: true });
expect(await userSettings().hasRequired('good', uid)).toBe(false);
- setUserConfig('good', { appToken: 'T' });
+ await setUserConfig('good', { appToken: 'T' });
expect(await userSettings().hasRequired('good', uid)).toBe(true);
});
@@ -153,10 +156,10 @@ describe('a plugin channel label is bounded by the host', () => {
const { PluginRuntimeService } = await import('../../../src/nest/plugins/plugin-runtime.service');
process.env.TREK_PLUGINS_ENABLED = 'true';
- testDb.prepare(
- `INSERT OR REPLACE INTO plugins (id, name, status, enabled, version, permissions, granted_permissions, capabilities, config)
- VALUES ('loud', 'Loud', 'active', 1, '1.0.0', '[]', '[]', ?, '{}')`,
- ).run(JSON.stringify({ notificationChannel: { title: '🎉'.repeat(5) + 'A'.repeat(500) } }));
+ await upsertRow(orm(), Plugins, {
+ id: 'loud', name: 'Loud', status: 'active', enabled: 1, version: '1.0.0', permissions: '[]', granted_permissions: '[]',
+ capabilities: JSON.stringify({ notificationChannel: { title: '🎉'.repeat(5) + 'A'.repeat(500) } }), config: '{}',
+ });
const rt = new PluginRuntimeService(
new AuditService(t.repo(AuditLog), t.repo(Users)),