mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
chore: move category backend to proper DI
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* Unit tests for MCP resources (resources.ts).
|
||||
* Tests all 14 resources via InMemoryTransport + Client.
|
||||
* Tests all 13 legacy-registrar resources via InMemoryTransport + Client
|
||||
* (trek://categories moved to the DI-discovered CategoriesMcp — see
|
||||
* tools-categories.test.ts).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
|
||||
|
||||
@@ -416,21 +418,9 @@ describe('Resource: trek://trips/{tripId}/collab-notes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Resource: trek://categories', () => {
|
||||
it('returns all categories', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
await withHarness(user.id, async (harness) => {
|
||||
const result = await harness.client.readResource({ uri: 'trek://categories' });
|
||||
const categories = parseResourceResult(result) as any[];
|
||||
expect(categories.length).toBeGreaterThan(0);
|
||||
expect(categories[0]).toHaveProperty('id');
|
||||
expect(categories[0]).toHaveProperty('name');
|
||||
expect(categories[0]).toHaveProperty('color');
|
||||
expect(categories[0]).toHaveProperty('icon');
|
||||
});
|
||||
});
|
||||
});
|
||||
// trek://categories moved to tools-categories.test.ts: it now registers via
|
||||
// the nest-mcp registry inside registerTools (CategoriesMcp @Resource), which
|
||||
// this file's withTools: false harness never attaches.
|
||||
|
||||
describe('Resource: trek://bucket-list', () => {
|
||||
it('returns only the current user\'s bucket list items', async () => {
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Unit tests for the categories MCP surface (CategoriesMcp, DI-discovered):
|
||||
* the list_categories tool and the trek://categories resource.
|
||||
*
|
||||
* Both attach via the nest-mcp registry inside registerTools, so every harness
|
||||
* here keeps withTools on (the resource is NOT registered by the legacy
|
||||
* registerResources fan-out anymore).
|
||||
*/
|
||||
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');
|
||||
const mock = {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: () => null,
|
||||
isOwner: () => false,
|
||||
};
|
||||
return { testDb: db, dbMock: mock };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
vi.mock('../../../src/config', () => ({
|
||||
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
}));
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser } from '../../helpers/factories';
|
||||
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
async function withHarness(
|
||||
userId: number,
|
||||
fn: (h: McpHarness) => Promise<void>,
|
||||
scopes: string[] | null = null,
|
||||
) {
|
||||
const h = await createMcpHarness({ userId, withResources: false, scopes });
|
||||
try { await fn(h); } finally { await h.cleanup(); }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// list_categories
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: list_categories', () => {
|
||||
it('returns all categories with id, name, color, icon', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({ name: 'list_categories', arguments: {} });
|
||||
const data = parseToolResult(result) as any;
|
||||
expect(data.categories).toBeDefined();
|
||||
expect(data.categories.length).toBeGreaterThan(0);
|
||||
const cat = data.categories[0];
|
||||
expect(cat).toHaveProperty('id');
|
||||
expect(cat).toHaveProperty('name');
|
||||
expect(cat).toHaveProperty('color');
|
||||
expect(cat).toHaveProperty('icon');
|
||||
});
|
||||
});
|
||||
|
||||
it('returns categories from all users, ordered by name', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
testDb.prepare('INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)').run('Zzz Mine', '#111111', '🅰️', user.id);
|
||||
testDb.prepare('INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)').run('Zzz Other', '#222222', '🅱️', other.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({ name: 'list_categories', arguments: {} });
|
||||
const names = (parseToolResult(result) as any).categories.map((c: { name: string }) => c.name);
|
||||
expect(names).toContain('Zzz Mine');
|
||||
expect(names).toContain('Zzz Other');
|
||||
expect(names).toEqual([...names].sort());
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// list_categories scope gating (places:read, registration-time)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: list_categories — scope gating', () => {
|
||||
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
|
||||
const h = await createMcpHarness({ userId, withResources: false, scopes });
|
||||
try {
|
||||
return (await h.client.listTools()).tools.map((t) => t.name);
|
||||
} finally {
|
||||
await h.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
it('registers with null scopes (full access)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
expect(await listToolNames(user.id, null)).toContain('list_categories');
|
||||
});
|
||||
|
||||
it('registers with places:read', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
expect(await listToolNames(user.id, ['places:read'])).toContain('list_categories');
|
||||
});
|
||||
|
||||
it('does not register for an unrelated scope', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
expect(await listToolNames(user.id, ['budget:read'])).not.toContain('list_categories');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// trek://categories resource (first production @Resource)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Resource: trek://categories', () => {
|
||||
it('returns all categories', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.readResource({ uri: 'trek://categories' });
|
||||
const categories = parseResourceResult(result) as any[];
|
||||
expect(categories.length).toBeGreaterThan(0);
|
||||
expect(categories[0]).toHaveProperty('id');
|
||||
expect(categories[0]).toHaveProperty('name');
|
||||
expect(categories[0]).toHaveProperty('color');
|
||||
expect(categories[0]).toHaveProperty('icon');
|
||||
});
|
||||
});
|
||||
|
||||
it('stays readable under restricted non-places scopes (legacy ungated behavior)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.readResource({ uri: 'trek://categories' });
|
||||
const categories = parseResourceResult(result) as any[];
|
||||
expect(Array.isArray(categories)).toBe(true);
|
||||
expect(categories.length).toBeGreaterThan(0);
|
||||
}, ['trips:read']);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* Unit tests for MCP place tools: create_place, update_place, delete_place, list_categories, search_place.
|
||||
* Unit tests for MCP place tools: create_place, update_place, delete_place, search_place.
|
||||
* (list_categories moved to tools-categories.test.ts with the CategoriesMcp migration.)
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
@@ -356,27 +357,6 @@ describe('Tool: create_and_assign_place', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// list_categories
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: list_categories', () => {
|
||||
it('returns all categories with id, name, color, icon', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({ name: 'list_categories', arguments: {} });
|
||||
const data = parseToolResult(result) as any;
|
||||
expect(data.categories).toBeDefined();
|
||||
expect(data.categories.length).toBeGreaterThan(0);
|
||||
const cat = data.categories[0];
|
||||
expect(cat).toHaveProperty('id');
|
||||
expect(cat).toHaveProperty('name');
|
||||
expect(cat).toHaveProperty('color');
|
||||
expect(cat).toHaveProperty('icon');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// search_place
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
+60
-47
@@ -1,6 +1,9 @@
|
||||
/**
|
||||
* Unit tests for categoryService — CAT-SVC-001 through CAT-SVC-015.
|
||||
* Unit tests for CategoriesService — CAT-SVC-001 through CAT-SVC-016.
|
||||
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
|
||||
* The service is constructed directly (new CategoriesService(new DatabaseService(db)))
|
||||
* — no Nest container needed. CAT-SVC-016 covers the categories.bridge export
|
||||
* used by the non-Nest plugin RPC host.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
@@ -34,13 +37,11 @@ import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser } from '../../helpers/factories';
|
||||
import {
|
||||
listCategories,
|
||||
createCategory,
|
||||
getCategoryById,
|
||||
updateCategory,
|
||||
deleteCategory,
|
||||
} from '../../../src/services/categoryService';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { CategoriesService } from '../../../src/nest/categories/categories.service';
|
||||
import { listCategories } from '../../../src/nest/categories/categories.bridge';
|
||||
|
||||
const svc = new CategoriesService(new DatabaseService(testDb));
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
@@ -55,22 +56,22 @@ afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
// ── listCategories ────────────────────────────────────────────────────────────
|
||||
// ── list ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('listCategories', () => {
|
||||
describe('list', () => {
|
||||
it('CAT-SVC-001 — returns an array (seeded defaults are present after migrations)', () => {
|
||||
// Migrations seed default categories, so the list is never empty in a fully initialized DB
|
||||
const cats = listCategories() as any[];
|
||||
const cats = svc.list();
|
||||
expect(Array.isArray(cats)).toBe(true);
|
||||
expect(cats.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('CAT-SVC-002 — results are ordered by name ascending (custom categories sort correctly)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
createCategory(user.id, 'Zoo');
|
||||
createCategory(user.id, 'Aquarium');
|
||||
svc.create(user.id, 'Zoo');
|
||||
svc.create(user.id, 'Aquarium');
|
||||
// Migrations seed default categories; verify ordering by checking our custom ones appear in sorted order
|
||||
const names = (listCategories() as any[]).map((c: any) => c.name);
|
||||
const names = svc.list().map((c) => c.name);
|
||||
const aquariumIdx = names.indexOf('Aquarium');
|
||||
const zooIdx = names.indexOf('Zoo');
|
||||
expect(aquariumIdx).toBeGreaterThanOrEqual(0);
|
||||
@@ -81,19 +82,19 @@ describe('listCategories', () => {
|
||||
it('CAT-SVC-003 — returns categories from all users (including seeded defaults)', () => {
|
||||
const { user: a } = createUser(testDb);
|
||||
const { user: b } = createUser(testDb);
|
||||
const before = (listCategories() as any[]).length;
|
||||
createCategory(a.id, 'Cat-A');
|
||||
createCategory(b.id, 'Cat-B');
|
||||
expect(listCategories()).toHaveLength(before + 2);
|
||||
const before = svc.list().length;
|
||||
svc.create(a.id, 'Cat-A');
|
||||
svc.create(b.id, 'Cat-B');
|
||||
expect(svc.list()).toHaveLength(before + 2);
|
||||
});
|
||||
});
|
||||
|
||||
// ── createCategory ────────────────────────────────────────────────────────────
|
||||
// ── create ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('createCategory', () => {
|
||||
describe('create', () => {
|
||||
it('CAT-SVC-004 — creates a category with name, color, and icon', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cat = createCategory(user.id, 'Restaurant', '#ff5500', '🍽️') as any;
|
||||
const cat = svc.create(user.id, 'Restaurant', '#ff5500', '🍽️');
|
||||
expect(cat.name).toBe('Restaurant');
|
||||
expect(cat.color).toBe('#ff5500');
|
||||
expect(cat.icon).toBe('🍽️');
|
||||
@@ -102,55 +103,55 @@ describe('createCategory', () => {
|
||||
|
||||
it('CAT-SVC-005 — defaults color to #6366f1 when not provided', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cat = createCategory(user.id, 'Default Color') as any;
|
||||
const cat = svc.create(user.id, 'Default Color');
|
||||
expect(cat.color).toBe('#6366f1');
|
||||
});
|
||||
|
||||
it('CAT-SVC-006 — defaults icon to 📍 when not provided', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cat = createCategory(user.id, 'Default Icon') as any;
|
||||
const cat = svc.create(user.id, 'Default Icon');
|
||||
expect(cat.icon).toBe('📍');
|
||||
});
|
||||
|
||||
it('CAT-SVC-007 — returns the inserted row with an id', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cat = createCategory(user.id, 'WithId') as any;
|
||||
const cat = svc.create(user.id, 'WithId');
|
||||
expect(typeof cat.id).toBe('number');
|
||||
expect(cat.id).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ── getCategoryById ───────────────────────────────────────────────────────────
|
||||
// ── getById ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('getCategoryById', () => {
|
||||
describe('getById', () => {
|
||||
it('CAT-SVC-008 — returns category for a valid id', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = createCategory(user.id, 'Find Me') as any;
|
||||
const found = getCategoryById(created.id) as any;
|
||||
const created = svc.create(user.id, 'Find Me');
|
||||
const found = svc.getById(created.id);
|
||||
expect(found).toBeDefined();
|
||||
expect(found.name).toBe('Find Me');
|
||||
expect(found?.name).toBe('Find Me');
|
||||
});
|
||||
|
||||
it('CAT-SVC-009 — returns undefined for non-existent id', () => {
|
||||
expect(getCategoryById(99999)).toBeUndefined();
|
||||
expect(svc.getById(99999)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('CAT-SVC-010 — accepts string id (coerced by SQLite)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = createCategory(user.id, 'StringId') as any;
|
||||
const found = getCategoryById(String(created.id)) as any;
|
||||
const created = svc.create(user.id, 'StringId');
|
||||
const found = svc.getById(String(created.id));
|
||||
expect(found).toBeDefined();
|
||||
expect(found.id).toBe(created.id);
|
||||
expect(found?.id).toBe(created.id);
|
||||
});
|
||||
});
|
||||
|
||||
// ── updateCategory ────────────────────────────────────────────────────────────
|
||||
// ── update ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('updateCategory', () => {
|
||||
describe('update', () => {
|
||||
it('CAT-SVC-011 — updates name, color, and icon', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cat = createCategory(user.id, 'Old', '#aaaaaa', '❓') as any;
|
||||
const updated = updateCategory(cat.id, 'New', '#bbbbbb', '✅') as any;
|
||||
const cat = svc.create(user.id, 'Old', '#aaaaaa', '❓');
|
||||
const updated = svc.update(cat.id, 'New', '#bbbbbb', '✅');
|
||||
expect(updated.name).toBe('New');
|
||||
expect(updated.color).toBe('#bbbbbb');
|
||||
expect(updated.icon).toBe('✅');
|
||||
@@ -158,32 +159,44 @@ describe('updateCategory', () => {
|
||||
|
||||
it('CAT-SVC-012 — COALESCE: omitting name preserves existing name', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cat = createCategory(user.id, 'KeepName', '#aaaaaa', '⭐') as any;
|
||||
const updated = updateCategory(cat.id, undefined, '#cccccc', '🔥') as any;
|
||||
const cat = svc.create(user.id, 'KeepName', '#aaaaaa', '⭐');
|
||||
const updated = svc.update(cat.id, undefined, '#cccccc', '🔥');
|
||||
expect(updated.name).toBe('KeepName');
|
||||
expect(updated.color).toBe('#cccccc');
|
||||
});
|
||||
|
||||
it('CAT-SVC-013 — COALESCE: omitting color preserves existing color', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cat = createCategory(user.id, 'KeepColor', '#dddddd', '⭐') as any;
|
||||
const updated = updateCategory(cat.id, 'NewName', undefined, '🌟') as any;
|
||||
const cat = svc.create(user.id, 'KeepColor', '#dddddd', '⭐');
|
||||
const updated = svc.update(cat.id, 'NewName', undefined, '🌟');
|
||||
expect(updated.name).toBe('NewName');
|
||||
expect(updated.color).toBe('#dddddd');
|
||||
});
|
||||
});
|
||||
|
||||
// ── deleteCategory ────────────────────────────────────────────────────────────
|
||||
// ── remove ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('deleteCategory', () => {
|
||||
describe('remove', () => {
|
||||
it('CAT-SVC-014 — deletes the category from the database', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cat = createCategory(user.id, 'ToDelete') as any;
|
||||
deleteCategory(cat.id);
|
||||
expect(getCategoryById(cat.id)).toBeUndefined();
|
||||
const cat = svc.create(user.id, 'ToDelete');
|
||||
svc.remove(cat.id);
|
||||
expect(svc.getById(cat.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('CAT-SVC-015 — deleting a non-existent category does not throw', () => {
|
||||
expect(() => deleteCategory(99999)).not.toThrow();
|
||||
expect(() => svc.remove(99999)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ── categories.bridge (non-Nest entry point) ──────────────────────────────────
|
||||
|
||||
describe('categories.bridge', () => {
|
||||
it('CAT-SVC-016 — listCategories delegates to the service', () => {
|
||||
const { user } = createUser(testDb);
|
||||
svc.create(user.id, 'Bridged');
|
||||
const names = listCategories().map((c) => c.name);
|
||||
expect(names).toContain('Bridged');
|
||||
expect(names).toEqual([...names].sort());
|
||||
});
|
||||
});
|
||||
@@ -136,7 +136,7 @@ vi.mock('../../../src/services/packingService', () => ({
|
||||
}));
|
||||
vi.mock('../../../src/services/conflictResult', () => ({ isUpdateConflict: (r: unknown) => !!(r as { conflict?: boolean })?.conflict }));
|
||||
vi.mock('../../../src/services/weatherService', () => ({ getWeather: vi.fn(async (lat: string, lng: string) => ({ lat, lng, temp: 20 })) }));
|
||||
vi.mock('../../../src/services/categoryService', () => ({ listCategories: vi.fn(() => [{ id: 1, name: 'Food' }]) }));
|
||||
vi.mock('../../../src/nest/categories/categories.bridge', () => ({ listCategories: vi.fn(() => [{ id: 1, name: 'Food' }]) }));
|
||||
vi.mock('../../../src/nest/tags/tags.bridge', () => ({
|
||||
listTags: vi.fn((uid: number) => [{ id: 1, user_id: uid, name: 'work' }]),
|
||||
createTag: vi.fn((uid: number, name: string, color?: string) => ({ id: 9, user_id: uid, name, color })),
|
||||
|
||||
Reference in New Issue
Block a user