-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshiftapi_test.go
More file actions
5811 lines (4992 loc) · 167 KB
/
shiftapi_test.go
File metadata and controls
5811 lines (4992 loc) · 167 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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package shiftapi_test
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/textproto"
"slices"
"strings"
"testing"
"github.com/fcjr/shiftapi"
"github.com/getkin/kin-openapi/openapi3"
"github.com/go-playground/validator/v10"
)
// --- Test types ---
type Person struct {
Name string `json:"name"`
}
type Greeting struct {
Hello string `json:"hello"`
}
type Status struct {
OK bool `json:"ok"`
}
type Item struct {
ID string `json:"id"`
Name string `json:"name"`
}
type Empty struct{}
// --- Helpers ---
func newTestAPI(t *testing.T) *shiftapi.API {
t.Helper()
return shiftapi.New()
}
func doRequest(t *testing.T, api http.Handler, method, path string, body string) *http.Response {
t.Helper()
var bodyReader io.Reader
if body != "" {
bodyReader = strings.NewReader(body)
}
req := httptest.NewRequest(method, path, bodyReader)
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
rec := httptest.NewRecorder()
api.ServeHTTP(rec, req)
return rec.Result()
}
func decodeJSON[T any](t *testing.T, resp *http.Response) T {
t.Helper()
var v T
defer func() { _ = resp.Body.Close() }()
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
t.Fatalf("failed to decode response body: %v", err)
}
return v
}
func readBody(t *testing.T, resp *http.Response) string {
t.Helper()
defer func() { _ = resp.Body.Close() }()
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("failed to read response body: %v", err)
}
return string(b)
}
// --- API creation tests ---
func TestNew(t *testing.T) {
api := shiftapi.New()
if api == nil {
t.Fatal("New() returned nil")
}
}
func TestNewWithOptions(t *testing.T) {
api := shiftapi.New(
shiftapi.WithInfo(shiftapi.Info{
Title: "Test API",
Description: "A test API",
Version: "1.0.0",
}),
)
spec := api.Spec()
if spec.Info == nil {
t.Fatal("expected spec.Info to be set")
}
if spec.Info.Title != "Test API" {
t.Errorf("expected title %q, got %q", "Test API", spec.Info.Title)
}
if spec.Info.Description != "A test API" {
t.Errorf("expected description %q, got %q", "A test API", spec.Info.Description)
}
if spec.Info.Version != "1.0.0" {
t.Errorf("expected version %q, got %q", "1.0.0", spec.Info.Version)
}
}
func TestWithInfoContact(t *testing.T) {
api := shiftapi.New(shiftapi.WithInfo(shiftapi.Info{
Title: "Test",
Contact: &shiftapi.Contact{
Name: "Dev",
URL: "https://example.com",
Email: "dev@example.com",
},
}))
spec := api.Spec()
if spec.Info.Contact == nil {
t.Fatal("expected contact to be set")
}
if spec.Info.Contact.Name != "Dev" {
t.Errorf("expected contact name %q, got %q", "Dev", spec.Info.Contact.Name)
}
if spec.Info.Contact.URL != "https://example.com" {
t.Errorf("expected contact URL %q, got %q", "https://example.com", spec.Info.Contact.URL)
}
if spec.Info.Contact.Email != "dev@example.com" {
t.Errorf("expected contact email %q, got %q", "dev@example.com", spec.Info.Contact.Email)
}
}
func TestWithInfoLicense(t *testing.T) {
api := shiftapi.New(shiftapi.WithInfo(shiftapi.Info{
Title: "Test",
License: &shiftapi.License{
Name: "MIT",
URL: "https://opensource.org/licenses/MIT",
},
}))
spec := api.Spec()
if spec.Info.License == nil {
t.Fatal("expected license to be set")
}
if spec.Info.License.Name != "MIT" {
t.Errorf("expected license name %q, got %q", "MIT", spec.Info.License.Name)
}
}
func TestWithExternalDocs(t *testing.T) {
api := shiftapi.New(shiftapi.WithExternalDocs(shiftapi.ExternalDocs{
Description: "More info",
URL: "https://example.com/docs",
}))
spec := api.Spec()
if spec.ExternalDocs == nil {
t.Fatal("expected ExternalDocs to be set")
}
if spec.ExternalDocs.Description != "More info" {
t.Errorf("expected description %q, got %q", "More info", spec.ExternalDocs.Description)
}
if spec.ExternalDocs.URL != "https://example.com/docs" {
t.Errorf("expected URL %q, got %q", "https://example.com/docs", spec.ExternalDocs.URL)
}
}
// --- Built-in endpoint tests ---
func TestServeOpenAPISpec(t *testing.T) {
api := shiftapi.New(shiftapi.WithInfo(shiftapi.Info{
Title: "Spec Test",
Version: "2.0",
}))
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
resp := doRequest(t, api, http.MethodGet, "/openapi.json", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
if ct := resp.Header.Get("Content-Type"); ct != "application/json; charset=utf-8" {
t.Errorf("expected Content-Type application/json; charset=utf-8, got %q", ct)
}
var spec map[string]any
if err := json.NewDecoder(resp.Body).Decode(&spec); err != nil {
t.Fatalf("failed to decode spec: %v", err)
}
_ = resp.Body.Close()
if spec["openapi"] != "3.1" {
t.Errorf("expected openapi 3.1, got %v", spec["openapi"])
}
info, ok := spec["info"].(map[string]any)
if !ok {
t.Fatal("expected info in spec")
}
if info["title"] != "Spec Test" {
t.Errorf("expected title %q, got %v", "Spec Test", info["title"])
}
}
func TestServeDocs(t *testing.T) {
api := shiftapi.New(shiftapi.WithInfo(shiftapi.Info{Title: "Docs Test"}))
resp := doRequest(t, api, http.MethodGet, "/docs", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
body := readBody(t, resp)
if !strings.Contains(body, "Scalar") {
t.Error("expected docs page to contain 'Scalar'")
}
if !strings.Contains(body, "Docs Test") {
t.Error("expected docs page to contain the API title")
}
}
func TestRootRedirectsToDocs(t *testing.T) {
api := shiftapi.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
api.ServeHTTP(rec, req)
resp := rec.Result()
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusTemporaryRedirect {
t.Fatalf("expected 307, got %d", resp.StatusCode)
}
loc := resp.Header.Get("Location")
if loc != "/docs" {
t.Errorf("expected redirect to /docs, got %q", loc)
}
}
// --- POST handler tests ---
func TestPostHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /greet", func(r *http.Request, in *Person) (*Greeting, error) {
return &Greeting{Hello: in.Name}, nil
})
resp := doRequest(t, api, http.MethodPost, "/greet", `{"name":"alice"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
greeting := decodeJSON[Greeting](t, resp)
if greeting.Hello != "alice" {
t.Errorf("expected Hello=alice, got %q", greeting.Hello)
}
}
func TestPostHandlerInvalidBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /greet", func(r *http.Request, in *Person) (*Greeting, error) {
return &Greeting{Hello: in.Name}, nil
})
resp := doRequest(t, api, http.MethodPost, "/greet", `not json`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", resp.StatusCode)
}
}
func TestPostHandlerEmptyBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /greet", func(r *http.Request, in *Person) (*Greeting, error) {
return &Greeting{Hello: in.Name}, nil
})
resp := doRequest(t, api, http.MethodPost, "/greet", "")
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", resp.StatusCode)
}
}
func TestPostHandlerEmptyJSONObject(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /person", func(r *http.Request, in *ValidatedPerson) (*ValidatedPerson, error) {
return in, nil
})
resp := doRequest(t, api, http.MethodPost, "/person", `{}`)
if resp.StatusCode != http.StatusUnprocessableEntity {
t.Fatalf("expected 422, got %d", resp.StatusCode)
}
}
// --- GET handler tests ---
func TestGetHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
resp := doRequest(t, api, http.MethodGet, "/health", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
status := decodeJSON[Status](t, resp)
if !status.OK {
t.Error("expected OK=true")
}
}
func TestGetHandlerWithPathParam(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /items/{id}", func(r *http.Request, _ struct{}) (*Item, error) {
return &Item{ID: r.PathValue("id"), Name: "widget"}, nil
})
resp := doRequest(t, api, http.MethodGet, "/items/abc123", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
item := decodeJSON[Item](t, resp)
if item.ID != "abc123" {
t.Errorf("expected ID=abc123, got %q", item.ID)
}
if item.Name != "widget" {
t.Errorf("expected Name=widget, got %q", item.Name)
}
}
// --- PUT handler tests ---
func TestPutHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "PUT /items/{id}", func(r *http.Request, in *Item) (*Item, error) {
in.ID = r.PathValue("id")
return in, nil
})
resp := doRequest(t, api, http.MethodPut, "/items/42", `{"name":"updated"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
item := decodeJSON[Item](t, resp)
if item.ID != "42" {
t.Errorf("expected ID=42, got %q", item.ID)
}
if item.Name != "updated" {
t.Errorf("expected Name=updated, got %q", item.Name)
}
}
// --- PATCH handler tests ---
func TestPatchHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "PATCH /items/{id}", func(r *http.Request, in *Item) (*Item, error) {
in.ID = r.PathValue("id")
return in, nil
})
resp := doRequest(t, api, http.MethodPatch, "/items/99", `{"name":"patched"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
item := decodeJSON[Item](t, resp)
if item.Name != "patched" {
t.Errorf("expected Name=patched, got %q", item.Name)
}
}
// --- DELETE handler tests ---
func TestDeleteHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "DELETE /items/{id}", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
resp := doRequest(t, api, http.MethodDelete, "/items/42", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
}
// --- HEAD handler tests ---
func TestHeadHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "HEAD /ping", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
resp := doRequest(t, api, http.MethodHead, "/ping", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
}
// --- OPTIONS handler tests ---
func TestOptionsHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "OPTIONS /items", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
resp := doRequest(t, api, http.MethodOptions, "/items", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
}
// --- TRACE handler tests ---
func TestTraceHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "TRACE /debug", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
resp := doRequest(t, api, http.MethodTrace, "/debug", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
}
// --- CONNECT handler tests ---
func TestConnectHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "CONNECT /tunnel", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
resp := doRequest(t, api, http.MethodConnect, "/tunnel", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
}
// --- Error handling tests ---
func TestCustomErrorReturnsCorrectStatusCode(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /fail", func(r *http.Request, _ struct{}) (*Empty, error) {
return nil, &NotFoundError{Message: "not found", Detail: "gone"}
}, shiftapi.WithError[*NotFoundError](http.StatusNotFound))
resp := doRequest(t, api, http.MethodGet, "/fail", "")
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("expected 404, got %d", resp.StatusCode)
}
body := decodeJSON[map[string]string](t, resp)
if body["message"] != "not found" {
t.Errorf("expected message 'not found', got %q", body["message"])
}
}
func TestCustomErrorReturnsJSON(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /fail", func(r *http.Request, in *Person) (*Greeting, error) {
return nil, &ConflictError{Code: "CONFLICT", Message: "invalid data"}
}, shiftapi.WithError[*ConflictError](http.StatusConflict))
resp := doRequest(t, api, http.MethodPost, "/fail", `{"name":"test"}`)
if resp.StatusCode != http.StatusConflict {
t.Fatalf("expected 409, got %d", resp.StatusCode)
}
if ct := resp.Header.Get("Content-Type"); ct != "application/json; charset=utf-8" {
t.Errorf("expected Content-Type application/json; charset=utf-8, got %q", ct)
}
}
func TestGenericErrorReturns500(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /boom", func(r *http.Request, _ struct{}) (*Empty, error) {
return nil, errors.New("something broke")
})
resp := doRequest(t, api, http.MethodGet, "/boom", "")
if resp.StatusCode != http.StatusInternalServerError {
t.Fatalf("expected 500, got %d", resp.StatusCode)
}
}
// --- WithStatus tests ---
func TestWithStatusCustomCode(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /items", func(r *http.Request, in *Item) (*Item, error) {
in.ID = "new-id"
return in, nil
}, shiftapi.WithStatus(http.StatusCreated))
resp := doRequest(t, api, http.MethodPost, "/items", `{"name":"widget"}`)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("expected 201, got %d", resp.StatusCode)
}
}
func TestWithStatusOnGetHandler(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "DELETE /items/{id}", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
}, shiftapi.WithStatus(http.StatusNoContent))
resp := doRequest(t, api, http.MethodDelete, "/items/1", "")
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("expected 204, got %d", resp.StatusCode)
}
}
// --- WithRouteInfo tests ---
func TestWithRouteInfoInSpec(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /greet", func(r *http.Request, in *Person) (*Greeting, error) {
return &Greeting{Hello: in.Name}, nil
}, shiftapi.WithRouteInfo(shiftapi.RouteInfo{
Summary: "Greet someone",
Description: "Greets a person by name",
Tags: []string{"greetings", "social"},
}))
spec := api.Spec()
pathItem := spec.Paths.Find("/greet")
if pathItem == nil {
t.Fatal("expected /greet in paths")
}
if pathItem.Post == nil {
t.Fatal("expected POST operation on /greet")
}
if pathItem.Post.Summary != "Greet someone" {
t.Errorf("expected summary %q, got %q", "Greet someone", pathItem.Post.Summary)
}
if pathItem.Post.Description != "Greets a person by name" {
t.Errorf("expected description %q, got %q", "Greets a person by name", pathItem.Post.Description)
}
if len(pathItem.Post.Tags) != 2 || pathItem.Post.Tags[0] != "greetings" {
t.Errorf("expected tags [greetings social], got %v", pathItem.Post.Tags)
}
}
// --- OpenAPI schema structure tests ---
func TestSpecHasPath(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
spec := api.Spec()
if spec.Paths.Find("/health") == nil {
t.Fatal("expected /health in spec paths")
}
}
func TestSpecGetHasNoRequestBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
spec := api.Spec()
pathItem := spec.Paths.Find("/health")
if pathItem.Get == nil {
t.Fatal("expected GET operation")
}
if pathItem.Get.RequestBody != nil {
t.Error("GET should not have a request body in the spec")
}
}
func TestSpecPostHasRequestBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /greet", func(r *http.Request, in *Person) (*Greeting, error) {
return &Greeting{Hello: in.Name}, nil
})
spec := api.Spec()
pathItem := spec.Paths.Find("/greet")
if pathItem.Post == nil {
t.Fatal("expected POST operation")
}
if pathItem.Post.RequestBody == nil {
t.Error("POST should have a request body in the spec")
}
}
func TestSpecRequestBodyIsRequired(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /greet", func(r *http.Request, in *Person) (*Greeting, error) {
return &Greeting{Hello: in.Name}, nil
})
spec := api.Spec()
pathItem := spec.Paths.Find("/greet")
rb := pathItem.Post.RequestBody
if rb == nil || rb.Value == nil {
t.Fatal("expected request body")
}
if !rb.Value.Required {
t.Error("request body should be marked as required")
}
}
// --- Empty body behavior for body-carrying methods ---
func TestPostNoInputRequiresBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /trigger", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
// Empty body should be rejected
resp := doRequest(t, api, http.MethodPost, "/trigger", "")
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400 for POST without body, got %d", resp.StatusCode)
}
// Empty JSON object should be accepted
resp2 := doRequest(t, api, http.MethodPost, "/trigger", `{}`)
if resp2.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for POST with {}, got %d", resp2.StatusCode)
}
}
func TestPutNoInputRequiresBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "PUT /items/{id}", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
resp := doRequest(t, api, http.MethodPut, "/items/1", "")
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400 for PUT without body, got %d", resp.StatusCode)
}
resp2 := doRequest(t, api, http.MethodPut, "/items/1", `{}`)
if resp2.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for PUT with {}, got %d", resp2.StatusCode)
}
}
func TestPatchNoInputRequiresBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "PATCH /items/{id}", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
resp := doRequest(t, api, http.MethodPatch, "/items/1", "")
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400 for PATCH without body, got %d", resp.StatusCode)
}
resp2 := doRequest(t, api, http.MethodPatch, "/items/1", `{}`)
if resp2.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for PATCH with {}, got %d", resp2.StatusCode)
}
}
func TestGetNoInputDoesNotRequireBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
// GET without body should succeed
resp := doRequest(t, api, http.MethodGet, "/health", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for GET without body, got %d", resp.StatusCode)
}
}
func TestDeleteNoInputDoesNotRequireBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "DELETE /items/{id}", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
// DELETE without body should succeed
resp := doRequest(t, api, http.MethodDelete, "/items/1", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for DELETE without body, got %d", resp.StatusCode)
}
}
// --- Spec: empty body on body-carrying methods ---
func TestSpecPostNoInputHasEmptyRequestBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /trigger", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
spec := api.Spec()
op := spec.Paths.Find("/trigger").Post
if op.RequestBody == nil {
t.Fatal("POST with no input should still have a request body in the spec")
}
if !op.RequestBody.Value.Required {
t.Error("request body should be required")
}
content := op.RequestBody.Value.Content["application/json"]
if content == nil {
t.Fatal("expected application/json content")
}
if !content.Schema.Value.Type.Is("object") {
t.Errorf("expected empty object schema, got %v", content.Schema.Value.Type)
}
if len(content.Schema.Value.Properties) != 0 {
t.Errorf("expected 0 properties, got %d", len(content.Schema.Value.Properties))
}
}
func TestSpecPutNoInputHasEmptyRequestBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "PUT /items/{id}", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
spec := api.Spec()
op := spec.Paths.Find("/items/{id}").Put
if op.RequestBody == nil {
t.Fatal("PUT with no input should still have a request body in the spec")
}
}
func TestSpecGetNoInputHasNoRequestBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
spec := api.Spec()
op := spec.Paths.Find("/health").Get
if op.RequestBody != nil {
t.Error("GET with no input should not have a request body in the spec")
}
}
func TestSpecDeleteHasNoRequestBody(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "DELETE /items/{id}", func(r *http.Request, _ struct{}) (*Empty, error) {
return &Empty{}, nil
})
spec := api.Spec()
pathItem := spec.Paths.Find("/items/{id}")
if pathItem.Delete == nil {
t.Fatal("expected DELETE operation")
}
if pathItem.Delete.RequestBody != nil {
t.Error("DELETE should not have a request body in the spec")
}
}
func TestSpecHasResponseSchema(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
spec := api.Spec()
pathItem := spec.Paths.Find("/health")
resp := pathItem.Get.Responses.Value("200")
if resp == nil {
t.Fatal("expected 200 response")
}
if resp.Value.Content["application/json"] == nil {
t.Fatal("expected application/json content in response")
}
}
func TestSpecResponseDescriptionUsesStatusText(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
spec := api.Spec()
resp := spec.Paths.Find("/health").Get.Responses.Value("200")
if resp.Value.Description == nil || *resp.Value.Description != "OK" {
t.Errorf("expected response description 'OK', got %v", resp.Value.Description)
}
}
func TestSpecWithStatusUsesCorrectCodeInSpec(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /items", func(r *http.Request, in *Item) (*Item, error) {
return in, nil
}, shiftapi.WithStatus(http.StatusCreated))
spec := api.Spec()
pathItem := spec.Paths.Find("/items")
if pathItem.Post.Responses.Value("201") == nil {
t.Error("expected 201 response in spec when WithStatus(201) is used")
}
if pathItem.Post.Responses.Value("200") != nil {
t.Error("should not have 200 response when WithStatus(201) is used")
}
}
func TestSpecComponentSchemasPopulated(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /greet", func(r *http.Request, in *Person) (*Greeting, error) {
return &Greeting{Hello: in.Name}, nil
})
spec := api.Spec()
if len(spec.Components.Schemas) == 0 {
t.Fatal("expected component schemas to be populated")
}
}
func TestSpecMultipleMethodsOnSamePath(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /items", func(r *http.Request, _ struct{}) (*[]Item, error) {
return &[]Item{}, nil
})
shiftapi.Handle(api, "POST /items", func(r *http.Request, in *Item) (*Item, error) {
return in, nil
})
spec := api.Spec()
pathItem := spec.Paths.Find("/items")
if pathItem == nil {
t.Fatal("expected /items in paths")
}
if pathItem.Get == nil {
t.Error("expected GET on /items")
}
if pathItem.Post == nil {
t.Error("expected POST on /items")
}
}
func TestSpecOpenAPIVersion(t *testing.T) {
api := newTestAPI(t)
if api.Spec().OpenAPI != "3.1" {
t.Errorf("expected OpenAPI 3.1, got %q", api.Spec().OpenAPI)
}
}
// --- Path parameter spec tests ---
func TestSpecPathParametersDocumented(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /users/{id}", func(r *http.Request, _ struct{}) (*Item, error) {
return &Item{ID: r.PathValue("id")}, nil
})
spec := api.Spec()
op := spec.Paths.Find("/users/{id}").Get
if len(op.Parameters) != 1 {
t.Fatalf("expected 1 path parameter, got %d", len(op.Parameters))
}
param := op.Parameters[0].Value
if param.Name != "id" {
t.Errorf("expected parameter name 'id', got %q", param.Name)
}
if param.In != "path" {
t.Errorf("expected parameter in 'path', got %q", param.In)
}
if !param.Required {
t.Error("path parameters must be required")
}
}
func TestSpecMultiplePathParameters(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /orgs/{orgId}/users/{userId}", func(r *http.Request, _ struct{}) (*Item, error) {
return &Item{}, nil
})
spec := api.Spec()
op := spec.Paths.Find("/orgs/{orgId}/users/{userId}").Get
if len(op.Parameters) != 2 {
t.Fatalf("expected 2 path parameters, got %d", len(op.Parameters))
}
if op.Parameters[0].Value.Name != "orgId" {
t.Errorf("expected first param 'orgId', got %q", op.Parameters[0].Value.Name)
}
if op.Parameters[1].Value.Name != "userId" {
t.Errorf("expected second param 'userId', got %q", op.Parameters[1].Value.Name)
}
}
func TestSpecNoPathParametersWhenNoneInPath(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
spec := api.Spec()
op := spec.Paths.Find("/health").Get
if len(op.Parameters) != 0 {
t.Errorf("expected 0 parameters, got %d", len(op.Parameters))
}
}
// --- Operation ID tests ---
func TestSpecOperationID(t *testing.T) {
tests := []struct {
method string
path string
expectedID string
}{
{"GET", "/health", "getHealth"},
{"GET", "/users/{id}", "getUsersById"},
{"POST", "/users", "postUsers"},
{"DELETE", "/orgs/{orgId}/users/{userId}", "deleteOrgsByOrgIdUsersByUserId"},
{"PUT", "/items/{id}", "putItemsById"},
}
for _, tc := range tests {
t.Run(tc.expectedID, func(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, tc.method+" "+tc.path, func(r *http.Request, in *Empty) (*Empty, error) {
return &Empty{}, nil
})
spec := api.Spec()
pathItem := spec.Paths.Find(tc.path)
var op *openapi3.Operation
switch tc.method {
case "GET":
op = pathItem.Get
case "POST":
op = pathItem.Post
case "PUT":
op = pathItem.Put
case "DELETE":
op = pathItem.Delete
}
if op.OperationID != tc.expectedID {
t.Errorf("expected operationId %q, got %q", tc.expectedID, op.OperationID)
}
})
}
}
// --- Default error response tests ---
func TestSpecHas422And500ErrorResponses(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "GET /health", func(r *http.Request, _ struct{}) (*Status, error) {
return &Status{OK: true}, nil
})
spec := api.Spec()
op := spec.Paths.Find("/health").Get
// 422 ValidationError
resp422 := op.Responses.Value("422")
if resp422 == nil {
t.Fatal("expected 422 error response in spec")
}
if resp422.Value.Description == nil || *resp422.Value.Description != "Validation Error" {
t.Error("expected 422 response description 'Validation Error'")
}
content422 := resp422.Value.Content["application/json"]
if content422 == nil {
t.Fatal("expected application/json content in 422 response")
}
if content422.Schema.Ref != "#/components/schemas/ValidationError" {
t.Errorf("expected 422 schema ref to ValidationError, got %s", content422.Schema.Ref)
}
// 500 APIError
resp500 := op.Responses.Value("500")
if resp500 == nil {
t.Fatal("expected 500 error response in spec")
}
if resp500.Value.Description == nil || *resp500.Value.Description != "Internal Server Error" {
t.Error("expected 500 response description 'Internal Server Error'")
}
content500 := resp500.Value.Content["application/json"]
if content500 == nil {
t.Fatal("expected application/json content in 500 response")
}
if content500.Schema.Ref != "#/components/schemas/InternalServerError" {
t.Errorf("expected 500 schema ref to APIError, got %s", content500.Schema.Ref)
}
}
func TestSpecErrorResponsesOnPost(t *testing.T) {
api := newTestAPI(t)
shiftapi.Handle(api, "POST /items", func(r *http.Request, in *Item) (*Item, error) {
return in, nil
})
spec := api.Spec()
op := spec.Paths.Find("/items").Post