-
-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
route.test.ts
226 lines (185 loc) · 7.18 KB
/
route.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// @vitest-environment node
import { getAuth } from '@clerk/nextjs/server';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { checkAuthMethod } from '@/app/(backend)/middleware/auth/utils';
import { LOBE_CHAT_AUTH_HEADER, OAUTH_AUTHORIZED } from '@/const/auth';
import { AgentRuntime, LobeRuntimeAI } from '@/libs/agent-runtime';
import { ChatErrorType } from '@/types/fetch';
import { getJWTPayload } from '@/utils/server/jwt';
import { POST } from './route';
vi.mock('@clerk/nextjs/server', () => ({
getAuth: vi.fn(),
}));
vi.mock('@/app/(backend)/middleware/auth/utils', () => ({
checkAuthMethod: vi.fn(),
}));
vi.mock('@/utils/server/jwt', () => ({
getJWTPayload: vi.fn(),
}));
// 定义一个变量来存储 enableAuth 的值
let enableClerk = false;
// 模拟 @/const/auth 模块
vi.mock('@/const/auth', async (importOriginal) => {
const modules = await importOriginal();
return {
...(modules as any),
get enableClerk() {
return enableClerk;
},
};
});
// 模拟请求和响应
let request: Request;
beforeEach(() => {
request = new Request(new URL('https://test.com'), {
headers: {
[LOBE_CHAT_AUTH_HEADER]: 'Bearer some-valid-token',
[OAUTH_AUTHORIZED]: 'true',
},
method: 'POST',
body: JSON.stringify({ model: 'test-model' }),
});
});
afterEach(() => {
// 清除模拟调用历史
vi.clearAllMocks();
enableClerk = false;
});
describe('POST handler', () => {
describe('init chat model', () => {
it('should initialize AgentRuntime correctly with valid authorization', async () => {
const mockParams = Promise.resolve({ provider: 'test-provider' });
// 设置 getJWTPayload 和 initAgentRuntimeWithUserPayload 的模拟返回值
vi.mocked(getJWTPayload).mockResolvedValueOnce({
accessCode: 'test-access-code',
apiKey: 'test-api-key',
azureApiVersion: 'v1',
});
const mockRuntime: LobeRuntimeAI = { baseURL: 'abc', chat: vi.fn() };
// migrate to new AgentRuntime init api
const spy = vi
.spyOn(AgentRuntime, 'initializeWithProviderOptions')
.mockResolvedValue(new AgentRuntime(mockRuntime));
// 调用 POST 函数
await POST(request as unknown as Request, { params: mockParams });
// 验证是否正确调用了模拟函数
expect(getJWTPayload).toHaveBeenCalledWith('Bearer some-valid-token');
expect(spy).toHaveBeenCalledWith('test-provider', expect.anything());
});
it('should return Unauthorized error when LOBE_CHAT_AUTH_HEADER is missing', async () => {
const mockParams = Promise.resolve({ provider: 'test-provider' });
const requestWithoutAuthHeader = new Request(new URL('https://test.com'), {
method: 'POST',
body: JSON.stringify({ model: 'test-model' }),
});
const response = await POST(requestWithoutAuthHeader, { params: mockParams });
expect(response.status).toBe(401);
expect(await response.json()).toEqual({
body: {
error: { errorType: 401 },
provider: 'test-provider',
},
errorType: 401,
});
});
it('should have pass clerk Auth when enable clerk', async () => {
enableClerk = true;
vi.mocked(getJWTPayload).mockResolvedValueOnce({
accessCode: 'test-access-code',
apiKey: 'test-api-key',
azureApiVersion: 'v1',
});
const mockParams = Promise.resolve({ provider: 'test-provider' });
// 设置 initAgentRuntimeWithUserPayload 的模拟返回值
vi.mocked(getAuth).mockReturnValue({} as any);
vi.mocked(checkAuthMethod).mockReset();
const mockRuntime: LobeRuntimeAI = { baseURL: 'abc', chat: vi.fn() };
vi.spyOn(AgentRuntime, 'initializeWithProviderOptions').mockResolvedValue(
new AgentRuntime(mockRuntime),
);
const request = new Request(new URL('https://test.com'), {
method: 'POST',
body: JSON.stringify({ model: 'test-model' }),
headers: {
[LOBE_CHAT_AUTH_HEADER]: 'some-valid-token',
[OAUTH_AUTHORIZED]: '1',
},
});
await POST(request, { params: mockParams });
expect(checkAuthMethod).toBeCalledWith({
accessCode: 'test-access-code',
apiKey: 'test-api-key',
clerkAuth: {},
nextAuthAuthorized: true,
});
});
it('should return InternalServerError error when throw a unknown error', async () => {
const mockParams = Promise.resolve({ provider: 'test-provider' });
vi.mocked(getJWTPayload).mockRejectedValueOnce(new Error('unknown error'));
const response = await POST(request, { params: mockParams });
expect(response.status).toBe(500);
expect(await response.json()).toEqual({
body: {
error: {},
provider: 'test-provider',
},
errorType: 500,
});
});
});
describe('chat', () => {
it('should correctly handle chat completion with valid payload', async () => {
vi.mocked(getJWTPayload).mockResolvedValueOnce({
accessCode: 'test-access-code',
apiKey: 'test-api-key',
azureApiVersion: 'v1',
userId: 'abc',
});
const mockParams = Promise.resolve({ provider: 'test-provider' });
const mockChatPayload = { message: 'Hello, world!' };
request = new Request(new URL('https://test.com'), {
headers: { [LOBE_CHAT_AUTH_HEADER]: 'Bearer some-valid-token' },
method: 'POST',
body: JSON.stringify(mockChatPayload),
});
const mockChatResponse: any = { success: true, message: 'Reply from agent' };
vi.spyOn(AgentRuntime.prototype, 'chat').mockResolvedValue(mockChatResponse);
const response = await POST(request as unknown as Request, { params: mockParams });
expect(response).toEqual(mockChatResponse);
expect(AgentRuntime.prototype.chat).toHaveBeenCalledWith(mockChatPayload, { user: 'abc' });
});
it('should return an error response when chat completion fails', async () => {
// 设置 getJWTPayload 和 initAgentRuntimeWithUserPayload 的模拟返回值
vi.mocked(getJWTPayload).mockResolvedValueOnce({
accessCode: 'test-access-code',
apiKey: 'test-api-key',
azureApiVersion: 'v1',
});
const mockParams = Promise.resolve({ provider: 'test-provider' });
const mockChatPayload = { message: 'Hello, world!' };
request = new Request(new URL('https://test.com'), {
headers: { [LOBE_CHAT_AUTH_HEADER]: 'Bearer some-valid-token' },
method: 'POST',
body: JSON.stringify(mockChatPayload),
});
const mockErrorResponse = {
errorType: ChatErrorType.InternalServerError,
errorMessage: 'Something went wrong',
};
vi.spyOn(AgentRuntime.prototype, 'chat').mockRejectedValue(mockErrorResponse);
const response = await POST(request, { params: mockParams });
expect(response.status).toBe(500);
expect(await response.json()).toEqual({
body: {
errorMessage: 'Something went wrong',
error: {
errorMessage: 'Something went wrong',
errorType: 500,
},
provider: 'test-provider',
},
errorType: 500,
});
});
});
});