-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine_e2e_test.go
More file actions
1417 lines (1284 loc) · 61.9 KB
/
Copy pathengine_e2e_test.go
File metadata and controls
1417 lines (1284 loc) · 61.9 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
// Copyright 2025 Ehab Terra, 2025-2026 Anton Starikov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package engine
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
intspec "github.com/antst/go-apispec/internal/spec"
"github.com/antst/go-apispec/spec"
)
// frameworkTestCase holds the configuration for testing a single framework.
type frameworkTestCase struct {
name string
inputDir string
configFn func() *spec.APISpecConfig
}
// allFrameworks returns test cases for every supported framework testdata dir.
// It skips frameworks whose testdata directory does not exist.
func allFrameworks(t *testing.T) []frameworkTestCase {
t.Helper()
cases := []frameworkTestCase{
{name: "chi", inputDir: "../../testdata/chi", configFn: spec.DefaultChiConfig},
{name: "gin", inputDir: "../../testdata/gin", configFn: spec.DefaultGinConfig},
{name: "echo", inputDir: "../../testdata/echo", configFn: spec.DefaultEchoConfig},
{name: "fiber", inputDir: "../../testdata/fiber", configFn: spec.DefaultFiberConfig},
{name: "mux", inputDir: "../../testdata/mux", configFn: spec.DefaultMuxConfig},
{name: "map_index_path", inputDir: "../../testdata/map_index_path", configFn: spec.DefaultMuxConfig},
{name: "response_patterns", inputDir: "../../testdata/response_patterns", configFn: spec.DefaultChiConfig},
{name: "nested_http", inputDir: "../../testdata/nested_http", configFn: spec.DefaultHTTPConfig},
{name: "error_helpers", inputDir: "../../testdata/error_helpers", configFn: spec.DefaultChiConfig},
{name: "form_value_var", inputDir: "../../testdata/form_value_var", configFn: spec.DefaultChiConfig},
{name: "json_dto", inputDir: "../../testdata/json_dto", configFn: spec.DefaultChiConfig},
{name: "json_dto_helpers", inputDir: "../../testdata/json_dto_helpers", configFn: spec.DefaultChiConfig},
{name: "shared_decode_any", inputDir: "../../testdata/shared_decode_any", configFn: spec.DefaultChiConfig},
{name: "shared_decode_generic", inputDir: "../../testdata/shared_decode_generic", configFn: spec.DefaultChiConfig},
{name: "shared_decode_methods", inputDir: "../../testdata/shared_decode_methods", configFn: spec.DefaultChiConfig},
{name: "shared_decode_router", inputDir: "../../testdata/shared_decode_router", configFn: spec.DefaultChiConfig},
{name: "json_patch", inputDir: "../../testdata/json_patch", configFn: spec.DefaultChiConfig},
{name: "servemux_methods", inputDir: "../../testdata/servemux_methods", configFn: spec.DefaultHTTPConfig},
{name: "security_bearer", inputDir: "../../testdata/security_bearer", configFn: spec.DefaultHTTPConfig},
{name: "writejson_helper", inputDir: "../../testdata/writejson_helper", configFn: spec.DefaultHTTPConfig},
{name: "error_switch_minimal", inputDir: "../../testdata/error_switch_minimal", configFn: spec.DefaultChiConfig},
{name: "error_switch_file_service", inputDir: "../../testdata/error_switch_file_service", configFn: spec.DefaultChiConfig},
// spec 009: a response helper that type-switches on its argument. The
// concrete-type route fans out only the matched arm; the imprecise route
// degrades to the default arm + warns (FR-011/FR-012).
{name: "cfg_helper_typeswitch", inputDir: "../../testdata/cfg_helper_typeswitch", configFn: spec.DefaultHTTPConfig},
// spec 009: a status assigned inside a loop body still reaches the response
// write (FR-010 — the loop back-edge terminates and the value contributes).
{name: "cfg_loop_status", inputDir: "../../testdata/cfg_loop_status", configFn: spec.DefaultHTTPConfig},
// spec 009 US2: an `if r.Method == …` dispatch splits into one operation per
// method, the same as a `switch r.Method` (FR-003).
{name: "cfg_method_if_dispatch", inputDir: "../../testdata/cfg_method_if_dispatch", configFn: spec.DefaultHTTPConfig},
// spec 009 US2 (FR-003): the switch-form mirror of cfg_method_if_dispatch, with
// net/http CONSTANT cases (`case http.MethodGet:`). Must split identically —
// extractCaseValues resolves the constants the same way extractMethodGuard does.
{name: "cfg_method_switch_dispatch", inputDir: "../../testdata/cfg_method_switch_dispatch", configFn: spec.DefaultHTTPConfig},
// spec 009 US2: a method dispatch combined with an INDEPENDENT pre-dispatch
// conditional — the independent 500 is carried onto every method operation
// (CFG: orthogonal to the dispatch), not dropped as the pre-CFG split did.
{name: "cfg_method_if_independent", inputDir: "../../testdata/cfg_method_if_independent", configFn: spec.DefaultHTTPConfig},
// spec 009 US2: cross-function guard — a method arm that splits AND calls a
// helper writing a conditional response. The helper response's branch is in the
// HELPER's CFG, so the classifier must not reason about it against the handler's
// CFG (that would leak it onto the other method); it is conservatively excluded.
{name: "cfg_method_helper_response", inputDir: "../../testdata/cfg_method_helper_response", configFn: spec.DefaultHTTPConfig},
// spec 009 US2: a `fallthrough` into a `switch r.Method` default — the 405 is
// recognised structurally as the dispatch fallback and excluded, NOT leaked onto
// GET/POST despite the fallthrough edge making it reachable from the POST arm.
{name: "cfg_method_switch_fallthrough", inputDir: "../../testdata/cfg_method_switch_fallthrough", configFn: spec.DefaultHTTPConfig},
// spec 009 US2: TWO `switch r.Method` dispatches with an independent 401 between
// them — the dispatch root is scoped to one dispatch's arms, so the 401 is shared
// onto GET+POST, not over-excluded by a root spanning both dispatches.
{name: "cfg_method_two_dispatch", inputDir: "../../testdata/cfg_method_two_dispatch", configFn: spec.DefaultHTTPConfig},
// spec 009 US2: a COMBINED case (`case GET, POST:`) + a `default` — the combined
// arm lowers to one block dominated by itself, so the dispatch root must come from
// the recorded group (all arms incl. default); the 405 stays the fallback and is
// not leaked onto the GET/POST operations the combined case splits into.
{name: "cfg_method_combined_default", inputDir: "../../testdata/cfg_method_combined_default", configFn: spec.DefaultHTTPConfig},
// spec 009 US2: responses split across an `if r.Method ==` arm AND a `switch r.Method`
// with a default — distinct dispatch groups; the root spans BOTH contributing groups so
// the switch default 405 is excluded, not leaked onto GET (if-arm) and POST (switch-arm).
{name: "cfg_method_if_switch_default", inputDir: "../../testdata/cfg_method_if_switch_default", configFn: spec.DefaultHTTPConfig},
// spec 009 US2: a `switch` over a COPY of r.Method (`m := r.Method; switch m`) — recognised
// by its method-named case values (not the tag), so the default 405 is excluded.
{name: "cfg_method_switch_copy", inputDir: "../../testdata/cfg_method_switch_copy", configFn: spec.DefaultHTTPConfig},
// spec 009 US3: branch-dependent response bodies are attributed to the status
// on which they are written — 200/FullUser vs 404/ErrorBody, not merged (FR-005).
{name: "cfg_branch_bodies", inputDir: "../../testdata/cfg_branch_bodies", configFn: spec.DefaultHTTPConfig},
{name: "bodyless_status", inputDir: "../../testdata/bodyless_status", configFn: spec.DefaultHTTPConfig},
{name: "wrapped_response", inputDir: "../../testdata/wrapped_response", configFn: spec.DefaultHTTPConfig},
{name: "echo_handler_factory", inputDir: "../../testdata/echo_handler_factory", configFn: spec.DefaultEchoConfig},
// Corpus-expansion batch: router diversity + uncovered scenarios.
{name: "gin_groups", inputDir: "../../testdata/gin_groups", configFn: spec.DefaultGinConfig},
{name: "fiber_resource", inputDir: "../../testdata/fiber_resource", configFn: spec.DefaultFiberConfig},
{name: "echo_enums", inputDir: "../../testdata/echo_enums", configFn: spec.DefaultEchoConfig},
{name: "mux_subrouter", inputDir: "../../testdata/mux_subrouter", configFn: spec.DefaultMuxConfig},
{name: "complex_chi_router", inputDir: "../../testdata/complex_chi_router", configFn: spec.DefaultChiConfig},
{name: "chi_recursive", inputDir: "../../testdata/chi_recursive", configFn: spec.DefaultChiConfig},
{name: "datetime_fields", inputDir: "../../testdata/datetime_fields", configFn: spec.DefaultHTTPConfig},
{name: "multipart_upload", inputDir: "../../testdata/multipart_upload", configFn: spec.DefaultHTTPConfig},
{name: "chi_middleware", inputDir: "../../testdata/chi_middleware", configFn: spec.DefaultChiConfig},
{name: "status_codes", inputDir: "../../testdata/status_codes", configFn: spec.DefaultChiConfig},
{name: "nested_dto", inputDir: "../../testdata/nested_dto", configFn: spec.DefaultHTTPConfig},
{name: "xml_text_response", inputDir: "../../testdata/xml_text_response", configFn: spec.DefaultHTTPConfig},
// Batch 3: full CRUD lifecycles, nested groups, and scalar-schema variety.
{name: "echo_crud", inputDir: "../../testdata/echo_crud", configFn: spec.DefaultEchoConfig},
{name: "fiber_crud", inputDir: "../../testdata/fiber_crud", configFn: spec.DefaultFiberConfig},
{name: "gin_nested_groups", inputDir: "../../testdata/gin_nested_groups", configFn: spec.DefaultGinConfig},
{name: "numeric_types", inputDir: "../../testdata/numeric_types", configFn: spec.DefaultHTTPConfig},
{name: "chi_crud", inputDir: "../../testdata/chi_crud", configFn: spec.DefaultChiConfig},
{name: "chi_format_tags", inputDir: "../../testdata/chi_format_tags", configFn: spec.DefaultChiConfig},
{name: "mux_crud", inputDir: "../../testdata/mux_crud", configFn: spec.DefaultMuxConfig},
{name: "gin_arrays", inputDir: "../../testdata/gin_arrays", configFn: spec.DefaultGinConfig},
{name: "fiber_nested", inputDir: "../../testdata/fiber_nested", configFn: spec.DefaultFiberConfig},
{name: "echo_subresources", inputDir: "../../testdata/echo_subresources", configFn: spec.DefaultEchoConfig},
{name: "maps_variety", inputDir: "../../testdata/maps_variety", configFn: spec.DefaultHTTPConfig},
{name: "arrays_variety", inputDir: "../../testdata/arrays_variety", configFn: spec.DefaultHTTPConfig},
{name: "fixed_arrays", inputDir: "../../testdata/fixed_arrays", configFn: spec.DefaultHTTPConfig},
// Field visibility + json-tag options: unexported fields and `json:"-"` are
// dropped (encoding/json never marshals them), `json:"-,"` keeps a literal
// "-" name, and the `,string` option forces {type:string} on a scalar.
{name: "unexported_skip", inputDir: "../../testdata/unexported_skip", configFn: spec.DefaultHTTPConfig},
// json.RawMessage round-trips raw JSON -> empty schema {} (not base64),
// composing through pointer and slice; a plain []byte stays base64.
{name: "raw_message", inputDir: "../../testdata/raw_message", configFn: spec.DefaultHTTPConfig},
// Generic defined-"other" types (type Box[T any] map[string]T): a field of
// Box[int] substitutes T -> int (map[string]int), in direct/pointer/slice
// positions, instead of dangling a $ref to the bare parameter.
{name: "generic_container", inputDir: "../../testdata/generic_container", configFn: spec.DefaultHTTPConfig},
// Defined non-struct/alias/interface types (Kind "other": a defined map,
// slice, nested-slice, func). A field of such a type must resolve from its
// captured underlying shape, not emit a dangling $ref; a func underlying is
// opaque and the field is omitted.
{name: "named_underlying", inputDir: "../../testdata/named_underlying", configFn: spec.DefaultHTTPConfig},
{name: "inline_structs", inputDir: "../../testdata/inline_structs", configFn: spec.DefaultHTTPConfig},
{name: "pointers_variety", inputDir: "../../testdata/pointers_variety", configFn: spec.DefaultHTTPConfig},
{name: "optional_fields", inputDir: "../../testdata/optional_fields", configFn: spec.DefaultHTTPConfig},
// Regression for #52: a multipart handler must not get a request body
// inferred from an unrelated json.Unmarshal deep in its call graph.
{name: "multipart_overreach", inputDir: "../../testdata/multipart_overreach", configFn: spec.DefaultChiConfig},
// Regression for #52 (response side): io.Copy to the response writer is a
// binary 200, but io.Copy to a file reachable in the call graph is not.
{name: "binary_response_overreach", inputDir: "../../testdata/binary_response_overreach", configFn: spec.DefaultHTTPConfig},
// Path-template normalization: gorilla/mux regex constraints and Go 1.22
// ServeMux wildcards must reduce to clean {name} placeholders.
{name: "mux_regex_path", inputDir: "../../testdata/mux_regex_path", configFn: spec.DefaultMuxConfig},
{name: "servemux_wildcards", inputDir: "../../testdata/servemux_wildcards", configFn: spec.DefaultHTTPConfig},
// Validation tags: gte/lte → numeric minimum/maximum; min/max/gte/lte on a
// string field → minLength/maxLength.
{name: "chi_validation", inputDir: "../../testdata/chi_validation", configFn: spec.DefaultChiConfig},
// map value types: map[string]Struct / []Struct / *Struct must ref the
// element with a single package separator.
{name: "map_struct_values", inputDir: "../../testdata/map_struct_values", configFn: spec.DefaultHTTPConfig},
// Nested slices [][]T must recurse as nested arrays, not a mangled _T ref.
{name: "nested_arrays", inputDir: "../../testdata/nested_arrays", configFn: spec.DefaultHTTPConfig},
// Embedded structs: anonymous fields (value/pointer/transitive) promote flat.
{name: "embedded_structs", inputDir: "../../testdata/embedded_structs", configFn: spec.DefaultHTTPConfig},
// json-tagged anonymous embeds: an untagged embed promotes flat, a
// `json:"meta"`-named embed nests under "meta" (not flattened), and a
// `json:"-"` embed is dropped entirely (no property, no component).
{name: "embedded_tagged", inputDir: "../../testdata/embedded_tagged", configFn: spec.DefaultHTTPConfig},
// Generic envelope wrapper: APIResponse[T] must bind T per call site.
{name: "generic_response_wrapper", inputDir: "../../testdata/generic_response_wrapper", configFn: spec.DefaultHTTPConfig},
{name: "generic_envelopes", inputDir: "../../testdata/generic_envelopes", configFn: spec.DefaultHTTPConfig},
// gorilla/mux .Queries(...) query params attach to their own route only.
{name: "mux_queries", inputDir: "../../testdata/mux_queries", configFn: spec.DefaultMuxConfig},
// Conditional-status fan-out reachability (#50): only statuses whose
// assignment reaches the response call site are emitted.
{name: "conditional_status_reachability", inputDir: "../../testdata/conditional_status_reachability", configFn: spec.DefaultHTTPConfig},
}
var available []frameworkTestCase
for _, tc := range cases {
if _, err := os.Stat(tc.inputDir); err == nil {
available = append(available, tc)
}
}
require.NotEmpty(t, available, "at least one framework testdata directory must exist")
return available
}
// newDefaultCfg returns an EngineConfig pre-filled with sensible defaults for e2e tests.
func newDefaultCfg(inputDir string, apiCfg *spec.APISpecConfig) *EngineConfig {
return &EngineConfig{
InputDir: inputDir,
OutputFile: "openapi.json",
Title: "Test",
APIVersion: "1.0.0",
OpenAPIVersion: "3.1.1",
MaxNodesPerTree: 50000,
MaxChildrenPerNode: 500,
MaxArgsPerFunction: 100,
MaxNestedArgsDepth: 100,
MaxRecursionDepth: 10,
Verbose: false,
APISpecConfig: apiCfg,
}
}
// collectOperations returns every non-nil Operation in the spec together with its operationId.
func collectOperations(result *spec.OpenAPISpec) []*operation {
var ops []*operation
for path, item := range result.Paths {
for method, op := range map[string]*intspec.Operation{
"GET": item.Get,
"POST": item.Post,
"PUT": item.Put,
"DELETE": item.Delete,
"PATCH": item.Patch,
} {
if op != nil {
ops = append(ops, &operation{path: path, method: method, op: op})
}
}
}
return ops
}
type operation struct {
path string
method string
op *intspec.Operation
}
// collectAllRefValues recursively collects every $ref string found in response content schemas.
func collectAllRefValues(result *spec.OpenAPISpec) []string {
var refs []string
for _, item := range result.Paths {
for _, op := range []*intspec.Operation{item.Get, item.Post, item.Put, item.Delete, item.Patch} {
if op == nil {
continue
}
for _, resp := range op.Responses {
for _, media := range resp.Content {
if media.Schema != nil {
refs = append(refs, collectSchemaRefs(media.Schema)...)
}
}
}
}
}
return refs
}
func collectSchemaRefs(s *spec.Schema) []string {
if s == nil {
return nil
}
var refs []string
if s.Ref != "" {
refs = append(refs, s.Ref)
}
if s.Items != nil {
refs = append(refs, collectSchemaRefs(s.Items)...)
}
for _, prop := range s.Properties {
refs = append(refs, collectSchemaRefs(prop)...)
}
for _, child := range s.AllOf {
refs = append(refs, collectSchemaRefs(child)...)
}
for _, child := range s.OneOf {
refs = append(refs, collectSchemaRefs(child)...)
}
for _, child := range s.AnyOf {
refs = append(refs, collectSchemaRefs(child)...)
}
return refs
}
// TestE2E_FormValueVar_AllPatternsExtracted asserts that r.FormValue calls
// reach the spec regardless of how the result is consumed (inline, var+guard,
// direct string usage), and that r.FormFile produces a binary form parameter.
//
// Regression test for the bug where the tracker dedup at the caller-side edge
// loop dropped every var-bound r.FormValue call once any inline r.FormValue
// existed in the same handler.
func TestE2E_FormValueVar_AllPatternsExtracted(t *testing.T) {
cfg := newDefaultCfg("../../testdata/form_value_var", spec.DefaultChiConfig())
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
pi, ok := result.Paths["/upload"]
require.True(t, ok, "expected /upload path; got: %v", pathKeys(result))
require.NotNil(t, pi.Post)
got := map[string]*spec.Schema{}
for _, p := range pi.Post.Parameters {
require.Equal(t, "form", p.In, "param %q should be in=form", p.Name)
got[p.Name] = p.Schema
}
expected := map[string]struct{ Type, Format string }{
"storageBucketId": {Type: "integer"}, // inline strconv.Atoi
"allowedMimeTypes": {Type: "string"}, // var-bound strings.Split — non-converter consumer must NOT cross into shadowed-v scopes
"temporaryLocation": {Type: "boolean"}, // var-bound strconv.ParseBool
"maxFileSize": {Type: "integer"}, // var-bound strconv.Atoi (shadowed v)
"displayName": {Type: "string"}, // no converter — string fallback
"file": {Type: "string", Format: "binary"}, // FormFile
}
assert.Equal(t, len(expected), len(got), "unexpected form params: have %v, want %v",
paramNames(pi.Post.Parameters), keysOf(expected))
for name, want := range expected {
s, ok := got[name]
if !assert.True(t, ok, "missing form param %q (have %v)", name, paramNames(pi.Post.Parameters)) {
continue
}
require.NotNil(t, s, "schema missing for %q", name)
assert.Equal(t, want.Type, s.Type, "wrong type for %q", name)
assert.Equal(t, want.Format, s.Format, "wrong format for %q", name)
}
}
// TestE2E_SecurityBearer_AllSchemesAndSuppression locks down the full
// Authorization-header detection matrix on testdata/security_bearer:
//
// - bearer via helper (transitive call-graph walk) and bearer inline
// (direct call in handler body) must share ONE bearerAuth scheme.
// - basic via helper produces a separate basicAuth scheme.
// - apiKey (raw header read, no TrimPrefix) falls back to apiKey-in-header.
// - The Authorization header parameter must be SUPPRESSED on every
// operation that gained a security scheme — leaving it would
// double-document the same auth surface and confuse SDK generators.
// - An open endpoint must remain free of any security stanza.
//
// Golden file separately covers the full JSON shape; this test asserts the
// behavioural invariants so a regression that flips a scheme name or
// breaks suppression fails with a clear diagnostic instead of a generic
// golden diff.
func TestE2E_SecurityBearer_AllSchemesAndSuppression(t *testing.T) {
cfg := newDefaultCfg("../../testdata/security_bearer", spec.DefaultHTTPConfig())
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
require.NotNil(t, result.Components, "components missing")
require.NotNil(t, result.Components.SecuritySchemes, "securitySchemes section must be emitted")
// Three distinct schemes registered, each with the expected shape.
require.Contains(t, result.Components.SecuritySchemes, "bearerAuth")
require.Contains(t, result.Components.SecuritySchemes, "basicAuth")
require.Contains(t, result.Components.SecuritySchemes, "apiKeyAuth")
assert.Equal(t, "http", result.Components.SecuritySchemes["bearerAuth"].Type)
assert.Equal(t, "bearer", result.Components.SecuritySchemes["bearerAuth"].Scheme)
assert.Equal(t, "http", result.Components.SecuritySchemes["basicAuth"].Type)
assert.Equal(t, "basic", result.Components.SecuritySchemes["basicAuth"].Scheme)
assert.Equal(t, "apiKey", result.Components.SecuritySchemes["apiKeyAuth"].Type)
assert.Equal(t, "header", result.Components.SecuritySchemes["apiKeyAuth"].In)
assert.Equal(t, "Authorization", result.Components.SecuritySchemes["apiKeyAuth"].Name)
// Helper + inline bearer endpoints reference the SAME scheme entry.
expectScheme := func(t *testing.T, path, schemeName string) {
t.Helper()
pi, ok := result.Paths[path]
require.True(t, ok, "expected %s in paths; got %v", path, pathKeys(result))
require.NotNil(t, pi.Post, "%s must have POST operation", path)
require.NotEmpty(t, pi.Post.Security, "%s must carry a security requirement", path)
// security: [{schemeName: []}] — single requirement, single scheme.
require.Contains(t, pi.Post.Security[0], schemeName,
"%s security must reference %s", path, schemeName)
// Authorization header must NOT appear as a parameter — the scheme
// reference already documents it. Case-insensitive match because
// HTTP header names are case-insensitive (and production suppression
// uses strings.EqualFold, so this assertion has to too).
for _, p := range pi.Post.Parameters {
assert.False(t, strings.EqualFold(p.Name, "Authorization"),
"%s parameter %q must not coexist with security scheme", path, p.Name)
}
}
expectScheme(t, "/protected/helper", "bearerAuth")
expectScheme(t, "/protected/inline", "bearerAuth")
expectScheme(t, "/protected/basic", "basicAuth")
expectScheme(t, "/protected/apikey", "apiKeyAuth")
// Regression: /matrix/user reads Authorization (no TrimPrefix on the
// header value) AND processes a Matrix user-ID via
// strings.TrimPrefix(userID, "@"). The unrelated "@" TrimPrefix must
// NOT poison auth detection — the resulting scheme stays apiKeyAuth,
// not the v0.4.12-era nonsense "@Auth".
expectScheme(t, "/matrix/user", "apiKeyAuth")
require.NotContains(t, result.Components.SecuritySchemes, "@Auth",
"unrelated TrimPrefix on '@' must not produce a bogus scheme")
// Open endpoint: no security stanza, no Authorization parameter.
open, ok := result.Paths["/open/ping"]
require.True(t, ok, "expected /open/ping in paths; got %v", pathKeys(result))
require.NotNil(t, open.Get)
assert.Empty(t, open.Get.Security, "open endpoint must NOT advertise auth")
}
// TestE2E_ServeMux_MethodPrefixAndGenericResponse covers two related Go 1.22+
// behaviors: HandleFunc("METHOD /path") syntax must yield clean path keys
// and the right operation verb (issue #21), and a generic response helper
// like `WriteJSON[T any](w, status, v T)` must instantiate T to the concrete
// call-site type rather than emitting the bare type parameter or — worse,
// per issue #22 — substituting an unrelated same-prefix type.
func TestE2E_ServeMux_MethodPrefixAndGenericResponse(t *testing.T) {
cfg := newDefaultCfg("../../testdata/servemux_methods", spec.DefaultHTTPConfig())
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
require.NotNil(t, result.Components, "components missing")
// Issue #21: path keys must be clean, no "METHOD " prefix.
pi, ok := result.Paths["/health/live"]
require.True(t, ok, "expected /health/live; got: %v", pathKeys(result))
require.NotContains(t, result.Paths, "/GET /health/live",
"malformed method-prefixed key must not be emitted")
require.NotNil(t, pi.Get, "GET prefix must produce a get: operation, not post:")
assert.Nil(t, pi.Post, "GET-prefix HandleFunc must NOT register a POST operation")
pi, ok = result.Paths["/matrix/check-room"]
require.True(t, ok, "expected /matrix/check-room; got: %v", pathKeys(result))
require.NotContains(t, result.Paths, "/POST /matrix/check-room",
"malformed method-prefixed key must not be emitted")
require.NotNil(t, pi.Post, "POST prefix must produce a post: operation")
// Issue #22: requestBody must reference dto.CheckRoomHTTPRequest, NOT
// dto.CheckRoomResponse — even though the call graph reaches an
// internal `json.Unmarshal(respBytes, &rmqResp)` inside the rpcClient
// service (which deserialises a RabbitMQ payload into
// dto.CheckRoomResponse). The first request-body match — the handler's
// own r.Body Decode — must win.
require.NotNil(t, pi.Post.RequestBody)
require.Contains(t, pi.Post.RequestBody.Content, "application/json",
"JSON request body must be advertised under application/json")
body := pi.Post.RequestBody.Content["application/json"]
require.NotNil(t, body.Schema, "requestBody schema must be set")
assert.Equal(t, "#/components/schemas/dto.CheckRoomHTTPRequest", body.Schema.Ref,
"requestBody must point to the handler's r.Body decode target, not an internal Unmarshal target")
// The internal rpcClient's json.Unmarshal target type must not leak
// into the spec at all when no endpoint actually exposes it.
require.NotNil(t, result.Components.Schemas, "components.schemas must be present")
require.NotContains(t, result.Components.Schemas, "dto.CheckRoomResponse",
"internal RabbitMQ payload type must not leak into the public schema set")
// Response: the WriteJSON(w, 200, dto.CheckRoomHTTPResponse{...}) call
// must resolve the interface{} parameter back to the concrete type.
require.Contains(t, pi.Post.Responses, "200", "200 response must be present")
resp200 := pi.Post.Responses["200"]
require.NotNil(t, resp200)
require.Contains(t, resp200.Content, "application/json")
respSchema := resp200.Content["application/json"].Schema
require.NotNil(t, respSchema)
assert.Equal(t, "#/components/schemas/dto.CheckRoomHTTPResponse", respSchema.Ref,
"response must substitute interface{} to the concrete call-site type")
// Legacy (no method prefix) keeps the default POST behavior.
pi, ok = result.Paths["/legacy"]
require.True(t, ok)
assert.NotNil(t, pi.Post, "no-prefix HandleFunc keeps the default POST")
}
// TestE2E_JSONPatch_StructLevelValidation asserts that a blank-marker
// `_ struct{} `apispec:"minProperties=...,anyOf=..."“ field on a request
// DTO produces both schema-level validation keywords and that the marker
// itself never leaks into the property map or `required` list.
func TestE2E_JSONPatch_StructLevelValidation(t *testing.T) {
cfg := newDefaultCfg("../../testdata/json_patch", spec.DefaultChiConfig())
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
require.NotNil(t, result.Components, "components missing")
schema := result.Components.Schemas["json_patch.UpdateDocumentRequest"]
require.NotNil(t, schema, "request schema missing")
// Marker must not appear as a property — the field is just a tag carrier.
for prop := range schema.Properties {
assert.NotEqual(t, "_", prop, "blank marker leaked into Properties")
}
for _, req := range schema.Required {
assert.NotEqual(t, "_", req, "blank marker leaked into Required")
}
// minProperties=1 emitted.
assert.Equal(t, 1, schema.MinProperties)
// anyOf emitted with exactly one `{required: [name]}` entry per listed
// field, in tag-declaration order.
require.Len(t, schema.AnyOf, 3, "anyOf should have one entry per listed field")
wantOrder := []string{"displayName", "storageBucketId", "temporaryLocation"}
for i, want := range wantOrder {
require.NotNil(t, schema.AnyOf[i])
assert.Equal(t, []string{want}, schema.AnyOf[i].Required, "anyOf[%d]", i)
}
// Field-level apispec tag on StorageBucketID still works alongside the
// marker — they're independent tags on different fields.
bucket := schema.Properties["storageBucketId"]
require.NotNil(t, bucket)
assert.Equal(t, "uuid", bucket.Format)
}
// TestE2E_JSONDto_FormatAndRequiredInference asserts the json_dto fixture's
// JSON request/response contract: requestBody.required is true, fields
// consumed by uuid.Parse get format=uuid via flow analysis, fields tagged
// with apispec:"format=..." get the tagged format, and pointer-derefed
// converter calls (`uuid.Parse(*body.TagsetID)`) reach the field schema.
func TestE2E_JSONDto_FormatAndRequiredInference(t *testing.T) {
cfg := newDefaultCfg("../../testdata/json_dto", spec.DefaultChiConfig())
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
pi, ok := result.Paths["/documents/copy"]
require.True(t, ok)
require.NotNil(t, pi.Post)
require.NotNil(t, pi.Post.RequestBody)
assert.True(t, pi.Post.RequestBody.Required, "requestBody must be marked required")
type want struct{ Type, Format string }
cases := map[string]map[string]want{
"json_dto.CopyDocumentRequest": {
// Flow-inferred via uuid.Parse(body.X) calls in the handler.
"sourceId": {Type: "string", Format: "uuid"},
"destinationBucketId": {Type: "string", Format: "uuid"},
"authorizationId": {Type: "string", Format: "uuid"},
// Pointer-derefed: uuid.Parse(*body.TagsetID).
"tagsetId": {Type: "string", Format: "uuid"},
// Struct-tag driven (no converter call).
"externalId": {Type: "string", Format: "uuid"},
"expiresAt": {Type: "string", Format: "date-time"},
},
"json_dto.CopyDocumentResponse": {
"id": {Type: "string", Format: "uuid"},
"createdAt": {Type: "string", Format: "date-time"},
"ownerEmail": {Type: "string", Format: "email"},
},
}
require.NotNil(t, result.Components, "components missing")
for typeName, fields := range cases {
schema := result.Components.Schemas[typeName]
require.NotNil(t, schema, "schema %s missing", typeName)
for prop, w := range fields {
ps := schema.Properties[prop]
require.NotNil(t, ps, "property %s.%s missing", typeName, prop)
assert.Equal(t, w.Type, ps.Type, "%s.%s type", typeName, prop)
assert.Equal(t, w.Format, ps.Format, "%s.%s format", typeName, prop)
}
}
}
// TestE2E_JSONDtoHelpers_InterproceduralInference asserts that the same
// request/response contract as json_dto survives the lint-driven helper
// extractions in issue #36: the decode boilerplate moved into a helper with an
// `any` parameter, and uuid.Parse moved into field-passed and struct-passed
// helpers. Request binding, per-field format: uuid, and the 200/400 split must
// all match the inline fixture rather than degrading.
func TestE2E_JSONDtoHelpers_InterproceduralInference(t *testing.T) {
cfg := newDefaultCfg("../../testdata/json_dto_helpers", spec.DefaultChiConfig())
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
pi, ok := result.Paths["/documents/copy"]
require.True(t, ok)
require.NotNil(t, pi.Post)
// Repro 2: request body still binds to the concrete type through the
// decodeStrictJSON(dst any) helper rather than collapsing to free-form.
require.NotNil(t, pi.Post.RequestBody)
assert.True(t, pi.Post.RequestBody.Required)
require.Contains(t, pi.Post.RequestBody.Content, "application/json")
reqSchema := pi.Post.RequestBody.Content["application/json"].Schema
require.NotNil(t, reqSchema)
assert.Equal(t, "#/components/schemas/json_dto.CopyDocumentRequest", reqSchema.Ref,
"request body must $ref the concrete schema, not inline a free-form object")
// Repro 1: format: uuid propagates from helpers back onto the fields.
reqType := result.Components.Schemas["json_dto.CopyDocumentRequest"]
require.NotNil(t, reqType)
for _, prop := range []string{"sourceId", "destinationBucketId", "authorizationId", "tagsetId", "externalId"} {
ps := reqType.Properties[prop]
require.NotNil(t, ps, "property %s missing", prop)
assert.Equal(t, "uuid", ps.Format, "%s must carry format: uuid", prop)
}
// Response split survives http.Error moving into a helper: 200 carries the
// response body, 400 stays a text/plain string (issue #36).
resp200, ok := pi.Post.Responses["200"]
require.True(t, ok, "200 response must be present")
require.Contains(t, resp200.Content, "application/json")
resp200Schema := resp200.Content["application/json"].Schema
require.NotNil(t, resp200Schema)
assert.Equal(t, "#/components/schemas/json_dto.CopyDocumentResponse", resp200Schema.Ref)
resp400, ok := pi.Post.Responses["400"]
require.True(t, ok, "400 response must be present")
require.Contains(t, resp400.Content, "text/plain; charset=utf-8")
resp400Schema := resp400.Content["text/plain; charset=utf-8"].Schema
require.NotNil(t, resp400Schema)
assert.Equal(t, "string", resp400Schema.Type,
"400 must remain a plain-text string, not steal the success body schema")
}
// TestE2E_MapIndexPath_NoPhantomPathParams asserts issue #35: a string-literal
// index into a plain map (fields["displayName"]) must not become an in:path
// parameter on a route with no placeholders, while a genuine mux.Vars read that
// matches a {placeholder} must still be emitted.
func TestE2E_MapIndexPath_NoPhantomPathParams(t *testing.T) {
cfg := newDefaultCfg("../../testdata/map_index_path", spec.DefaultMuxConfig())
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
// Bug case: no path params on a placeholder-free route.
file, ok := result.Paths["/internal/file"]
require.True(t, ok, "/internal/file must be present")
require.NotNil(t, file.Post)
for _, p := range file.Post.Parameters {
assert.NotEqualf(t, "path", p.In,
"no path parameter expected on /internal/file, got %q (issue #35)", p.Name)
}
// Control: the legitimate {id} path param must survive.
widget, ok := result.Paths["/widgets/{id}"]
require.True(t, ok, "/widgets/{id} must be present")
require.NotNil(t, widget.Get)
var pathParams []string
for _, p := range widget.Get.Parameters {
if p.In == "path" {
pathParams = append(pathParams, p.Name)
}
}
assert.Equal(t, []string{"id"}, pathParams,
"the {id} placeholder read via mux.Vars must remain a path parameter")
}
// TestE2E_SharedDecodeHelper_PerCallSiteBodyTypes asserts issue #39: a decode
// helper shared by two handlers with different DTOs resolves each endpoint to
// its own request type and keeps per-field format: uuid — for both the
// any-typed and the generic helper forms.
func TestE2E_SharedDecodeHelper_PerCallSiteBodyTypes(t *testing.T) {
for _, dir := range []string{"shared_decode_any", "shared_decode_generic", "shared_decode_methods"} {
t.Run(dir, func(t *testing.T) {
cfg := newDefaultCfg("../../testdata/"+dir, spec.DefaultChiConfig())
result, err := NewEngine(cfg).GenerateOpenAPI()
require.NoError(t, err)
refOf := func(path string) string {
pi, ok := result.Paths[path]
require.True(t, ok, "%s missing", path)
require.NotNil(t, pi.Post)
require.NotNil(t, pi.Post.RequestBody)
mt, ok := pi.Post.RequestBody.Content["application/json"]
require.True(t, ok, "%s json content missing", path)
require.NotNil(t, mt.Schema)
return mt.Schema.Ref
}
assert.Equal(t, "#/components/schemas/json_dto.CopyDocumentRequest", refOf("/copy"),
"copy endpoint must keep its own DTO")
assert.Equal(t, "#/components/schemas/json_dto.UpdateDocumentRequest", refOf("/update"),
"update endpoint must keep its own DTO (not collapse onto copy's)")
// Both schemas exist and retain their flow-inferred uuid formats.
require.NotNil(t, result.Components, "components missing")
schemas := result.Components.Schemas
assertUUIDField := func(typeName, prop string) {
schema := schemas[typeName]
require.NotNil(t, schema, "schema %s missing", typeName)
ps := schema.Properties[prop]
require.NotNil(t, ps, "property %s.%s missing", typeName, prop)
assert.Equal(t, "uuid", ps.Format, "%s.%s format", typeName, prop)
}
assertUUIDField("json_dto.CopyDocumentRequest", "sourceId")
assertUUIDField("json_dto.CopyDocumentRequest", "destinationBucketId")
assertUUIDField("json_dto.UpdateDocumentRequest", "storageBucketId")
})
}
}
// TestE2E_SharedDecodeRouter_ClosureRegisteredMethods asserts issue #41's
// residual case: method handlers registered via a deps-struct selector inside an
// r.Route(...) closure, sharing a free-function any-typed decode helper, must
// still resolve each endpoint to its own DTO with per-field format: uuid.
func TestE2E_SharedDecodeRouter_ClosureRegisteredMethods(t *testing.T) {
cfg := newDefaultCfg("../../testdata/shared_decode_router", spec.DefaultChiConfig())
result, err := NewEngine(cfg).GenerateOpenAPI()
require.NoError(t, err)
refOf := func(path, method string) string {
pi, ok := result.Paths[path]
require.True(t, ok, "%s missing", path)
op := map[string]*intspec.Operation{"POST": pi.Post, "PATCH": pi.Patch}[method]
require.NotNil(t, op, "%s %s missing", method, path)
require.NotNil(t, op.RequestBody)
mt, ok := op.RequestBody.Content["application/json"]
require.True(t, ok)
require.NotNil(t, mt.Schema)
return mt.Schema.Ref
}
assert.Equal(t, "#/components/schemas/handlers.CopyDocumentRequest", refOf("/internal/file/copy", "POST"))
assert.Equal(t, "#/components/schemas/handlers.UpdateDocumentRequest", refOf("/internal/file/{id}", "PATCH"))
require.NotNil(t, result.Components)
copyReq := result.Components.Schemas["handlers.CopyDocumentRequest"]
require.NotNil(t, copyReq, "CopyDocumentRequest schema must not be dropped")
for _, p := range []string{"sourceId", "destinationBucketId", "authorizationId"} {
ps := copyReq.Properties[p]
require.NotNil(t, ps, "property %s missing", p)
assert.Equal(t, "uuid", ps.Format, "%s format", p)
}
}
func paramNames(ps []intspec.Parameter) []string {
out := make([]string, 0, len(ps))
for _, p := range ps {
out = append(out, p.Name)
}
return out
}
func keysOf[V any](m map[string]V) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
return out
}
// TestE2E_EchoHandlerFactory_ClosureInterfaceAndLocalType covers the
// handler-factory pattern end to end: routes registered as g.POST(p, h.Create())
// where Create() returns a closure, dispatched through an interface whose
// implementation lives in a different package, and a request bound to a
// function-local named type.
func TestE2E_EchoHandlerFactory_ClosureInterfaceAndLocalType(t *testing.T) {
cfg := newDefaultCfg("../../testdata/echo_handler_factory", spec.DefaultEchoConfig())
result, err := NewEngine(cfg).GenerateOpenAPI()
require.NoError(t, err)
reqRef := func(path, method string) string {
pi, ok := result.Paths[path]
require.True(t, ok, "%s missing", path)
op := map[string]*intspec.Operation{"POST": pi.Post, "GET": pi.Get}[method]
require.NotNil(t, op, "%s %s missing", method, path)
require.NotNil(t, op.RequestBody, "%s %s request body missing — closure body not analyzed", method, path)
mt, ok := op.RequestBody.Content["application/json"]
require.True(t, ok)
require.NotNil(t, mt.Schema)
return mt.Schema.Ref
}
// Interface dispatch (api.Handlers -> handlers.userHandlers) + factory
// closure resolved: the request binds to models.User.
assert.Equal(t, "#/components/schemas/models.User", reqRef("/api/v1/users", "POST"))
// Function-local named type (type Login struct{…} inside the method) is
// captured as a real component, not a dangling $ref.
assert.Equal(t, "#/components/schemas/handlers.Login", reqRef("/api/v1/login", "POST"))
require.NotNil(t, result.Components)
login := result.Components.Schemas["handlers.Login"]
require.NotNil(t, login, "function-local Login type must be emitted as a component, not left dangling")
for _, p := range []string{"email", "password"} {
require.NotNil(t, login.Properties[p], "Login.%s property missing", p)
}
// The factory closure's response (c.JSON(200, &models.User{})) is recovered.
pi, ok := result.Paths["/api/v1/users/{id}"]
require.True(t, ok, "/api/v1/users/{id} missing")
require.NotNil(t, pi.Get)
ok200, ok := pi.Get.Responses["200"]
require.True(t, ok, "200 response missing")
mt, ok := ok200.Content["application/json"]
require.True(t, ok, "200 application/json content missing")
require.NotNil(t, mt.Schema)
assert.Equal(t, "#/components/schemas/models.User", mt.Schema.Ref)
}
// ---------------------------------------------------------------------------
// 1. TestE2E_Chi_FullPipeline
// ---------------------------------------------------------------------------
func TestE2E_Chi_FullPipeline(t *testing.T) {
cfg := newDefaultCfg("../../testdata/chi", spec.DefaultChiConfig())
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
require.NotNil(t, result)
// OpenAPI version
assert.Equal(t, "3.1.1", result.OpenAPI)
// Info
assert.NotEmpty(t, result.Info.Title)
assert.NotEmpty(t, result.Info.Version)
// Paths: expect at least some of the chi routes
require.NotEmpty(t, result.Paths, "expected non-empty Paths")
foundUsers := false
foundProducts := false
foundPayment := false
for path := range result.Paths {
if strings.Contains(path, "user") || strings.Contains(path, "User") {
foundUsers = true
}
if strings.Contains(path, "product") || strings.Contains(path, "Product") {
foundProducts = true
}
if strings.Contains(path, "payment") || strings.Contains(path, "Payment") || strings.Contains(path, "stripe") {
foundPayment = true
}
}
assert.True(t, foundUsers, "expected a path related to users; got paths: %v", pathKeys(result))
assert.True(t, foundProducts, "expected a path related to products; got paths: %v", pathKeys(result))
assert.True(t, foundPayment, "expected a path related to payment; got paths: %v", pathKeys(result))
// Operations have non-empty operationIds
ops := collectOperations(result)
require.NotEmpty(t, ops, "expected at least one operation")
for _, o := range ops {
assert.NotEmpty(t, o.op.OperationID, "operationId should be non-empty for %s %s", o.method, o.path)
}
// Components.Schemas is non-empty
require.NotNil(t, result.Components, "expected non-nil Components")
assert.NotEmpty(t, result.Components.Schemas, "expected non-empty schemas")
// Response status codes are present on at least some operations
foundResponseCodes := false
for _, o := range ops {
if len(o.op.Responses) > 0 {
foundResponseCodes = true
for code := range o.op.Responses {
assert.NotEmpty(t, code, "response status code should not be empty")
}
}
}
assert.True(t, foundResponseCodes, "expected at least one operation with response status codes")
}
// ---------------------------------------------------------------------------
// 2. TestE2E_Chi_Determinism
// ---------------------------------------------------------------------------
func TestE2E_Chi_Determinism(t *testing.T) {
cfg1 := newDefaultCfg("../../testdata/chi", spec.DefaultChiConfig())
eng1 := NewEngine(cfg1)
result1, err := eng1.GenerateOpenAPI()
require.NoError(t, err)
require.NotNil(t, result1)
cfg2 := newDefaultCfg("../../testdata/chi", spec.DefaultChiConfig())
eng2 := NewEngine(cfg2)
result2, err := eng2.GenerateOpenAPI()
require.NoError(t, err)
require.NotNil(t, result2)
json1, err := json.Marshal(result1)
require.NoError(t, err)
json2, err := json.Marshal(result2)
require.NoError(t, err)
assert.Equal(t, string(json1), string(json2), "two consecutive generations should produce identical JSON output")
}
// ---------------------------------------------------------------------------
// 3. TestE2E_Chi_ShortNames
// ---------------------------------------------------------------------------
func TestE2E_Chi_ShortNames(t *testing.T) {
chiCfg := spec.DefaultChiConfig()
// Default config has ShortNames nil (= true)
cfg := newDefaultCfg("../../testdata/chi", chiCfg)
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
require.NotNil(t, result)
// All operationIds should have no "/" character
ops := collectOperations(result)
require.NotEmpty(t, ops)
for _, o := range ops {
assert.NotContains(t, o.op.OperationID, "/",
"operationId %q should not contain '/' with short names", o.op.OperationID)
}
// All schema keys should have no "/" character
if result.Components != nil {
for key := range result.Components.Schemas {
assert.NotContains(t, key, "/",
"schema key %q should not contain '/' with short names", key)
}
}
// All $ref values should not contain full module path
refs := collectAllRefValues(result)
for _, ref := range refs {
assert.NotContains(t, ref, "github.com/antst/go-apispec/testdata/chi",
"$ref %q should not contain full module path with short names", ref)
}
}
// ---------------------------------------------------------------------------
// 4. TestE2E_Chi_LegacyNames
// ---------------------------------------------------------------------------
func TestE2E_Chi_LegacyNames(t *testing.T) {
chiCfg := spec.DefaultChiConfig()
f := false
chiCfg.ShortNames = &f
cfg := newDefaultCfg("../../testdata/chi", chiCfg)
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
require.NotNil(t, result)
// operationIds should contain the full module path
ops := collectOperations(result)
require.NotEmpty(t, ops)
foundLegacyOpID := false
for _, o := range ops {
if strings.Contains(o.op.OperationID, "github.com") || strings.Contains(o.op.OperationID, "ehabterra") {
foundLegacyOpID = true
break
}
}
assert.True(t, foundLegacyOpID,
"with ShortNames=false, at least one operationId should contain the full module path")
// Schema keys should contain underscored module path
if result.Components != nil && len(result.Components.Schemas) > 0 {
foundLegacySchema := false
for key := range result.Components.Schemas {
if strings.Contains(key, "ehabterra") || strings.Contains(key, "apispec") {
foundLegacySchema = true
break
}
}
assert.True(t, foundLegacySchema,
"with ShortNames=false, at least one schema key should contain module path components")
}
}
// ---------------------------------------------------------------------------
// 5. TestE2E_Gin_FullPipeline
// ---------------------------------------------------------------------------
func TestE2E_Gin_FullPipeline(t *testing.T) {
cfg := newDefaultCfg("../../testdata/gin", spec.DefaultGinConfig())
eng := NewEngine(cfg)
result, err := eng.GenerateOpenAPI()
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, "3.1.1", result.OpenAPI)
require.NotEmpty(t, result.Paths, "expected non-empty Paths for gin")
// Expect paths related to users
foundUsers := false
for path := range result.Paths {
if strings.Contains(strings.ToLower(path), "user") {
foundUsers = true
break
}
}
assert.True(t, foundUsers, "expected a path related to users; got paths: %v", pathKeys(result))
// Operations should have operationIds
ops := collectOperations(result)
require.NotEmpty(t, ops, "expected at least one operation for gin")
for _, o := range ops {
assert.NotEmpty(t, o.op.OperationID, "operationId should be non-empty for %s %s", o.method, o.path)
}
// User schema should exist
if result.Components != nil && len(result.Components.Schemas) > 0 {
foundUserSchema := false
for key := range result.Components.Schemas {
if strings.Contains(strings.ToLower(key), "user") {
foundUserSchema = true
break
}
}
assert.True(t, foundUserSchema, "expected User schema in components; got schemas: %v", schemaKeys(result))