|
| 1 | +// Use vi.hoisted to define mock functions that can be referenced in hoisted vi.mock() calls |
| 2 | +const { mockStreamText, mockGenerateText } = vi.hoisted(() => ({ |
| 3 | + mockStreamText: vi.fn(), |
| 4 | + mockGenerateText: vi.fn(), |
| 5 | +})) |
| 6 | + |
| 7 | +vi.mock("ai", async (importOriginal) => { |
| 8 | + const actual = await importOriginal<typeof import("ai")>() |
| 9 | + return { |
| 10 | + ...actual, |
| 11 | + streamText: mockStreamText, |
| 12 | + generateText: mockGenerateText, |
| 13 | + } |
| 14 | +}) |
| 15 | + |
| 16 | +vi.mock("@ai-sdk/openai-compatible", () => ({ |
| 17 | + createOpenAICompatible: vi.fn(function () { |
| 18 | + // Return a function that returns a mock language model |
| 19 | + return vi.fn(() => ({ |
| 20 | + modelId: "test-model", |
| 21 | + provider: "openai-compatible", |
| 22 | + })) |
| 23 | + }), |
| 24 | +})) |
| 25 | + |
| 26 | +import type { Anthropic } from "@anthropic-ai/sdk" |
| 27 | + |
| 28 | +import { OpenAICompatibleHandler, OpenAICompatibleConfig } from "../openai-compatible" |
| 29 | +import type { ApiHandlerOptions } from "../../../shared/api" |
| 30 | + |
| 31 | +// Concrete implementation for testing |
| 32 | +class TestOpenAICompatibleHandler extends OpenAICompatibleHandler { |
| 33 | + constructor(options: ApiHandlerOptions, config: OpenAICompatibleConfig) { |
| 34 | + super(options, config) |
| 35 | + } |
| 36 | + |
| 37 | + override getModel() { |
| 38 | + return { |
| 39 | + id: this.config.modelId, |
| 40 | + info: this.config.modelInfo, |
| 41 | + maxTokens: this.config.modelMaxTokens, |
| 42 | + temperature: this.config.temperature, |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +describe("OpenAICompatibleHandler", () => { |
| 48 | + let handler: TestOpenAICompatibleHandler |
| 49 | + let mockOptions: ApiHandlerOptions |
| 50 | + let mockConfig: OpenAICompatibleConfig |
| 51 | + |
| 52 | + const systemPrompt = "You are a helpful assistant." |
| 53 | + const messages: Anthropic.Messages.MessageParam[] = [ |
| 54 | + { |
| 55 | + role: "user", |
| 56 | + content: [{ type: "text", text: "Hello!" }], |
| 57 | + }, |
| 58 | + ] |
| 59 | + |
| 60 | + beforeEach(() => { |
| 61 | + mockOptions = { |
| 62 | + apiModelId: "test-model", |
| 63 | + apiKey: "test-api-key", |
| 64 | + } |
| 65 | + mockConfig = { |
| 66 | + providerName: "TestProvider", |
| 67 | + baseURL: "https://api.test.com/v1", |
| 68 | + apiKey: "test-api-key", |
| 69 | + modelId: "test-model", |
| 70 | + modelInfo: { |
| 71 | + maxTokens: 8192, |
| 72 | + contextWindow: 128000, |
| 73 | + supportsImages: false, |
| 74 | + supportsPromptCache: true, |
| 75 | + }, |
| 76 | + } |
| 77 | + handler = new TestOpenAICompatibleHandler(mockOptions, mockConfig) |
| 78 | + vi.clearAllMocks() |
| 79 | + }) |
| 80 | + |
| 81 | + describe("constructor", () => { |
| 82 | + it("should initialize with provided options and config", () => { |
| 83 | + expect(handler).toBeInstanceOf(TestOpenAICompatibleHandler) |
| 84 | + expect(handler.getModel().id).toBe(mockConfig.modelId) |
| 85 | + }) |
| 86 | + }) |
| 87 | + |
| 88 | + describe("createMessage", () => { |
| 89 | + it("should handle streaming responses", async () => { |
| 90 | + async function* mockFullStream() { |
| 91 | + yield { type: "text-delta", text: "Test response" } |
| 92 | + } |
| 93 | + |
| 94 | + const mockUsage = Promise.resolve({ |
| 95 | + inputTokens: 10, |
| 96 | + outputTokens: 5, |
| 97 | + details: {}, |
| 98 | + raw: {}, |
| 99 | + }) |
| 100 | + |
| 101 | + mockStreamText.mockReturnValue({ |
| 102 | + fullStream: mockFullStream(), |
| 103 | + usage: mockUsage, |
| 104 | + }) |
| 105 | + |
| 106 | + const stream = handler.createMessage(systemPrompt, messages) |
| 107 | + const chunks: any[] = [] |
| 108 | + for await (const chunk of stream) { |
| 109 | + chunks.push(chunk) |
| 110 | + } |
| 111 | + |
| 112 | + expect(chunks.length).toBeGreaterThan(0) |
| 113 | + const textChunks = chunks.filter((chunk) => chunk.type === "text") |
| 114 | + expect(textChunks).toHaveLength(1) |
| 115 | + expect(textChunks[0].text).toBe("Test response") |
| 116 | + }) |
| 117 | + // Test 1: createMessage() with mock 429 response → verify thrown error has .status === 429 and provider name in message |
| 118 | + it("should throw error with .status 429 when API returns 429", async () => { |
| 119 | + const rateLimitError = new Error("Rate limited") as Error & { status: number } |
| 120 | + rateLimitError.status = 429 |
| 121 | + |
| 122 | + mockStreamText.mockReturnValue({ |
| 123 | + // eslint-disable-next-line require-yield |
| 124 | + fullStream: (async function* () { |
| 125 | + throw rateLimitError |
| 126 | + })(), |
| 127 | + usage: Promise.resolve({ inputTokens: 0, outputTokens: 0, details: {}, raw: {} }), |
| 128 | + }) |
| 129 | + |
| 130 | + let thrownError: any |
| 131 | + try { |
| 132 | + for await (const chunk of handler.createMessage(systemPrompt, messages)) { |
| 133 | + void chunk // Use void to satisfy no-unused-expressions rule |
| 134 | + } |
| 135 | + } catch (e: any) { |
| 136 | + thrownError = e |
| 137 | + } |
| 138 | + |
| 139 | + expect(thrownError).toBeInstanceOf(Error) |
| 140 | + expect(thrownError.status).toBe(429) |
| 141 | + expect(thrownError.message).toContain("TestProvider") |
| 142 | + }) |
| 143 | + |
| 144 | + // Test 2: createMessage() with mock 500 response → verify error is properly tagged |
| 145 | + it("should throw error with .status 500 and provider name when API returns 500", async () => { |
| 146 | + const serverError = new Error("Internal Server Error") as Error & { status: number } |
| 147 | + serverError.status = 500 |
| 148 | + |
| 149 | + mockStreamText.mockReturnValue({ |
| 150 | + // eslint-disable-next-line require-yield |
| 151 | + fullStream: (async function* () { |
| 152 | + throw serverError |
| 153 | + })(), |
| 154 | + usage: Promise.resolve({ inputTokens: 0, outputTokens: 0, details: {}, raw: {} }), |
| 155 | + }) |
| 156 | + |
| 157 | + let thrownError: any |
| 158 | + try { |
| 159 | + for await (const chunk of handler.createMessage(systemPrompt, messages)) { |
| 160 | + void chunk |
| 161 | + } |
| 162 | + } catch (e: any) { |
| 163 | + thrownError = e |
| 164 | + } |
| 165 | + |
| 166 | + expect(thrownError).toBeInstanceOf(Error) |
| 167 | + expect(thrownError.status).toBe(500) |
| 168 | + expect(thrownError.message).toContain("TestProvider") |
| 169 | + }) |
| 170 | + }) |
| 171 | + |
| 172 | + describe("completePrompt", () => { |
| 173 | + it("should complete a prompt using generateText", async () => { |
| 174 | + mockGenerateText.mockResolvedValue({ |
| 175 | + text: "Test completion", |
| 176 | + }) |
| 177 | + |
| 178 | + const result = await handler.completePrompt("Test prompt") |
| 179 | + |
| 180 | + expect(result).toBe("Test completion") |
| 181 | + expect(mockGenerateText).toHaveBeenCalledWith( |
| 182 | + expect.objectContaining({ |
| 183 | + prompt: "Test prompt", |
| 184 | + }), |
| 185 | + ) |
| 186 | + }) |
| 187 | + |
| 188 | + // Test 3: completePrompt() with mock 4xx/5xx → verify error carries .status and provider name |
| 189 | + it("should throw error with .status and provider name when generateText throws 400", async () => { |
| 190 | + const badRequestError = new Error("Bad Request") as Error & { status: number } |
| 191 | + badRequestError.status = 400 |
| 192 | + |
| 193 | + mockGenerateText.mockRejectedValue(badRequestError) |
| 194 | + |
| 195 | + await expect(handler.completePrompt("Test prompt")).rejects.toThrow("TestProvider") |
| 196 | + |
| 197 | + let thrownError: any |
| 198 | + try { |
| 199 | + await handler.completePrompt("Test prompt") |
| 200 | + } catch (e: any) { |
| 201 | + thrownError = e |
| 202 | + } |
| 203 | + |
| 204 | + expect(thrownError).toBeInstanceOf(Error) |
| 205 | + expect((thrownError as any).status).toBe(400) |
| 206 | + expect(thrownError.message).toContain("TestProvider") |
| 207 | + }) |
| 208 | + |
| 209 | + it("should throw error with .status and provider name when generateText throws 500", async () => { |
| 210 | + const serverError = new Error("Internal Server Error") as Error & { status: number } |
| 211 | + serverError.status = 500 |
| 212 | + |
| 213 | + mockGenerateText.mockRejectedValue(serverError) |
| 214 | + |
| 215 | + let thrownError: any |
| 216 | + try { |
| 217 | + await handler.completePrompt("Test prompt") |
| 218 | + } catch (e: any) { |
| 219 | + thrownError = e |
| 220 | + } |
| 221 | + |
| 222 | + expect(thrownError).toBeInstanceOf(Error) |
| 223 | + expect((thrownError as any).status).toBe(500) |
| 224 | + expect(thrownError.message).toContain("TestProvider") |
| 225 | + }) |
| 226 | + }) |
| 227 | +}) |
0 commit comments