-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathopenapi_test.go
More file actions
713 lines (591 loc) · 16.8 KB
/
Copy pathopenapi_test.go
File metadata and controls
713 lines (591 loc) · 16.8 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
// Copyright 2025 coregx. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package fursy
import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
// Test types for OpenAPI generation.
type testUser struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
}
func TestOpenAPI_GenerateBasic(t *testing.T) {
router := New()
router.Handle("GET", "/users", func(c *Context) error {
return c.String(200, "users")
})
router.Handle("POST", "/users", func(c *Context) error {
return c.String(201, "created")
})
doc, err := router.GenerateOpenAPI(Info{
Title: "Test API",
Version: "1.0.0",
})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
if doc.OpenAPI != "3.1.0" {
t.Errorf("Expected OpenAPI version 3.1.0, got %s", doc.OpenAPI)
}
if doc.Info.Title != "Test API" {
t.Errorf("Expected title 'Test API', got %s", doc.Info.Title)
}
if doc.Info.Version != "1.0.0" {
t.Errorf("Expected version '1.0.0', got %s", doc.Info.Version)
}
// Check paths - GET and POST to /users should be in one PathItem.
if len(doc.Paths) != 1 {
t.Errorf("Expected 1 path, got %d", len(doc.Paths))
}
// Check /users GET and POST.
usersPath, exists := doc.Paths["/users"]
if !exists {
t.Fatal("/users path not found")
}
if usersPath.Get == nil {
t.Error("/users GET operation not found")
}
if usersPath.Post == nil {
t.Error("/users POST operation not found")
}
}
func TestOpenAPI_WithInfo(t *testing.T) {
router := New()
router.WithInfo(Info{
Title: "My API",
Version: "2.0.0",
Description: "Test description",
})
router.Handle("GET", "/test", func(_ *Context) error {
return nil
})
doc, err := router.GenerateOpenAPI(Info{
Title: "Ignored",
Version: "0.0.0",
})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
// Should use router info, not parameter.
if doc.Info.Title != "My API" {
t.Errorf("Expected title 'My API', got %s", doc.Info.Title)
}
if doc.Info.Version != "2.0.0" {
t.Errorf("Expected version '2.0.0', got %s", doc.Info.Version)
}
if doc.Info.Description != "Test description" {
t.Errorf("Expected description 'Test description', got %s", doc.Info.Description)
}
}
func TestOpenAPI_WithServer(t *testing.T) {
router := New()
router.WithServer(Server{
URL: "https://api.example.com",
Description: "Production server",
})
router.WithServer(Server{
URL: "https://staging.example.com",
Description: "Staging server",
})
router.Handle("GET", "/test", func(_ *Context) error {
return nil
})
doc, err := router.GenerateOpenAPI(Info{
Title: "Test",
Version: "1.0.0",
})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
if len(doc.Servers) != 2 {
t.Fatalf("Expected 2 servers, got %d", len(doc.Servers))
}
if doc.Servers[0].URL != "https://api.example.com" {
t.Errorf("Expected first server URL 'https://api.example.com', got %s", doc.Servers[0].URL)
}
if doc.Servers[1].URL != "https://staging.example.com" {
t.Errorf("Expected second server URL 'https://staging.example.com', got %s", doc.Servers[1].URL)
}
}
func TestOpenAPI_HandleWithOptions(t *testing.T) {
router := New()
router.HandleWithOptions(http.MethodGet, "/users/:id", func(_ *Context) error {
return nil
}, &RouteOptions{
Summary: "Get user by ID",
Description: "Returns a single user",
Tags: []string{"users"},
OperationID: "getUserByID",
})
doc, err := router.GenerateOpenAPI(Info{
Title: "Test",
Version: "1.0.0",
})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
// Path should be converted to OpenAPI format.
usersPath, exists := doc.Paths["/users/{id}"]
if !exists {
t.Fatal("/users/{id} path not found")
}
if usersPath.Get == nil {
t.Fatal("/users/{id} GET operation not found")
}
op := usersPath.Get
if op.Summary != "Get user by ID" {
t.Errorf("Expected summary 'Get user by ID', got %s", op.Summary)
}
if op.Description != "Returns a single user" {
t.Errorf("Expected description 'Returns a single user', got %s", op.Description)
}
if len(op.Tags) != 1 || op.Tags[0] != "users" {
t.Errorf("Expected tags ['users'], got %v", op.Tags)
}
if op.OperationID != "getUserByID" {
t.Errorf("Expected operationId 'getUserByID', got %s", op.OperationID)
}
}
func TestOpenAPI_PathConversion(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "static path",
input: "/users",
expected: "/users",
},
{
name: "single parameter",
input: "/users/:id",
expected: "/users/{id}",
},
{
name: "multiple parameters",
input: "/users/:userId/posts/:postId",
expected: "/users/{userId}/posts/{postId}",
},
{
name: "wildcard",
input: "/files/*path",
expected: "/files/{path}",
},
{
name: "mixed",
input: "/api/v1/users/:id",
expected: "/api/v1/users/{id}",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := convertPathToOpenAPI(tt.input)
if result != tt.expected {
t.Errorf("convertPathToOpenAPI(%q) = %q, want %q", tt.input, result, tt.expected)
}
})
}
}
func TestOpenAPI_SchemaGeneration(t *testing.T) {
tests := []struct {
name string
typ reflect.Type
expected *Schema
}{
{
name: "string",
typ: reflect.TypeOf(""),
expected: &Schema{
Type: "string",
},
},
{
name: "int",
typ: reflect.TypeOf(0),
expected: &Schema{
Type: "integer",
},
},
{
name: "bool",
typ: reflect.TypeOf(false),
expected: &Schema{
Type: "boolean",
},
},
{
name: "float64",
typ: reflect.TypeOf(0.0),
expected: &Schema{
Type: "number",
},
},
{
name: "slice",
typ: reflect.TypeOf([]string{}),
expected: &Schema{
Type: "array",
Items: &Schema{
Type: "string",
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := generateSchema(tt.typ)
if result.Type != tt.expected.Type {
t.Errorf("Type = %q, want %q", result.Type, tt.expected.Type)
}
if tt.expected.Items != nil {
if result.Items == nil {
t.Error("Expected Items to be set")
} else if result.Items.Type != tt.expected.Items.Type {
t.Errorf("Items.Type = %q, want %q", result.Items.Type, tt.expected.Items.Type)
}
}
})
}
}
func TestOpenAPI_SchemaGeneration_Struct(t *testing.T) {
schema := generateSchema(reflect.TypeOf(testUser{}))
if schema.Type != "object" {
t.Errorf("Expected type 'object', got %s", schema.Type)
}
if schema.Properties == nil {
t.Fatal("Expected Properties to be set")
}
// Check id field.
idSchema, exists := schema.Properties["id"]
if !exists {
t.Error("Expected 'id' property")
} else if idSchema.Type != "integer" {
t.Errorf("Expected 'id' type 'integer', got %s", idSchema.Type)
}
// Check name field.
nameSchema, exists := schema.Properties["name"]
if !exists {
t.Error("Expected 'name' property")
} else if nameSchema.Type != "string" {
t.Errorf("Expected 'name' type 'string', got %s", nameSchema.Type)
}
// Check email field (omitempty).
emailSchema, exists := schema.Properties["email"]
if !exists {
t.Error("Expected 'email' property")
} else if emailSchema.Type != "string" {
t.Errorf("Expected 'email' type 'string', got %s", emailSchema.Type)
}
// Check required fields (should not include email with omitempty).
expectedRequired := []string{"id", "name"}
if !reflect.DeepEqual(schema.Required, expectedRequired) {
t.Errorf("Expected required %v, got %v", expectedRequired, schema.Required)
}
}
func TestOpenAPI_ProblemDetailsSchema(t *testing.T) {
router := New()
router.Handle("GET", "/test", func(_ *Context) error {
return nil
})
doc, err := router.GenerateOpenAPI(Info{
Title: "Test",
Version: "1.0.0",
})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
// Check that Problem schema is included.
problemSchema, exists := doc.Components.Schemas["Problem"]
if !exists {
t.Fatal("Problem schema not found in components")
}
if problemSchema.Type != "object" {
t.Errorf("Expected Problem type 'object', got %s", problemSchema.Type)
}
// Check required fields.
expectedRequired := []string{"type", "title", "status"}
if !reflect.DeepEqual(problemSchema.Required, expectedRequired) {
t.Errorf("Expected Problem required %v, got %v", expectedRequired, problemSchema.Required)
}
// Check that Problem response is included.
problemResponse, exists := doc.Components.Responses["Problem"]
if !exists {
t.Fatal("Problem response not found in components")
}
if problemResponse.Description != "RFC 9457 Problem Details" {
t.Errorf("Expected Problem response description 'RFC 9457 Problem Details', got %s", problemResponse.Description)
}
}
//nolint:nestif,gocritic // Test validation requires nested checks.
func TestOpenAPI_DefaultErrorResponses(t *testing.T) {
router := New()
router.Handle("GET", "/users", func(_ *Context) error {
return nil
})
doc, err := router.GenerateOpenAPI(Info{
Title: "Test",
Version: "1.0.0",
})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
usersPath := doc.Paths["/users"]
if usersPath.Get == nil {
t.Fatal("GET /users not found")
}
op := usersPath.Get
// Check 400 response.
resp400, exists := op.Responses["400"]
if !exists {
t.Error("Expected 400 response")
} else {
if resp400.Description != "Bad Request" {
t.Errorf("Expected 400 description 'Bad Request', got %s", resp400.Description)
}
content, exists := resp400.Content["application/problem+json"]
if !exists {
t.Error("Expected application/problem+json content type for 400")
} else if content.Schema.Ref != "#/components/schemas/Problem" {
t.Errorf("Expected 400 schema ref '#/components/schemas/Problem', got %s", content.Schema.Ref)
}
}
// Check 500 response.
resp500, exists := op.Responses["500"]
if !exists {
t.Error("Expected 500 response")
} else {
if resp500.Description != "Internal Server Error" {
t.Errorf("Expected 500 description 'Internal Server Error', got %s", resp500.Description)
}
}
}
func TestOpenAPI_AllHTTPMethods(t *testing.T) {
router := New()
router.Handle("GET", "/test", func(_ *Context) error { return nil })
router.Handle("POST", "/test", func(_ *Context) error { return nil })
router.Handle("PUT", "/test", func(_ *Context) error { return nil })
router.Handle("DELETE", "/test", func(_ *Context) error { return nil })
router.Handle("PATCH", "/test", func(_ *Context) error { return nil })
router.Handle("HEAD", "/test", func(_ *Context) error { return nil })
router.Handle("OPTIONS", "/test", func(_ *Context) error { return nil })
doc, err := router.GenerateOpenAPI(Info{
Title: "Test",
Version: "1.0.0",
})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
testPath := doc.Paths["/test"]
if testPath.Get == nil {
t.Error("GET operation not found")
}
if testPath.Post == nil {
t.Error("POST operation not found")
}
if testPath.Put == nil {
t.Error("PUT operation not found")
}
if testPath.Delete == nil {
t.Error("DELETE operation not found")
}
if testPath.Patch == nil {
t.Error("PATCH operation not found")
}
if testPath.Head == nil {
t.Error("HEAD operation not found")
}
if testPath.Options == nil {
t.Error("OPTIONS operation not found")
}
}
func TestOpenAPI_JSONMarshaling(t *testing.T) {
router := New()
router.WithInfo(Info{
Title: "Test API",
Version: "1.0.0",
})
router.Handle("GET", "/users", func(_ *Context) error {
return nil
})
doc, err := router.GenerateOpenAPI(Info{})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
// Test JSON marshaling.
data, err := json.Marshal(doc)
if err != nil {
t.Fatalf("json.Marshal failed: %v", err)
}
if len(data) == 0 {
t.Error("Expected non-empty JSON")
}
// Check that it's valid JSON.
var result map[string]any
if err := json.Unmarshal(data, &result); err != nil {
t.Fatalf("JSON unmarshaling failed: %v", err)
}
if result["openapi"] != "3.1.0" {
t.Errorf("Expected openapi '3.1.0', got %v", result["openapi"])
}
}
func TestRouter_ServeOpenAPI(t *testing.T) {
router := New()
router.WithInfo(Info{
Title: "Test API",
Version: "2.0.0",
Description: "API for testing",
})
router.Handle("GET", "/users", func(c *Context) error {
return c.String(200, "users")
})
router.Handle("POST", "/users", func(c *Context) error {
return c.String(201, "created")
})
// Serve OpenAPI spec.
router.ServeOpenAPI("/openapi.json")
// Test the endpoint.
req := httptest.NewRequest("GET", "/openapi.json", http.NoBody)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != 200 {
t.Errorf("Expected status 200, got %d", w.Code)
}
contentType := w.Header().Get("Content-Type")
if contentType != "application/json; charset=utf-8" {
t.Errorf("Expected Content-Type 'application/json; charset=utf-8', got %s", contentType)
}
// Verify it's valid OpenAPI JSON.
var doc OpenAPI
if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil {
t.Fatalf("Failed to unmarshal OpenAPI document: %v", err)
}
if doc.OpenAPI != "3.1.0" {
t.Errorf("Expected OpenAPI version '3.1.0', got %s", doc.OpenAPI)
}
if doc.Info.Title != "Test API" {
t.Errorf("Expected title 'Test API', got %s", doc.Info.Title)
}
if doc.Info.Version != "2.0.0" {
t.Errorf("Expected version '2.0.0', got %s", doc.Info.Version)
}
if doc.Info.Description != "API for testing" {
t.Errorf("Expected description 'API for testing', got %s", doc.Info.Description)
}
// Verify paths are included (/users + /openapi.json).
if len(doc.Paths) != 2 {
t.Errorf("Expected 2 paths, got %d", len(doc.Paths))
}
usersPath, exists := doc.Paths["/users"]
if !exists {
t.Error("/users path not found")
}
if usersPath.Get == nil {
t.Error("GET operation not found")
}
if usersPath.Post == nil {
t.Error("POST operation not found")
}
// Verify OpenAPI endpoint itself is documented.
_, exists = doc.Paths["/openapi.json"]
if !exists {
t.Error("/openapi.json path not found in spec")
}
}
func TestOpenAPI_WriteJSON(t *testing.T) {
router := New()
router.WithInfo(Info{
Title: "Write JSON Test",
Version: "1.0.0",
})
router.Handle("GET", "/ping", func(_ *Context) error {
return nil
})
doc, err := router.GenerateOpenAPI(Info{})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
w := httptest.NewRecorder()
if err := doc.WriteJSON(w); err != nil {
t.Fatalf("WriteJSON failed: %v", err)
}
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
contentType := w.Header().Get("Content-Type")
if contentType != "application/json; charset=utf-8" {
t.Errorf("expected Content-Type 'application/json; charset=utf-8', got %q", contentType)
}
if w.Body.Len() == 0 {
t.Error("expected non-empty body")
}
// Verify valid JSON with expected openapi version.
var result map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatalf("body is not valid JSON: %v", err)
}
if result["openapi"] != "3.1.0" {
t.Errorf("expected openapi '3.1.0', got %v", result["openapi"])
}
info, ok := result["info"].(map[string]any)
if !ok {
t.Fatal("expected info object in JSON")
}
if info["title"] != "Write JSON Test" {
t.Errorf("expected title 'Write JSON Test', got %v", info["title"])
}
}
func TestOpenAPI_WriteYAML(t *testing.T) {
router := New()
router.Handle("GET", "/test", func(_ *Context) error {
return nil
})
doc, err := router.GenerateOpenAPI(Info{
Title: "YAML Test",
Version: "1.0.0",
})
if err != nil {
t.Fatalf("GenerateOpenAPI failed: %v", err)
}
w := httptest.NewRecorder()
err = doc.WriteYAML(w)
// WriteYAML is not yet implemented and must return an error.
if err == nil {
t.Fatal("expected error from WriteYAML, got nil")
}
if err.Error() != "YAML output not yet implemented (requires external dependency)" {
t.Errorf("unexpected error message: %q", err.Error())
}
}
func TestRouter_ServeOpenAPI_DefaultInfo(t *testing.T) {
router := New()
router.Handle("GET", "/test", func(_ *Context) error {
return nil
})
// Serve OpenAPI spec without configuring Info.
router.ServeOpenAPI("/api-spec.json")
// Test the endpoint.
req := httptest.NewRequest("GET", "/api-spec.json", http.NoBody)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != 200 {
t.Errorf("Expected status 200, got %d", w.Code)
}
// Verify it uses default info.
var doc OpenAPI
if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil {
t.Fatalf("Failed to unmarshal OpenAPI document: %v", err)
}
if doc.Info.Title != "API Documentation" {
t.Errorf("Expected default title 'API Documentation', got %s", doc.Info.Title)
}
if doc.Info.Version != "1.0.0" {
t.Errorf("Expected default version '1.0.0', got %s", doc.Info.Version)
}
}