-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathapi_test.go
More file actions
870 lines (785 loc) · 23.1 KB
/
Copy pathapi_test.go
File metadata and controls
870 lines (785 loc) · 23.1 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
package integration_test
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/privapps/github-copilot-svcs/internal"
)
var (
testServer *internal.Server
baseURL string
cleanup func()
)
// TestMain sets up and tears down the test server for all integration tests
func TestMain(m *testing.M) {
// Set up test server
var err error
testServer, baseURL, cleanup, err = setupTestServer()
if err != nil {
fmt.Printf("Failed to setup test server: %v\n", err)
os.Exit(1)
}
// Wait for server to be ready
if !waitForServer(baseURL, 15*time.Second) {
cleanup()
fmt.Println("Server failed to start within timeout")
os.Exit(1)
}
fmt.Printf("Test server ready at %s\n", baseURL)
// Run tests
code := m.Run()
// Cleanup
cleanup()
os.Exit(code)
}
func TestHealthEndpoint(t *testing.T) {
tests := []struct {
name string
endpoint string
expectedStatus int
expectedFields []string
}{
{
name: "basic health check",
endpoint: "/health",
expectedStatus: http.StatusOK,
expectedFields: []string{"status", "timestamp", "version"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resp, err := http.Get(baseURL + tt.endpoint)
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.expectedStatus {
t.Errorf("Expected status %d, got %d", tt.expectedStatus, resp.StatusCode)
}
// Check response body is valid JSON with expected fields
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
t.Errorf("Failed to decode JSON response: %v", err)
return
}
for _, field := range tt.expectedFields {
if _, exists := result[field]; !exists {
t.Errorf("Expected field '%s' not found in response", field)
}
}
// Verify status is "healthy"
if status, ok := result["status"].(string); !ok || status != "healthy" {
t.Errorf("Expected status 'healthy', got %v", result["status"])
}
})
}
}
func TestModelsEndpoint(t *testing.T) {
tests := []struct {
name string
method string
endpoint string
expectedStatus int
checkJSON bool
expectedFields []string
}{
{
name: "get models list",
method: "GET",
endpoint: "/v1/models",
expectedStatus: http.StatusOK,
checkJSON: true,
expectedFields: []string{"object", "data"},
},
{
name: "models endpoint with POST method",
method: "POST",
endpoint: "/v1/models",
expectedStatus: http.StatusOK, // Models endpoint accepts POST
checkJSON: true,
expectedFields: []string{"object", "data"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest(tt.method, baseURL+tt.endpoint, http.NoBody)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.expectedStatus {
body, _ := io.ReadAll(resp.Body)
t.Errorf("Expected status %d, got %d. Response: %s", tt.expectedStatus, resp.StatusCode, string(body))
}
if tt.checkJSON {
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
t.Errorf("Failed to decode JSON response: %v", err)
return
}
for _, field := range tt.expectedFields {
if _, exists := result[field]; !exists {
t.Errorf("Expected field '%s' not found in response", field)
}
}
// Check that data is an array
if data, ok := result["data"].([]interface{}); !ok {
t.Errorf("Expected 'data' to be an array, got %T", result["data"])
} else if len(data) == 0 {
t.Log("Note: Models list is empty - this may be expected in test environment")
}
}
})
}
}
func TestChatCompletionsEndpoint(t *testing.T) {
tests := []struct {
name string
method string
endpoint string
body string
expectedStatus int
contentType string
}{
{
name: "chat completions with empty body",
method: "POST",
endpoint: "/v1/chat/completions",
body: "",
expectedStatus: http.StatusBadRequest,
contentType: "application/json",
},
{
name: "chat completions with invalid JSON",
method: "POST",
endpoint: "/v1/chat/completions",
body: `{"invalid": json}`,
expectedStatus: http.StatusBadRequest,
contentType: "application/json",
},
{
name: "chat completions with wrong method",
method: "GET",
endpoint: "/v1/chat/completions",
body: "",
expectedStatus: http.StatusMethodNotAllowed,
contentType: "application/json",
},
{
name: "chat completions with basic valid request",
method: "POST",
endpoint: "/v1/chat/completions",
body: `{"model":"gpt-4","messages":[{"role":"user","content":"test"}]}`,
expectedStatus: http.StatusUnauthorized, // Should be 401 if auth is missing
contentType: "application/json",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var body io.Reader
if tt.body != "" {
body = strings.NewReader(tt.body)
}
req, err := http.NewRequest(tt.method, baseURL+tt.endpoint, body)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
if tt.contentType != "" {
req.Header.Set("Content-Type", tt.contentType)
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.expectedStatus {
respBody, _ := io.ReadAll(resp.Body)
t.Errorf("Expected status %d, got %d. Response: %s", tt.expectedStatus, resp.StatusCode, string(respBody))
}
})
}
}
// TestHeaderForwardingProxy checks correct forwarding and defaulting of Content-Type, Accept, Accept-Encoding, TE headers
func TestHeaderForwardingProxy(t *testing.T) {
// --- Setup fake upstream server to capture proxied headers ---
var capturedHeaders http.Header
mux := http.NewServeMux()
mux.HandleFunc("/chat/completions", func(w http.ResponseWriter, r *http.Request) {
capturedHeaders = r.Header.Clone()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"ok":true}`))
})
ts := httptest.NewServer(mux)
defer ts.Close()
// Point the proxy at our fake upstream
internal.SetCopilotAPIBase(ts.URL)
defer internal.ResetCopilotAPIBase()
// Patch config to point upstream base URLs to our fake server
cfg := &internal.Config{
Port: 0,
CopilotToken: "token",
ExpiresAt: time.Now().Add(1 * time.Hour).Unix(),
AllowedModels: []string{"gpt-4"},
}
internal.SetDefaultTimeouts(cfg)
internal.SetDefaultHeaders(cfg)
internal.SetDefaultCORS(cfg)
httpClient := &http.Client{Transport: &http.Transport{}}
proxy := internal.NewProxyService(cfg, httpClient, internal.NewAuthService(httpClient), internal.NewWorkerPool(1))
srv := httptest.NewServer(proxy.Handler())
defer srv.Close()
cases := []struct {
name string
headers map[string]string
wantExpected map[string]string
}{
{
name: "all client headers set",
headers: map[string]string{
"Content-Type": "custom/type",
"Accept": "foo/bar",
"Accept-Encoding": "gzip, deflate",
"TE": "trailers",
},
wantExpected: map[string]string{
"Content-Type": "custom/type",
"Accept": "foo/bar",
"Accept-Encoding": "gzip, deflate",
"TE": "trailers",
},
},
{
name: "content-type only",
headers: map[string]string{
"Content-Type": "foo/baz",
},
wantExpected: map[string]string{
"Content-Type": "foo/baz",
"Accept": "application/json",
},
},
{
name: "accept only",
headers: map[string]string{
"Accept": "bar/foo",
},
wantExpected: map[string]string{
"Content-Type": "application/json",
"Accept": "bar/foo",
},
},
{
name: "neither set (default both)",
headers: map[string]string{},
wantExpected: map[string]string{
"Content-Type": "application/json",
"Accept": "application/json",
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
capturedHeaders = nil // Reset
jsonBody := `{"model":"gpt-4","messages":[{"role":"user","content":"test"}]}`
client := &http.Client{}
req, err := http.NewRequest("POST", srv.URL+"/v1/chat/completions", strings.NewReader(jsonBody))
if err != nil {
t.Fatalf("new req err: %v", err)
}
for k, v := range tc.headers {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("proxy req failed: %v", err)
}
io.ReadAll(resp.Body)
resp.Body.Close()
for wantKey, wantVal := range tc.wantExpected {
got := capturedHeaders.Get(wantKey)
if got != wantVal {
t.Errorf("expected header %q to be %q, got %q. All headers: %+v", wantKey, wantVal, got, capturedHeaders)
}
}
// TE should not be forwarded unless explicitly set by client.
// Note: Accept-Encoding may be added automatically by Go's HTTP client.
if _, ok := tc.headers["TE"]; !ok {
if capturedHeaders.Get("TE") != "" {
t.Errorf("expected header %q absent, got %q. All headers: %+v", "TE", capturedHeaders.Get("TE"), capturedHeaders)
}
}
})
}
}
// TestResponsesEndpoint tests the /v1/responses endpoint for GPT-5.x models
func TestResponsesEndpoint(t *testing.T) {
tests := []struct {
name string
method string
endpoint string
body string
expectedStatus int
contentType string
}{
{
name: "responses with empty body",
method: "POST",
endpoint: "/v1/responses",
body: "",
expectedStatus: http.StatusBadRequest,
contentType: "application/json",
},
{
name: "responses with invalid JSON",
method: "POST",
endpoint: "/v1/responses",
body: `{"invalid": json}`,
expectedStatus: http.StatusBadRequest,
contentType: "application/json",
},
{
name: "responses with wrong method",
method: "GET",
endpoint: "/v1/responses",
body: "",
expectedStatus: http.StatusMethodNotAllowed,
contentType: "application/json",
},
{
name: "responses with basic valid request",
method: "POST",
endpoint: "/v1/responses",
body: `{"model":"gpt-5.6-luna","input":"test","max_output_tokens":50}`,
expectedStatus: http.StatusUnauthorized, // Should be 401 if auth is missing
contentType: "application/json",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var body io.Reader
if tt.body != "" {
body = strings.NewReader(tt.body)
}
req, err := http.NewRequest(tt.method, baseURL+tt.endpoint, body)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
if tt.contentType != "" {
req.Header.Set("Content-Type", tt.contentType)
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.expectedStatus {
respBody, _ := io.ReadAll(resp.Body)
t.Errorf("Expected status %d, got %d. Response: %s", tt.expectedStatus, resp.StatusCode, string(respBody))
}
})
}
}
func TestCORSHeaders(t *testing.T) {
tests := []struct {
name string
endpoint string
origin string
method string
expectedStatus int
checkCORS bool
}{
{
name: "CORS preflight request",
endpoint: "/v1/models",
origin: "http://localhost:3000",
method: "OPTIONS",
expectedStatus: http.StatusOK,
checkCORS: true,
},
{
name: "CORS actual request",
endpoint: "/health",
origin: "http://localhost:3000",
method: "GET",
expectedStatus: http.StatusOK,
checkCORS: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest(tt.method, baseURL+tt.endpoint, http.NoBody)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
if tt.origin != "" {
req.Header.Set("Origin", tt.origin)
}
if tt.method == "OPTIONS" {
req.Header.Set("Access-Control-Request-Method", "GET")
req.Header.Set("Access-Control-Request-Headers", "Content-Type")
}
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.expectedStatus {
t.Errorf("Expected status %d, got %d", tt.expectedStatus, resp.StatusCode)
}
if tt.checkCORS {
// Check for CORS headers
allowOrigin := resp.Header.Get("Access-Control-Allow-Origin")
if allowOrigin == "" {
t.Error("Expected Access-Control-Allow-Origin header")
}
if tt.method == "OPTIONS" {
allowMethods := resp.Header.Get("Access-Control-Allow-Methods")
if allowMethods == "" {
t.Error("Expected Access-Control-Allow-Methods header for preflight")
}
}
}
})
}
}
func TestErrorConditions(t *testing.T) {
tests := []struct {
name string
endpoint string
expectedStatus int
}{
{
name: "nonexistent endpoint",
endpoint: "/nonexistent",
expectedStatus: http.StatusNotFound,
},
{
name: "invalid path",
endpoint: "/v1/invalid",
expectedStatus: http.StatusNotFound,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resp, err := http.Get(baseURL + tt.endpoint)
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.expectedStatus {
t.Errorf("Expected status %d, got %d", tt.expectedStatus, resp.StatusCode)
}
})
}
}
func TestSecurityHeaders(t *testing.T) {
resp, err := http.Get(baseURL + "/health")
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
defer resp.Body.Close()
expectedHeaders := map[string]string{
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
}
for header, expectedValue := range expectedHeaders {
actualValue := resp.Header.Get(header)
if actualValue != expectedValue {
t.Errorf("Expected header %s to be '%s', got '%s'", header, expectedValue, actualValue)
}
}
}
func TestServerShutdown(t *testing.T) {
// This test verifies that the server can be gracefully shut down
// We'll create a separate server instance for this test
server, serverURL, shutdownFunc, err := setupTestServer()
if err != nil {
t.Fatalf("Failed to setup test server: %v", err)
}
// Wait for server to be ready
if !waitForServer(serverURL, 5*time.Second) {
shutdownFunc()
t.Fatal("Server failed to start within timeout")
}
// Make a request to ensure server is working
resp, err := http.Get(serverURL + "/health")
if err != nil {
shutdownFunc()
t.Fatalf("Failed to make request: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, resp.StatusCode)
}
// Shutdown the server
shutdownFunc()
// Verify server is no longer responding
time.Sleep(200 * time.Millisecond) // Give time for shutdown
resp2, err := http.Get(serverURL + "/health")
if resp2 != nil {
defer resp2.Body.Close()
}
if err == nil {
t.Error("Expected server to be shut down, but it's still responding")
}
_ = server // Use server variable to avoid unused warning
}
// setupTestServer creates a test server instance and returns cleanup function
func setupTestServer() (server *internal.Server, baseURL string, cleanup func(), err error) {
// Find an available port
listener, err := net.Listen("tcp", ":0")
if err != nil {
return nil, "", nil, fmt.Errorf("failed to find available port: %w", err)
}
port := listener.Addr().(*net.TCPAddr).Port
listener.Close()
// Create test configuration with proper defaults
cfg := &internal.Config{
Port: port,
}
// Set default headers to prevent validation errors
internal.SetDefaultHeaders(cfg)
internal.SetDefaultCORS(cfg)
internal.SetDefaultTimeouts(cfg)
// Create HTTP client for the server
httpClient := &http.Client{
Timeout: 30 * time.Second,
}
// Create server instance
server = internal.NewServer(cfg, httpClient)
baseURL = fmt.Sprintf("http://localhost:%d", port)
// Start server in background goroutine
serverErrCh := make(chan error, 1)
go func() {
// For testing, we'll just call Start() which blocks
if err := server.Start(); err != nil && err != http.ErrServerClosed {
serverErrCh <- err
}
}()
cleanup = func() {
if server != nil {
if err := server.Stop(); err != nil {
fmt.Printf("Error stopping server: %v\n", err)
}
}
// Give server time to shutdown gracefully
time.Sleep(200 * time.Millisecond)
}
// Check for immediate startup errors
select {
case err := <-serverErrCh:
cleanup()
return nil, "", nil, fmt.Errorf("server failed to start: %w", err)
case <-time.After(1 * time.Second):
// Server seems to be starting OK
}
return server, baseURL, cleanup, nil
}
// waitForServer waits for the server to be ready to accept connections
func waitForServer(baseURL string, timeout time.Duration) bool {
client := &http.Client{Timeout: 1 * time.Second}
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
resp, err := client.Get(baseURL + "/health")
if err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return true
}
}
time.Sleep(200 * time.Millisecond)
}
return false
}
// TestVisionSupport tests that the proxy correctly handles vision/image requests
func TestVisionSupport(t *testing.T) {
// Create a small 1x1 transparent PNG image for testing
pngData, _ := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==")
imageDataURL := "data:image/png;base64," + base64.StdEncoding.EncodeToString(pngData)
tests := []struct {
name string
payload string
expectedStatus int
description string
}{
{
name: "vision request with image_url",
payload: fmt.Sprintf(`{
"model": "gpt-4o",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image"},
{"type": "image_url", "image_url": {"url": "%s"}}
]
}],
"max_tokens": 100
}`, imageDataURL),
expectedStatus: http.StatusUnauthorized, // Will fail auth, but should accept the payload structure
description: "Multi-part content with image should be accepted",
},
{
name: "vision request with base64 image",
payload: fmt.Sprintf(`{
"model": "gpt-4o",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{"type": "image_url", "image_url": {"url": "%s", "detail": "high"}}
]
}],
"max_tokens": 200
}`, imageDataURL),
expectedStatus: http.StatusUnauthorized,
description: "Image with detail parameter should be accepted",
},
{
name: "text-only request still works",
payload: `{
"model": "gpt-4o",
"messages": [{
"role": "user",
"content": "Hello"
}],
"max_tokens": 50
}`,
expectedStatus: http.StatusUnauthorized,
description: "Backward compatibility: text-only content should still work",
},
{
name: "mixed text and vision in same conversation",
payload: fmt.Sprintf(`{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "Hello"
},
{
"role": "assistant",
"content": "Hi! How can I help?"
},
{
"role": "user",
"content": [
{"type": "text", "text": "Look at this"},
{"type": "image_url", "image_url": {"url": "%s"}}
]
}
],
"max_tokens": 150
}`, imageDataURL),
expectedStatus: http.StatusUnauthorized,
description: "Mixed text and vision messages should be accepted",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest("POST", baseURL+"/v1/chat/completions", strings.NewReader(tt.payload))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
defer resp.Body.Close()
// We expect 401 because we don't have auth in tests
// But the important part is that the request is not rejected as "bad request"
if resp.StatusCode != tt.expectedStatus {
body, _ := io.ReadAll(resp.Body)
t.Errorf("%s: Expected status %d, got %d. Response: %s",
tt.description, tt.expectedStatus, resp.StatusCode, string(body))
}
// If we got a 400, it means the payload structure was rejected
if resp.StatusCode == http.StatusBadRequest {
body, _ := io.ReadAll(resp.Body)
t.Errorf("%s: Vision payload was rejected as bad request. Response: %s",
tt.description, string(body))
}
})
}
}
// TestVisionPayloadValidation ensures vision payloads pass JSON validation
func TestVisionPayloadValidation(t *testing.T) {
pngData, _ := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==")
imageDataURL := "data:image/png;base64," + base64.StdEncoding.EncodeToString(pngData)
tests := []struct {
name string
payload string
shouldPass bool
description string
}{
{
name: "valid vision payload",
payload: fmt.Sprintf(`{
"model": "gpt-4o",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "test"},
{"type": "image_url", "image_url": {"url": "%s"}}
]
}]
}`, imageDataURL),
shouldPass: true,
description: "Valid vision payload should pass validation",
},
{
name: "missing model field",
payload: `{"messages": [{"role": "user", "content": "test"}]}`,
shouldPass: true,
description: "Missing model field results in empty model",
},
{
name: "invalid json",
payload: `{"model": "gpt-4o", invalid}`,
shouldPass: false,
description: "Invalid JSON should fail",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest("POST", baseURL+"/v1/chat/completions", strings.NewReader(tt.payload))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to make request: %v", err)
}
defer resp.Body.Close()
isBadRequest := resp.StatusCode == http.StatusBadRequest
if tt.shouldPass && isBadRequest {
body, _ := io.ReadAll(resp.Body)
t.Errorf("%s: Expected to pass, got 400. Response: %s", tt.description, string(body))
}
if !tt.shouldPass && !isBadRequest {
t.Errorf("%s: Expected to fail validation, got status %d", tt.description, resp.StatusCode)
}
})
}
}