fix(16): add async/await to createTestDb in route and MCP tests

Route and MCP test files were calling createTestDb() without await,
causing db to be a Promise object instead of a Drizzle instance.
Also rewrote auth route tests for OIDC-based auth (merge picked old version).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-05 11:52:38 +02:00
parent c4a7a6c76f
commit 5ae3836d64
8 changed files with 139 additions and 130 deletions

View File

@@ -14,7 +14,7 @@ function parseResult(result: {
describe("MCP Item Tools", () => {
test("list_items returns array", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerItemTools(db, userId);
const result = await tools.list_items({});
const data = parseResult(result);
@@ -22,7 +22,7 @@ describe("MCP Item Tools", () => {
});
test("create_item creates and returns item", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerItemTools(db, userId);
const result = await tools.create_item({
name: "Test Tent",
@@ -38,7 +38,7 @@ describe("MCP Item Tools", () => {
});
test("get_item retrieves by ID", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerItemTools(db, userId);
const created = parseResult(
await tools.create_item({ name: "Sleeping Bag", categoryId: 1 }),
@@ -50,7 +50,7 @@ describe("MCP Item Tools", () => {
});
test("get_item returns error for missing item", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerItemTools(db, userId);
const result = await tools.get_item({ id: 999 });
const data = parseResult(result);
@@ -58,7 +58,7 @@ describe("MCP Item Tools", () => {
});
test("delete_item removes item", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerItemTools(db, userId);
const created = parseResult(
await tools.create_item({ name: "To Delete", categoryId: 1 }),
@@ -76,7 +76,7 @@ describe("MCP Item Tools", () => {
describe("MCP Category Tools", () => {
test("list_categories returns array with Uncategorized", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerCategoryTools(db, userId);
const result = await tools.list_categories();
const data = parseResult(result);
@@ -86,7 +86,7 @@ describe("MCP Category Tools", () => {
});
test("create_category creates a new category", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerCategoryTools(db, userId);
const result = await tools.create_category({
name: "Shelter",
@@ -100,7 +100,7 @@ describe("MCP Category Tools", () => {
describe("MCP Thread Tools", () => {
test("create_thread starts a thread with status active", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerThreadTools(db, userId);
const result = await tools.create_thread({
name: "Handlebar Bag",
@@ -112,7 +112,7 @@ describe("MCP Thread Tools", () => {
});
test("add_candidate adds to thread", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerThreadTools(db, userId);
const thread = parseResult(
await tools.create_thread({ name: "Saddle Bag", categoryId: 1 }),
@@ -132,7 +132,7 @@ describe("MCP Thread Tools", () => {
});
test("resolve_thread picks winner and creates item", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const threadTools = registerThreadTools(db, userId);
const itemTools = registerItemTools(db, userId);
@@ -179,7 +179,7 @@ describe("MCP Thread Tools", () => {
describe("MCP Setup Tools", () => {
test("create_setup and list_setups", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const tools = registerSetupTools(db, userId);
await tools.create_setup({ name: "Weekend Trip" });
const result = await tools.list_setups();
@@ -189,7 +189,7 @@ describe("MCP Setup Tools", () => {
});
test("get_setup returns setup with items", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const setupTools = registerSetupTools(db, userId);
const itemTools = registerItemTools(db, userId);
@@ -210,8 +210,8 @@ describe("MCP Setup Tools", () => {
});
describe("MCP Collection Summary Resource", () => {
test("returns overview with correct counts", () => {
const { db, userId } = createTestDb();
test("returns overview with correct counts", async () => {
const { db, userId } = await createTestDb();
const summary = getCollectionSummary(db, userId);
expect(summary.overview).toBeDefined();
@@ -223,7 +223,7 @@ describe("MCP Collection Summary Resource", () => {
});
test("reflects items and threads after creation", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const itemTools = registerItemTools(db, userId);
const threadTools = registerThreadTools(db, userId);
@@ -254,7 +254,7 @@ describe("MCP Collection Summary Resource", () => {
describe("MCP Cross-User Isolation", () => {
test("user 2 cannot see user 1's items via MCP tools", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const userId2 = createSecondTestUser(db);
const user1Tools = registerItemTools(db, userId);
@@ -285,7 +285,7 @@ describe("MCP Cross-User Isolation", () => {
});
test("user 2 cannot access user 1's item by ID", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const userId2 = createSecondTestUser(db);
const user1Tools = registerItemTools(db, userId);
@@ -305,7 +305,7 @@ describe("MCP Cross-User Isolation", () => {
});
test("user 2 cannot see user 1's threads via MCP tools", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const userId2 = createSecondTestUser(db);
const user1Tools = registerThreadTools(db, userId);
@@ -329,7 +329,7 @@ describe("MCP Cross-User Isolation", () => {
});
test("collection summary is scoped to user", async () => {
const { db, userId } = createTestDb();
const { db, userId } = await createTestDb();
const userId2 = createSecondTestUser(db);
const user1Tools = registerItemTools(db, userId);

View File

@@ -1,10 +1,27 @@
import { beforeEach, describe, expect, it } from "bun:test";
import { beforeEach, describe, expect, it, mock } from "bun:test";
import { Hono } from "hono";
import { authRoutes } from "../../src/server/routes/auth.ts";
import { createApiKey } from "../../src/server/services/auth.service.ts";
import { createTestDb } from "../helpers/db.ts";
function createTestApp() {
const { db, userId } = createTestDb();
// Mock @hono/oidc-auth
const mockGetAuth = mock(() => null as any);
mock.module("@hono/oidc-auth", () => ({
getAuth: mockGetAuth,
oidcAuthMiddleware: () => async (_c: any, next: any) => next(),
processOAuthCallback: async (c: any) => c.json({ ok: true }),
revokeSession: async () => {},
}));
// Mock verifyAccessToken from oauth.service
mock.module("../../src/server/services/oauth.service", () => ({
verifyAccessToken: mock(() => Promise.resolve(null)),
}));
// Import routes AFTER mocks
const { authRoutes } = await import("../../src/server/routes/auth.ts");
async function createTestApp() {
const { db, userId } = await createTestDb();
const app = new Hono<{ Variables: { db?: any; userId?: number } }>();
app.use("*", async (c, next) => {
@@ -19,111 +36,99 @@ function createTestApp() {
describe("Auth Routes", () => {
let app: Hono;
let db: Awaited<ReturnType<typeof createTestDb>>["db"];
let userId: number;
beforeEach(() => {
const testApp = createTestApp();
beforeEach(async () => {
const testApp = await createTestApp();
app = testApp.app;
db = testApp.db;
userId = testApp.userId;
mockGetAuth.mockReset();
mockGetAuth.mockReturnValue(null);
});
describe("GET /api/auth/me", () => {
it("returns null user and setupRequired true when no users exist", async () => {
it("returns authenticated false when no OIDC session", async () => {
const res = await app.request("/api/auth/me");
expect(res.status).toBe(200);
const body = await res.json();
expect(body.user).toBeNull();
expect(body.setupRequired).toBe(true);
});
expect(body.authenticated).toBe(false);
});
describe("POST /api/auth/setup", () => {
it("creates first user and returns 201", async () => {
const res = await app.request("/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "admin", password: "secret123" }),
it("returns user info when OIDC session exists", async () => {
mockGetAuth.mockReturnValue({
sub: "logto-user-abc123",
email: "user@example.com",
});
expect(res.status).toBe(201);
const body = await res.json();
expect(body.username).toBe("admin");
// Should set a session cookie
const setCookie = res.headers.get("set-cookie");
expect(setCookie).toContain("gearbox_session");
});
it("rejects second setup attempt with 403", async () => {
// First setup
await app.request("/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "admin", password: "secret123" }),
});
// Second attempt
const res = await app.request("/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "other", password: "secret456" }),
});
expect(res.status).toBe(403);
});
it("rejects password shorter than 6 characters", async () => {
const res = await app.request("/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "admin", password: "short" }),
});
expect(res.status).toBe(400);
});
});
describe("POST /api/auth/login", () => {
beforeEach(async () => {
// Create a user first
await app.request("/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "admin", password: "secret123" }),
});
});
it("returns session cookie on valid login", async () => {
const res = await app.request("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "admin", password: "secret123" }),
});
const res = await app.request("/api/auth/me");
expect(res.status).toBe(200);
const body = await res.json();
expect(body.username).toBe("admin");
const setCookie = res.headers.get("set-cookie");
expect(setCookie).toContain("gearbox_session");
expect(body.authenticated).toBe(true);
expect(body.user.id).toBe("logto-user-abc123");
expect(body.user.email).toBe("user@example.com");
});
});
it("rejects invalid credentials with 401", async () => {
const res = await app.request("/api/auth/login", {
describe("GET /api/auth/keys", () => {
it("returns 401 without authentication", async () => {
const res = await app.request("/api/auth/keys");
expect(res.status).toBe(401);
});
it("returns key list with API key auth", async () => {
const key = await createApiKey(db, userId, "test-key");
const res = await app.request("/api/auth/keys", {
headers: { "X-API-Key": key.rawKey },
});
expect(res.status).toBe(200);
const body = await res.json();
expect(Array.isArray(body)).toBe(true);
expect(body.length).toBeGreaterThanOrEqual(1);
});
});
describe("POST /api/auth/keys", () => {
it("creates a new API key when authenticated", async () => {
const authKey = await createApiKey(db, userId, "auth-key");
const res = await app.request("/api/auth/keys", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": authKey.rawKey,
},
body: JSON.stringify({ name: "my-new-key" }),
});
expect(res.status).toBe(201);
const body = await res.json();
expect(body.name).toBe("my-new-key");
expect(body.key).toBeDefined();
expect(body.prefix).toBeDefined();
});
it("rejects without auth", async () => {
const res = await app.request("/api/auth/keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "admin", password: "wrongpassword" }),
body: JSON.stringify({ name: "my-key" }),
});
expect(res.status).toBe(401);
});
});
describe("POST /api/auth/logout", () => {
it("clears session cookie", async () => {
const res = await app.request("/api/auth/logout", {
method: "POST",
});
describe("DELETE /api/auth/keys/:id", () => {
it("deletes an API key when authenticated", async () => {
const authKey = await createApiKey(db, userId, "auth-key");
const targetKey = await createApiKey(db, userId, "to-delete");
const res = await app.request(`/api/auth/keys/${targetKey.id}`, {
method: "DELETE",
headers: { "X-API-Key": authKey.rawKey },
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.ok).toBe(true);
});
});
});

View File

@@ -4,8 +4,8 @@ import { categoryRoutes } from "../../src/server/routes/categories.ts";
import { itemRoutes } from "../../src/server/routes/items.ts";
import { createTestDb } from "../helpers/db.ts";
function createTestApp() {
const { db, userId } = createTestDb();
async function createTestApp() {
const { db, userId } = await createTestDb();
const app = new Hono();
// Inject test DB and userId into context for all routes
@@ -23,8 +23,8 @@ function createTestApp() {
describe("Category Routes", () => {
let app: Hono;
beforeEach(() => {
const testApp = createTestApp();
beforeEach(async () => {
const testApp = await createTestApp();
app = testApp.app;
});

View File

@@ -1,16 +1,20 @@
import { describe, expect, test } from "bun:test";
import { beforeEach, describe, expect, test } from "bun:test";
import { Hono } from "hono";
import { imageRoutes } from "../../src/server/routes/images";
import { createTestDb } from "../helpers/db.ts";
const { db, userId } = createTestDb();
const app = new Hono();
let app: Hono;
beforeEach(async () => {
const { db, userId } = await createTestDb();
app = new Hono();
app.use("*", async (c, next) => {
c.set("db", db);
c.set("userId", userId);
await next();
});
app.route("/api/images", imageRoutes);
});
describe("POST /api/images/from-url", () => {
test("returns 400 for missing URL", async () => {

View File

@@ -4,8 +4,8 @@ import { categoryRoutes } from "../../src/server/routes/categories.ts";
import { itemRoutes } from "../../src/server/routes/items.ts";
import { createTestDb } from "../helpers/db.ts";
function createTestApp() {
const { db, userId } = createTestDb();
async function createTestApp() {
const { db, userId } = await createTestDb();
const app = new Hono();
// Inject test DB and userId into context for all routes
@@ -23,8 +23,8 @@ function createTestApp() {
describe("Item Routes", () => {
let app: Hono;
beforeEach(() => {
const testApp = createTestApp();
beforeEach(async () => {
const testApp = await createTestApp();
app = testApp.app;
});

View File

@@ -6,8 +6,8 @@ import { setupRoutes } from "../../src/server/routes/setups";
import { threadRoutes } from "../../src/server/routes/threads";
import { createTestDb } from "../helpers/db";
function createTestApp() {
const { db, userId } = createTestDb();
async function createTestApp() {
const { db, userId } = await createTestDb();
const app = new Hono();
app.use("*", async (c, next) => {
c.set("db", db);
@@ -24,8 +24,8 @@ function createTestApp() {
describe("Invalid ID parameter handling", () => {
let app: Hono;
beforeEach(() => {
app = createTestApp();
beforeEach(async () => {
app = await createTestApp();
});
describe("items", () => {

View File

@@ -4,8 +4,8 @@ import { itemRoutes } from "../../src/server/routes/items.ts";
import { setupRoutes } from "../../src/server/routes/setups.ts";
import { createTestDb } from "../helpers/db.ts";
function createTestApp() {
const { db, userId } = createTestDb();
async function createTestApp() {
const { db, userId } = await createTestDb();
const app = new Hono();
app.use("*", async (c, next) => {
@@ -40,8 +40,8 @@ async function createItemViaAPI(app: Hono, data: any) {
describe("Setup Routes", () => {
let app: Hono;
beforeEach(() => {
const testApp = createTestApp();
beforeEach(async () => {
const testApp = await createTestApp();
app = testApp.app;
});

View File

@@ -3,8 +3,8 @@ import { Hono } from "hono";
import { threadRoutes } from "../../src/server/routes/threads.ts";
import { createTestDb } from "../helpers/db.ts";
function createTestApp() {
const { db, userId } = createTestDb();
async function createTestApp() {
const { db, userId } = await createTestDb();
const app = new Hono();
// Inject test DB and userId into context for all routes
@@ -39,8 +39,8 @@ async function createCandidateViaAPI(app: Hono, threadId: number, data: any) {
describe("Thread Routes", () => {
let app: Hono;
beforeEach(() => {
const testApp = createTestApp();
beforeEach(async () => {
const testApp = await createTestApp();
app = testApp.app;
});