-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_test.go
More file actions
311 lines (268 loc) · 10.4 KB
/
handler_test.go
File metadata and controls
311 lines (268 loc) · 10.4 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package main
import (
"bufio"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
var v1Endpoint = "/v1/messages"
func TestHandler(t *testing.T) {
t.Run("non-streaming", func(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != v1Endpoint {
t.Errorf("unexpected path: %s", r.URL.Path)
}
if r.Header.Get("anthropic-version") != "2023-06-01" {
t.Errorf("missing anthropic-version header")
}
if r.Header.Get("Authorization") != "Bearer test-token" {
t.Errorf("unexpected auth: %s", r.Header.Get("Authorization"))
}
var antReq anthropicRequest
json.NewDecoder(r.Body).Decode(&antReq)
if antReq.System != "You are helpful" {
t.Errorf("system not extracted: %q", antReq.System)
}
if antReq.MaxTokens != 100 {
t.Errorf("unexpected max_tokens: %d", antReq.MaxTokens)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(anthropicResponse{
ID: "msg-test",
Type: "message",
Role: "assistant",
Content: []contentBlock{{Type: "text", Text: "Hi there!"}},
Model: "claude-sonnet-4-20250514",
StopReason: "end_turn",
Usage: anthropicUsage{InputTokens: 10, OutputTokens: 5},
})
}))
t.Cleanup(backend.Close)
provider := &tokenProvider{token: "test-token"}
fallback := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Error("fallback should not be called")
})
handler := newConvertHandler(backend.URL+v1Endpoint, provider, convertOpts{}, fallback)
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
body := `{"model":"claude-sonnet-4-20250514","messages":[{"role":"system","content":"You are helpful"},{"role":"user","content":"Hello"}],"max_tokens":100}`
resp, err := http.Post(server.URL+"/v1/chat/completions", "application/json", strings.NewReader(body))
if err != nil {
t.Fatalf("request error: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status: %d", resp.StatusCode)
}
var oaiResp openAIResponse
json.NewDecoder(resp.Body).Decode(&oaiResp)
if oaiResp.ID != "chatcmpl-msg-test" {
t.Errorf("unexpected ID: %q", oaiResp.ID)
}
var content string
json.Unmarshal(oaiResp.Choices[0].Message.Content, &content)
if content != "Hi there!" {
t.Errorf("unexpected content: %q", content)
}
if oaiResp.Choices[0].FinishReason != "stop" {
t.Errorf("unexpected finish_reason: %q", oaiResp.Choices[0].FinishReason)
}
})
t.Run("fallthrough on GET", func(t *testing.T) {
var fallbackCalled bool
fallback := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fallbackCalled = true
w.WriteHeader(http.StatusOK)
})
provider := &tokenProvider{token: "test-token"}
handler := newConvertHandler("http://unused", provider, convertOpts{}, fallback)
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
resp, err := http.Get(server.URL + "/v1/chat/completions")
if err != nil {
t.Fatalf("request error: %v", err)
}
resp.Body.Close()
if !fallbackCalled {
t.Error("fallback should have been called for GET request")
}
})
t.Run("fallthrough on different path", func(t *testing.T) {
var fallbackCalled bool
fallback := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fallbackCalled = true
w.WriteHeader(http.StatusOK)
})
provider := &tokenProvider{token: "test-token"}
handler := newConvertHandler("http://unused", provider, convertOpts{}, fallback)
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
resp, err := http.Post(server.URL+"/v1/models", "application/json", strings.NewReader("{}"))
if err != nil {
t.Fatalf("request error: %v", err)
}
resp.Body.Close()
if !fallbackCalled {
t.Error("fallback should have been called for different path")
}
})
t.Run("streaming", func(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "no flusher", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
events := []string{
"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg-stream\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-20250514\",\"stop_reason\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0}}}\n",
"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n",
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hello\"}}\n",
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\" world\"}}\n",
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n",
"event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"input_tokens\":10,\"output_tokens\":5}}\n",
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n",
}
for _, e := range events {
w.Write([]byte(e))
flusher.Flush()
}
}))
t.Cleanup(backend.Close)
provider := &tokenProvider{token: "test-token"}
handler := newConvertHandler(backend.URL+v1Endpoint, provider, convertOpts{}, http.NotFoundHandler())
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
body := `{"model":"claude-sonnet-4-20250514","messages":[{"role":"user","content":"Hello"}],"max_tokens":100,"stream":true}`
resp, err := http.Post(server.URL+"/v1/chat/completions", "application/json", strings.NewReader(body))
if err != nil {
t.Fatalf("request error: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("unexpected status %d: %s", resp.StatusCode, body)
}
if ct := resp.Header.Get("Content-Type"); ct != "text/event-stream" {
t.Fatalf("unexpected content-type: %q", ct)
}
scanner := bufio.NewScanner(resp.Body)
var chunks []string
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "data: ") {
chunks = append(chunks, strings.TrimPrefix(line, "data: "))
}
}
if len(chunks) < 3 {
t.Fatalf("expected at least 3 chunks, got %d: %v", len(chunks), chunks)
}
var first openAIStreamChunk
json.Unmarshal([]byte(chunks[0]), &first)
if first.Choices[0].Delta.Role != "assistant" {
t.Errorf("first chunk should have role 'assistant': %+v", first)
}
var gotHello, gotWorld bool
for _, c := range chunks {
var chunk openAIStreamChunk
if json.Unmarshal([]byte(c), &chunk) == nil && len(chunk.Choices) > 0 {
if chunk.Choices[0].Delta.Content != nil {
if *chunk.Choices[0].Delta.Content == "Hello" {
gotHello = true
}
if *chunk.Choices[0].Delta.Content == " world" {
gotWorld = true
}
}
}
}
if !gotHello || !gotWorld {
t.Errorf("missing text chunks, gotHello=%v gotWorld=%v", gotHello, gotWorld)
}
last := chunks[len(chunks)-1]
if last != "[DONE]" {
t.Errorf("last chunk should be [DONE], got %q", last)
}
var finishChunk openAIStreamChunk
json.Unmarshal([]byte(chunks[len(chunks)-2]), &finishChunk)
if len(finishChunk.Choices) > 0 && finishChunk.Choices[0].FinishReason != nil {
if *finishChunk.Choices[0].FinishReason != "stop" {
t.Errorf("unexpected finish_reason: %q", *finishChunk.Choices[0].FinishReason)
}
}
})
t.Run("model mapping", func(t *testing.T) {
var gotModel string
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var antReq anthropicRequest
json.NewDecoder(r.Body).Decode(&antReq)
gotModel = antReq.Model
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(anthropicResponse{
ID: "msg-map",
Type: "message",
Role: "assistant",
Content: []contentBlock{{Type: "text", Text: "Hi"}},
Model: "claude-sonnet-4-20250514",
StopReason: "end_turn",
Usage: anthropicUsage{InputTokens: 5, OutputTokens: 2},
})
}))
t.Cleanup(backend.Close)
provider := &tokenProvider{token: "test-token"}
handler := newConvertHandler(backend.URL+v1Endpoint, provider, convertOpts{
modelMap: map[string]string{"gpt-4o": "claude-sonnet-4-20250514"},
}, http.NotFoundHandler())
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
body := `{"model":"gpt-4o","messages":[{"role":"user","content":"Hello"}],"max_tokens":100}`
resp, err := http.Post(server.URL+"/v1/chat/completions", "application/json", strings.NewReader(body))
if err != nil {
t.Fatalf("request error: %v", err)
}
resp.Body.Close()
if gotModel != "claude-sonnet-4-20250514" {
t.Errorf("model not mapped: got %q", gotModel)
}
})
t.Run("omit and add fields", func(t *testing.T) {
var gotBody map[string]any
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewDecoder(r.Body).Decode(&gotBody)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(anthropicResponse{
ID: "msg-fields",
Type: "message",
Role: "assistant",
Content: []contentBlock{{Type: "text", Text: "ok"}},
Model: "claude-sonnet-4-20250514",
StopReason: "end_turn",
Usage: anthropicUsage{InputTokens: 5, OutputTokens: 2},
})
}))
t.Cleanup(backend.Close)
provider := &tokenProvider{token: "test-token"}
handler := newConvertHandler(backend.URL+v1Endpoint, provider, convertOpts{
omitFields: []string{"model"},
addFields: map[string]string{"anthropic_version": "2023-06-01"},
}, http.NotFoundHandler())
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
body := `{"model":"claude-opus-4-6","messages":[{"role":"user","content":"Hello"}],"max_tokens":100}`
resp, err := http.Post(server.URL+"/v1/chat/completions", "application/json", strings.NewReader(body))
if err != nil {
t.Fatalf("request error: %v", err)
}
resp.Body.Close()
if _, ok := gotBody["model"]; ok {
t.Error("model field should have been omitted")
}
if v, ok := gotBody["anthropic_version"]; !ok || v != "2023-06-01" {
t.Errorf("anthropic_version field missing or wrong: %v", gotBody["anthropic_version"])
}
})
}