Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 76 additions & 40 deletions lib/chat/__tests__/handleChatGenerate.test.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,15 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextResponse } from "next/server";

import { getApiKeyAccountId } from "@/lib/auth/getApiKeyAccountId";
import { validateOverrideAccountId } from "@/lib/accounts/validateOverrideAccountId";
import { validateAuthContext } from "@/lib/auth/validateAuthContext";
import { setupChatRequest } from "@/lib/chat/setupChatRequest";
import { saveChatCompletion } from "@/lib/chat/saveChatCompletion";
import { setupConversation } from "@/lib/chat/setupConversation";
import { handleChatGenerate } from "../handleChatGenerate";

// Mock all dependencies before importing the module under test
vi.mock("@/lib/auth/getApiKeyAccountId", () => ({
getApiKeyAccountId: vi.fn(),
}));

vi.mock("@/lib/auth/getAuthenticatedAccountId", () => ({
getAuthenticatedAccountId: vi.fn(),
}));

vi.mock("@/lib/accounts/validateOverrideAccountId", () => ({
validateOverrideAccountId: vi.fn(),
}));

vi.mock("@/lib/keys/getApiKeyDetails", () => ({
getApiKeyDetails: vi.fn(),
}));

vi.mock("@/lib/organizations/validateOrganizationAccess", () => ({
validateOrganizationAccess: vi.fn(),
vi.mock("@/lib/auth/validateAuthContext", () => ({
validateAuthContext: vi.fn(),
}));

vi.mock("@/lib/chat/setupChatRequest", () => ({
Expand Down Expand Up @@ -61,8 +44,7 @@ vi.mock("@/lib/chat/setupConversation", () => ({
setupConversation: vi.fn(),
}));

const mockGetApiKeyAccountId = vi.mocked(getApiKeyAccountId);
const mockValidateOverrideAccountId = vi.mocked(validateOverrideAccountId);
const mockValidateAuthContext = vi.mocked(validateAuthContext);
const mockSetupChatRequest = vi.mocked(setupChatRequest);
const mockSaveChatCompletion = vi.mocked(saveChatCompletion);
const mockSetupConversation = vi.mocked(setupConversation);
Expand Down Expand Up @@ -112,7 +94,11 @@ describe("handleChatGenerate", () => {

describe("validation", () => {
it("returns 400 error when neither messages nor prompt is provided", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});

const request = createMockRequest({ roomId: "room-123" }, { "x-api-key": "test-key" });

Expand All @@ -125,20 +111,25 @@ describe("handleChatGenerate", () => {
});

it("returns 401 error when no auth header is provided", async () => {
mockValidateAuthContext.mockResolvedValue(
NextResponse.json({ status: "error", error: "Unauthorized" }, { status: 401 }),
);
const request = createMockRequest({ prompt: "Hello" }, {});

const result = await handleChatGenerate(request as any);

expect(result).toBeInstanceOf(NextResponse);
expect(result.status).toBe(401);
const json = await result.json();
expect(json.message).toBe("Exactly one of x-api-key or Authorization must be provided");
});
});

describe("text generation", () => {
it("returns generated text using agent.generate() for valid requests", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});

const mockAgent = createMockAgent({
text: "Hello! How can I help you?",
Expand Down Expand Up @@ -171,7 +162,11 @@ describe("handleChatGenerate", () => {
});

it("uses messages array when provided", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});

const mockAgent = createMockAgent({
text: "Response",
Expand Down Expand Up @@ -199,7 +194,11 @@ describe("handleChatGenerate", () => {
});

it("passes through optional parameters", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});
mockSetupConversation.mockResolvedValue({
roomId: "room-xyz",
memoryId: "memory-id",
Expand Down Expand Up @@ -241,7 +240,11 @@ describe("handleChatGenerate", () => {
});

it("includes reasoningText when present", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});

const mockAgent = createMockAgent({
text: "Response",
Expand Down Expand Up @@ -270,7 +273,11 @@ describe("handleChatGenerate", () => {

describe("error handling", () => {
it("returns 500 error when setupChatRequest fails", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});
mockSetupChatRequest.mockRejectedValue(new Error("Setup failed"));

const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" });
Expand All @@ -284,7 +291,11 @@ describe("handleChatGenerate", () => {
});

it("returns 500 error when agent.generate() fails", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});

const mockAgent = {
generate: vi.fn().mockRejectedValue(new Error("Generation failed")),
Expand All @@ -309,10 +320,11 @@ describe("handleChatGenerate", () => {
});

describe("accountId override", () => {
it("allows org API key to override accountId", async () => {
mockGetApiKeyAccountId.mockResolvedValue("org-account-123");
mockValidateOverrideAccountId.mockResolvedValue({
it("allows accountId override", async () => {
mockValidateAuthContext.mockResolvedValue({
accountId: "target-account-456",
orgId: null,
authToken: "token",
});

const mockAgent = createMockAgent({
Expand Down Expand Up @@ -344,7 +356,11 @@ describe("handleChatGenerate", () => {

describe("message persistence", () => {
it("saves assistant message to database when roomId is provided", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});
mockSetupConversation.mockResolvedValue({
roomId: "room-abc-123",
memoryId: "memory-id",
Expand Down Expand Up @@ -378,7 +394,11 @@ describe("handleChatGenerate", () => {
});

it("saves message with auto-generated roomId when roomId is not provided", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});
mockSetupConversation.mockResolvedValue({
roomId: "auto-generated-room-id",
memoryId: "memory-id",
Expand Down Expand Up @@ -410,7 +430,11 @@ describe("handleChatGenerate", () => {
});

it("includes roomId in HTTP response when provided by client", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});
mockSetupConversation.mockResolvedValue({
roomId: "client-provided-room-id",
memoryId: "memory-id",
Expand Down Expand Up @@ -443,7 +467,11 @@ describe("handleChatGenerate", () => {
});

it("includes auto-generated roomId in HTTP response when not provided", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});
mockSetupConversation.mockResolvedValue({
roomId: "auto-generated-room-456",
memoryId: "memory-id",
Expand Down Expand Up @@ -473,7 +501,11 @@ describe("handleChatGenerate", () => {
});

it("passes correct text to saveChatCompletion", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});
mockSetupConversation.mockResolvedValue({
roomId: "room-xyz",
memoryId: "memory-id",
Expand Down Expand Up @@ -507,7 +539,11 @@ describe("handleChatGenerate", () => {
});

it("still returns success response even if saveChatCompletion fails", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});
mockSetupConversation.mockResolvedValue({
roomId: "room-abc",
memoryId: "memory-id",
Expand Down
68 changes: 36 additions & 32 deletions lib/chat/__tests__/handleChatStream.test.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,15 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextResponse } from "next/server";

import { getApiKeyAccountId } from "@/lib/auth/getApiKeyAccountId";
import { validateOverrideAccountId } from "@/lib/accounts/validateOverrideAccountId";
import { validateAuthContext } from "@/lib/auth/validateAuthContext";
import { setupChatRequest } from "@/lib/chat/setupChatRequest";
import { setupConversation } from "@/lib/chat/setupConversation";
import { createUIMessageStream, createUIMessageStreamResponse } from "ai";
import { handleChatStream } from "../handleChatStream";

// Mock all dependencies before importing the module under test
vi.mock("@/lib/auth/getApiKeyAccountId", () => ({
getApiKeyAccountId: vi.fn(),
}));

vi.mock("@/lib/auth/getAuthenticatedAccountId", () => ({
getAuthenticatedAccountId: vi.fn(),
}));

vi.mock("@/lib/accounts/validateOverrideAccountId", () => ({
validateOverrideAccountId: vi.fn(),
}));

vi.mock("@/lib/keys/getApiKeyDetails", () => ({
getApiKeyDetails: vi.fn(),
}));

vi.mock("@/lib/organizations/validateOrganizationAccess", () => ({
validateOrganizationAccess: vi.fn(),
vi.mock("@/lib/auth/validateAuthContext", () => ({
validateAuthContext: vi.fn(),
}));

vi.mock("@/lib/chat/setupConversation", () => ({
Expand Down Expand Up @@ -67,8 +50,7 @@ vi.mock("ai", () => ({
createUIMessageStreamResponse: vi.fn(),
}));

const mockGetApiKeyAccountId = vi.mocked(getApiKeyAccountId);
const mockValidateOverrideAccountId = vi.mocked(validateOverrideAccountId);
const mockValidateAuthContext = vi.mocked(validateAuthContext);
const mockSetupConversation = vi.mocked(setupConversation);
const mockSetupChatRequest = vi.mocked(setupChatRequest);
const mockCreateUIMessageStream = vi.mocked(createUIMessageStream);
Expand Down Expand Up @@ -107,7 +89,11 @@ describe("handleChatStream", () => {

describe("validation", () => {
it("returns 400 error when neither messages nor prompt is provided", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});

const request = createMockRequest({ roomId: "room-123" }, { "x-api-key": "test-key" });

Expand All @@ -120,20 +106,25 @@ describe("handleChatStream", () => {
});

it("returns 401 error when no auth header is provided", async () => {
mockValidateAuthContext.mockResolvedValue(
NextResponse.json({ status: "error", error: "Unauthorized" }, { status: 401 }),
);
const request = createMockRequest({ prompt: "Hello" }, {});

const result = await handleChatStream(request as any);

expect(result).toBeInstanceOf(NextResponse);
expect(result.status).toBe(401);
const json = await result.json();
expect(json.message).toBe("Exactly one of x-api-key or Authorization must be provided");
});
});

describe("streaming", () => {
it("creates a streaming response for valid requests", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});

const mockAgent = {
stream: vi.fn().mockResolvedValue({
Expand Down Expand Up @@ -173,7 +164,11 @@ describe("handleChatStream", () => {
});

it("uses messages array when provided", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});

const mockAgent = {
stream: vi.fn().mockResolvedValue({
Expand Down Expand Up @@ -206,7 +201,11 @@ describe("handleChatStream", () => {
});

it("passes through optional parameters", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});

const mockAgent = {
stream: vi.fn().mockResolvedValue({
Expand Down Expand Up @@ -251,7 +250,11 @@ describe("handleChatStream", () => {

describe("error handling", () => {
it("returns 500 error when setupChatRequest fails", async () => {
mockGetApiKeyAccountId.mockResolvedValue("account-123");
mockValidateAuthContext.mockResolvedValue({
accountId: "account-123",
orgId: null,
authToken: "token",
});
mockSetupChatRequest.mockRejectedValue(new Error("Setup failed"));

const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" });
Expand All @@ -266,10 +269,11 @@ describe("handleChatStream", () => {
});

describe("accountId override", () => {
it("allows org API key to override accountId", async () => {
mockGetApiKeyAccountId.mockResolvedValue("org-account-123");
mockValidateOverrideAccountId.mockResolvedValue({
it("allows accountId override", async () => {
mockValidateAuthContext.mockResolvedValue({
accountId: "target-account-456",
orgId: null,
authToken: "token",
});

const mockAgent = {
Expand Down
Loading
Loading