Debian Codegraph @

paths/paths_test.go

raw
1 // Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package paths
5
6 import (
7 "fmt"
8 "net/http"
9 "os"
10 "regexp"
11 "sync"
12 "testing"
13
14 "github.com/pb33f/libopenapi"
15 "github.com/pb33f/libopenapi-validator/config"
16 "github.com/pb33f/libopenapi-validator/radix"
17 "github.com/stretchr/testify/assert"
18 )
19
20 func TestNewValidator_BadParam(t *testing.T) {
21 request, _ := http.NewRequest(http.MethodGet, "https://things.com/pet/doggy", nil)
22
23 // load a doc
24 b, _ := os.ReadFile("../test_specs/petstorev3.json")
25 doc, _ := libopenapi.NewDocument(b)
26
27 m, _ := doc.BuildV3Model()
28
29 pathItem, _, _ := FindPath(request, &m.Model, nil)
30 assert.NotNil(t, pathItem)
31 }
32
33 func TestNewValidator_GoodParamFloat(t *testing.T) {
34 request, _ := http.NewRequest(http.MethodGet, "https://things.com/pet/232.233", nil)
35
36 b, _ := os.ReadFile("../test_specs/petstorev3.json")
37 doc, _ := libopenapi.NewDocument(b)
38 m, _ := doc.BuildV3Model()
39
40 pathItem, _, _ := FindPath(request, &m.Model, nil)
41 assert.NotNil(t, pathItem)
42 }
43
44 func TestNewValidator_GoodParamInt(t *testing.T) {
45 request, _ := http.NewRequest(http.MethodGet, "https://things.com/pet/12334", nil)
46
47 b, _ := os.ReadFile("../test_specs/petstorev3.json")
48 doc, _ := libopenapi.NewDocument(b)
49
50 m, _ := doc.BuildV3Model()
51 pathItem, _, _ := FindPath(request, &m.Model, nil)
52 assert.NotNil(t, pathItem)
53 }
54
55 func TestNewValidator_FindSimpleEncodedArrayPath(t *testing.T) {
56 spec := `openapi: 3.1.0
57 paths:
58 /burgers/{burgerId*}/locate:
59 patch:
60 operationId: locateBurger
61 `
62
63 doc, _ := libopenapi.NewDocument([]byte(spec))
64
65 m, _ := doc.BuildV3Model()
66
67 request, _ := http.NewRequest(http.MethodPatch, "https://things.com/burgers/1,2,3,4,5/locate", nil)
68
69 pathItem, _, _ := FindPath(request, &m.Model, nil)
70 assert.NotNil(t, pathItem)
71 assert.Equal(t, "locateBurger", pathItem.Patch.OperationId)
72 }
73
74 func TestNewValidator_FindSimpleEncodedObjectPath(t *testing.T) {
75 spec := `openapi: 3.1.0
76 paths:
77 /burgers/{burgerId*}/locate:
78 patch:
79 operationId: locateBurger
80 `
81
82 doc, _ := libopenapi.NewDocument([]byte(spec))
83
84 m, _ := doc.BuildV3Model()
85
86 request, _ := http.NewRequest(http.MethodPatch, "https://things.com/burgers/bish=bosh,wish=wash/locate", nil)
87
88 pathItem, _, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
89 assert.NotNil(t, pathItem)
90 assert.Equal(t, "locateBurger", pathItem.Patch.OperationId)
91 }
92
93 func TestNewValidator_FindLabelEncodedArrayPath(t *testing.T) {
94 spec := `openapi: 3.1.0
95 paths:
96 /burgers/{.burgerId}/locate:
97 patch:
98 operationId: locateBurger
99 `
100
101 doc, _ := libopenapi.NewDocument([]byte(spec))
102
103 m, _ := doc.BuildV3Model()
104 request, _ := http.NewRequest(http.MethodPatch, "https://things.com/burgers/.1.2.3.4.5/locate", nil)
105
106 pathItem, _, _ := FindPath(request, &m.Model, nil)
107 assert.NotNil(t, pathItem)
108 assert.Equal(t, "locateBurger", pathItem.Patch.OperationId)
109 }
110
111 func TestNewValidator_FindPathPost(t *testing.T) {
112 // load a doc
113 b, _ := os.ReadFile("../test_specs/petstorev3.json")
114 doc, _ := libopenapi.NewDocument(b)
115
116 m, _ := doc.BuildV3Model()
117
118 request, _ := http.NewRequest(http.MethodPost, "https://things.com/pet/12334", nil)
119
120 pathItem, _, _ := FindPath(request, &m.Model, nil)
121 assert.NotNil(t, pathItem)
122 }
123
124 func TestNewValidator_FindPathDelete(t *testing.T) {
125 // load a doc
126 b, _ := os.ReadFile("../test_specs/petstorev3.json")
127 doc, _ := libopenapi.NewDocument(b)
128
129 m, _ := doc.BuildV3Model()
130 request, _ := http.NewRequest(http.MethodDelete, "https://things.com/pet/12334", nil)
131
132 pathItem, _, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
133 assert.NotNil(t, pathItem)
134 }
135
136 func TestNewValidator_FindPathPatch(t *testing.T) {
137 spec := `openapi: 3.1.0
138 paths:
139 /burgers/{burgerId}:
140 patch:
141 operationId: locateBurger
142 `
143
144 doc, _ := libopenapi.NewDocument([]byte(spec))
145 m, _ := doc.BuildV3Model()
146
147 request, _ := http.NewRequest(http.MethodPatch, "https://things.com/burgers/12345", nil)
148
149 pathItem, _, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
150 assert.NotNil(t, pathItem)
151 assert.Equal(t, "locateBurger", pathItem.Patch.OperationId)
152 }
153
154 func TestNewValidator_FindPathOptions(t *testing.T) {
155 spec := `openapi: 3.1.0
156 paths:
157 /burgers/{burgerId}:
158 options:
159 operationId: locateBurger
160 `
161
162 doc, _ := libopenapi.NewDocument([]byte(spec))
163
164 m, _ := doc.BuildV3Model()
165 request, _ := http.NewRequest(http.MethodOptions, "https://things.com/burgers/12345", nil)
166
167 pathItem, _, _ := FindPath(request, &m.Model, nil)
168 assert.NotNil(t, pathItem)
169 assert.Equal(t, "locateBurger", pathItem.Options.OperationId)
170 }
171
172 func TestNewValidator_FindPathTrace(t *testing.T) {
173 spec := `openapi: 3.1.0
174 paths:
175 /burgers/{burgerId}:
176 trace:
177 operationId: locateBurger
178 `
179
180 doc, _ := libopenapi.NewDocument([]byte(spec))
181 m, _ := doc.BuildV3Model()
182
183 request, _ := http.NewRequest(http.MethodTrace, "https://things.com/burgers/12345", nil)
184
185 pathItem, _, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
186 assert.NotNil(t, pathItem)
187 assert.Equal(t, "locateBurger", pathItem.Trace.OperationId)
188 }
189
190 func TestNewValidator_FindPathPut(t *testing.T) {
191 spec := `openapi: 3.1.0
192 paths:
193 /burgers/{burgerId}:
194 put:
195 operationId: locateBurger
196 `
197
198 doc, _ := libopenapi.NewDocument([]byte(spec))
199
200 m, _ := doc.BuildV3Model()
201
202 request, _ := http.NewRequest(http.MethodPut, "https://things.com/burgers/12345", nil)
203
204 pathItem, _, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
205 assert.NotNil(t, pathItem)
206 assert.Equal(t, "locateBurger", pathItem.Put.OperationId)
207 }
208
209 func TestNewValidator_FindPathHead(t *testing.T) {
210 spec := `openapi: 3.1.0
211 paths:
212 /burgers/{burgerId}:
213 head:
214 operationId: locateBurger
215 `
216
217 doc, _ := libopenapi.NewDocument([]byte(spec))
218 m, _ := doc.BuildV3Model()
219
220 request, _ := http.NewRequest(http.MethodHead, "https://things.com/burgers/12345", nil)
221
222 pathItem, _, _ := FindPath(request, &m.Model, nil)
223 assert.NotNil(t, pathItem)
224 assert.Equal(t, "locateBurger", pathItem.Head.OperationId)
225 }
226
227 func TestNewValidator_FindPathWithBaseURLInServer(t *testing.T) {
228 spec := `openapi: 3.1.0
229 servers:
230 - url: https://things.com/base1
231 - url: https://things.com/base2
232 - url: https://things.com/base3/base4/base5/base6/
233 paths:
234 /user:
235 post:
236 operationId: addUser
237 `
238
239 doc, _ := libopenapi.NewDocument([]byte(spec))
240 m, _ := doc.BuildV3Model()
241
242 // check against base1
243 request, _ := http.NewRequest(http.MethodPost, "https://things.com/base1/user", nil)
244 pathItem, _, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
245 assert.NotNil(t, pathItem)
246 assert.Equal(t, "addUser", pathItem.Post.OperationId)
247
248 // check against base2
249 request, _ = http.NewRequest(http.MethodPost, "https://things.com/base2/user", nil)
250 pathItem, _, _ = FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
251 assert.NotNil(t, pathItem)
252 assert.Equal(t, "addUser", pathItem.Post.OperationId)
253
254 // check against a deeper base
255 request, _ = http.NewRequest(http.MethodPost, "https://things.com/base3/base4/base5/base6/user", nil)
256 pathItem, _, _ = FindPath(request, &m.Model, nil)
257 assert.NotNil(t, pathItem)
258 assert.Equal(t, "addUser", pathItem.Post.OperationId)
259 }
260
261 func TestNewValidator_FindPathWithBaseURLInServer_Args(t *testing.T) {
262 spec := `openapi: 3.1.0
263 servers:
264 - url: https://things.com/base3/base4/base5/base6/
265 paths:
266 /user/{userId}/thing/{thingId}:
267 post:
268 operationId: addUser
269 `
270
271 doc, _ := libopenapi.NewDocument([]byte(spec))
272 m, _ := doc.BuildV3Model()
273
274 // check against a deeper base
275 request, _ := http.NewRequest(http.MethodPost, "https://things.com/base3/base4/base5/base6/user/1234/thing/abcd", nil)
276 pathItem, _, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
277 assert.NotNil(t, pathItem)
278 assert.Equal(t, "addUser", pathItem.Post.OperationId)
279 }
280
281 func TestNewValidator_FindPathMissing(t *testing.T) {
282 spec := `openapi: 3.1.0
283 paths:
284 /a/fishy/on/a/dishy:
285 head:
286 operationId: locateFishy
287 `
288
289 doc, _ := libopenapi.NewDocument([]byte(spec))
290
291 m, _ := doc.BuildV3Model()
292
293 request, _ := http.NewRequest(http.MethodHead, "https://things.com/not/here", nil)
294
295 pathItem, errs, _ := FindPath(request, &m.Model, nil)
296 assert.Nil(t, pathItem)
297 assert.NotNil(t, errs)
298 assert.Equal(t, "HEAD Path '/not/here' not found", errs[0].Message)
299 assert.True(t, errs[0].IsPathMissingError())
300 }
301
302 func TestNewValidator_FindOperationMissing(t *testing.T) {
303 spec := `openapi: 3.1.0
304 paths:
305 /burgers/{burgerId}:
306 trace:
307 operationId: locateBurger
308 `
309
310 doc, _ := libopenapi.NewDocument([]byte(spec))
311 m, _ := doc.BuildV3Model()
312
313 request, _ := http.NewRequest(http.MethodPut, "https://things.com/burgers/12345", nil)
314
315 pathItem, errs, _ := FindPath(request, &m.Model, nil)
316 assert.NotNil(t, pathItem)
317 assert.NotNil(t, errs)
318 assert.Equal(t, "PUT Path '/burgers/12345' not found", errs[0].Message)
319 assert.True(t, errs[0].IsOperationMissingError())
320 }
321
322 func TestNewValidator_GetLiteralMatch(t *testing.T) {
323 request, _ := http.NewRequest(http.MethodGet, "https://things.com/store/inventory", nil)
324
325 // load a doc
326 b, _ := os.ReadFile("../test_specs/petstorev3.json")
327 doc, _ := libopenapi.NewDocument(b)
328
329 m, _ := doc.BuildV3Model()
330
331 _, errs, _ := FindPath(request, &m.Model, nil)
332
333 assert.Len(t, errs, 0)
334 }
335
336 func TestNewValidator_PostLiteralMatch(t *testing.T) {
337 request, _ := http.NewRequest(http.MethodPost, "https://things.com/user", nil)
338
339 // load a doc
340 b, _ := os.ReadFile("../test_specs/petstorev3.json")
341 doc, _ := libopenapi.NewDocument(b)
342
343 m, _ := doc.BuildV3Model()
344
345 _, errs, _ := FindPath(request, &m.Model, nil)
346
347 assert.Len(t, errs, 0)
348 }
349
350 func TestNewValidator_PutLiteralMatch(t *testing.T) {
351 spec := `openapi: 3.1.0
352 paths:
353 /pizza/burger:
354 put:
355 operationId: locateBurger`
356
357 doc, _ := libopenapi.NewDocument([]byte(spec))
358 m, _ := doc.BuildV3Model()
359
360 request, _ := http.NewRequest(http.MethodPut, "https://things.com/pizza/burger", nil)
361
362 _, errs, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
363
364 assert.Len(t, errs, 0)
365 }
366
367 func TestNewValidator_PutMatch_Error(t *testing.T) {
368 spec := `openapi: 3.1.0
369 paths:
370 /pizza/{cakes}:
371 put:
372 operationId: locateBurger
373 parameters:
374 - name: cakes
375 in: path
376 required: true
377 schema:
378 type: string`
379
380 doc, _ := libopenapi.NewDocument([]byte(spec))
381 m, _ := doc.BuildV3Model()
382
383 request, _ := http.NewRequest(http.MethodPost, "https://things.com/pizza/1234", nil)
384
385 _, errs, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
386
387 assert.Len(t, errs, 1)
388 assert.Equal(t, "POST Path '/pizza/1234' not found", errs[0].Message)
389 }
390
391 func TestNewValidator_OptionsMatch_Error(t *testing.T) {
392 spec := `openapi: 3.1.0
393 paths:
394 /pizza/{cakes}:
395 options:
396 operationId: locateBurger
397 parameters:
398 - name: cakes
399 in: path
400 required: true
401 schema:
402 type: string`
403
404 doc, _ := libopenapi.NewDocument([]byte(spec))
405 m, _ := doc.BuildV3Model()
406
407 request, _ := http.NewRequest(http.MethodPost, "https://things.com/pizza/1234", nil)
408
409 _, errs, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
410
411 assert.Len(t, errs, 1)
412 assert.Equal(t, "POST Path '/pizza/1234' not found", errs[0].Message)
413 }
414
415 func TestNewValidator_PatchLiteralMatch(t *testing.T) {
416 spec := `openapi: 3.1.0
417 paths:
418 /pizza/burger:
419 patch:
420 operationId: locateBurger`
421
422 doc, _ := libopenapi.NewDocument([]byte(spec))
423 m, _ := doc.BuildV3Model()
424
425 request, _ := http.NewRequest(http.MethodPatch, "https://things.com/pizza/burger", nil)
426
427 _, errs, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
428
429 assert.Len(t, errs, 0)
430 }
431
432 func TestNewValidator_PatchMatch_Error(t *testing.T) {
433 spec := `openapi: 3.1.0
434 paths:
435 /pizza/{cakes}:
436 patch:
437 operationId: locateBurger
438 parameters:
439 - name: cakes
440 in: path
441 required: true
442 schema:
443 type: string`
444
445 doc, _ := libopenapi.NewDocument([]byte(spec))
446 m, _ := doc.BuildV3Model()
447
448 request, _ := http.NewRequest(http.MethodPost, "https://things.com/pizza/1234", nil)
449
450 _, errs, _ := FindPath(request, &m.Model, nil)
451
452 assert.Len(t, errs, 1)
453 assert.Equal(t, "POST Path '/pizza/1234' not found", errs[0].Message)
454 }
455
456 func TestNewValidator_DeleteLiteralMatch(t *testing.T) {
457 spec := `openapi: 3.1.0
458 paths:
459 /pizza/burger:
460 delete:
461 operationId: locateBurger`
462
463 doc, _ := libopenapi.NewDocument([]byte(spec))
464 m, _ := doc.BuildV3Model()
465
466 request, _ := http.NewRequest(http.MethodDelete, "https://things.com/pizza/burger", nil)
467
468 _, errs, _ := FindPath(request, &m.Model, nil)
469
470 assert.Len(t, errs, 0)
471 }
472
473 func TestNewValidator_OptionsLiteralMatch(t *testing.T) {
474 spec := `openapi: 3.1.0
475 paths:
476 /pizza/burger:
477 options:
478 operationId: locateBurger`
479
480 doc, _ := libopenapi.NewDocument([]byte(spec))
481 m, _ := doc.BuildV3Model()
482
483 request, _ := http.NewRequest(http.MethodOptions, "https://things.com/pizza/burger", nil)
484
485 _, errs, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
486
487 assert.Len(t, errs, 0)
488 }
489
490 func TestNewValidator_HeadLiteralMatch(t *testing.T) {
491 spec := `openapi: 3.1.0
492 paths:
493 /pizza/burger:
494 head:
495 operationId: locateBurger`
496
497 doc, _ := libopenapi.NewDocument([]byte(spec))
498 m, _ := doc.BuildV3Model()
499
500 request, _ := http.NewRequest(http.MethodHead, "https://things.com/pizza/burger", nil)
501
502 _, errs, _ := FindPath(request, &m.Model, nil)
503
504 assert.Len(t, errs, 0)
505 }
506
507 func TestNewValidator_TraceLiteralMatch(t *testing.T) {
508 spec := `openapi: 3.1.0
509 paths:
510 /pizza/burger:
511 trace:
512 operationId: locateBurger`
513
514 doc, _ := libopenapi.NewDocument([]byte(spec))
515 m, _ := doc.BuildV3Model()
516
517 request, _ := http.NewRequest(http.MethodTrace, "https://things.com/pizza/burger", nil)
518
519 _, errs, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
520
521 assert.Len(t, errs, 0)
522 }
523
524 func TestNewValidator_TraceMatch_Error(t *testing.T) {
525 spec := `openapi: 3.1.0
526 paths:
527 /pizza/{cakes}:
528 trace:
529 operationId: locateBurger
530 parameters:
531 - name: cakes
532 in: path
533 required: true
534 schema:
535 type: string`
536
537 doc, _ := libopenapi.NewDocument([]byte(spec))
538 m, _ := doc.BuildV3Model()
539
540 request, _ := http.NewRequest(http.MethodPost, "https://things.com/pizza/1234", nil)
541
542 _, errs, _ := FindPath(request, &m.Model, nil)
543
544 assert.Len(t, errs, 1)
545 assert.Equal(t, "POST Path '/pizza/1234' not found", errs[0].Message)
546 }
547
548 func TestNewValidator_DeleteMatch_Error(t *testing.T) {
549 spec := `openapi: 3.1.0
550 paths:
551 /pizza/{cakes}:
552 delete:
553 operationId: locateBurger
554 parameters:
555 - name: cakes
556 in: path
557 required: true
558 schema:
559 type: string`
560
561 doc, _ := libopenapi.NewDocument([]byte(spec))
562 m, _ := doc.BuildV3Model()
563
564 request, _ := http.NewRequest(http.MethodPost, "https://things.com/pizza/1234", nil)
565
566 _, errs, _ := FindPath(request, &m.Model, nil)
567
568 assert.Len(t, errs, 1)
569 assert.Equal(t, "POST Path '/pizza/1234' not found", errs[0].Message)
570 }
571
572 func TestNewValidator_PostMatch_Error(t *testing.T) {
573 spec := `openapi: 3.1.0
574 paths:
575 /pizza/{cakes}:
576 post:
577 operationId: locateBurger
578 parameters:
579 - name: cakes
580 in: path
581 required: true
582 schema:
583 type: string`
584
585 doc, _ := libopenapi.NewDocument([]byte(spec))
586 m, _ := doc.BuildV3Model()
587
588 request, _ := http.NewRequest(http.MethodPut, "https://things.com/pizza/1234", nil)
589
590 _, errs, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
591
592 assert.Len(t, errs, 1)
593 assert.Equal(t, "PUT Path '/pizza/1234' not found", errs[0].Message)
594 }
595
596 func TestNewValidator_FindPathWithFragment(t *testing.T) {
597 spec := `openapi: 3.1.0
598 paths:
599 /hashy#one:
600 post:
601 operationId: one
602 /hashy#two:
603 post:
604 operationId: two
605 `
606
607 doc, _ := libopenapi.NewDocument([]byte(spec))
608 m, _ := doc.BuildV3Model()
609
610 request, _ := http.NewRequest(http.MethodPost, "https://things.com/hashy#one", nil)
611
612 pathItem, errs, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
613 assert.Len(t, errs, 0)
614 assert.NotNil(t, pathItem)
615 assert.Equal(t, "one", pathItem.Post.OperationId)
616
617 request, _ = http.NewRequest(http.MethodPost, "https://things.com/hashy#two", nil)
618 pathItem, errs, _ = FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
619 assert.Len(t, errs, 0)
620 assert.NotNil(t, pathItem)
621 assert.Equal(t, "two", pathItem.Post.OperationId)
622 }
623
624 func TestNewValidator_FindPathMissingWithBaseURLInServer(t *testing.T) {
625 spec := `openapi: 3.1.0
626 servers:
627 - url: 'https://things.com/'
628 paths:
629 /dishy:
630 get:
631 operationId: one
632 `
633
634 doc, err := libopenapi.NewDocument([]byte(spec))
635 if err != nil {
636 t.Fatal(err)
637 }
638 m, _ := doc.BuildV3Model()
639
640 request, _ := http.NewRequest(http.MethodGet, "https://things.com/not_here", nil)
641
642 _, errs, _ := FindPath(request, &m.Model, nil)
643 assert.Len(t, errs, 1)
644 assert.Equal(t, "GET Path '/not_here' not found", errs[0].Message)
645 }
646
647 func TestStripRequestPath(t *testing.T) {
648 tests := []struct {
649 name string
650 servers []string
651 reqURL string
652 want string
653 }{
654 {
655 name: "no servers, no base path to strip",
656 servers: nil,
657 reqURL: "https://things.com/users",
658 want: "/users",
659 },
660 {
661 name: "host-only server URL leaves request path untouched",
662 servers: []string{"https://things.com"},
663 reqURL: "https://things.com/users",
664 want: "/users",
665 },
666 {
667 name: "base path prefix stripped from request path",
668 servers: []string{"https://things.com/api"},
669 reqURL: "https://things.com/api/users",
670 want: "/users",
671 },
672 {
673 name: "base path fully consumes request path yields /",
674 servers: []string{"https://things.com/v1beta/weather"},
675 reqURL: "https://things.com/v1beta/weather",
676 want: "/",
677 },
678 {
679 name: "fragment preserved after stripping",
680 servers: []string{"https://things.com/api"},
681 reqURL: "https://things.com/api/users#frag",
682 want: "/users#frag",
683 },
684 }
685
686 for _, test := range tests {
687 t.Run(test.name, func(t *testing.T) {
688 t.Parallel()
689
690 spec := "openapi: 3.1.0\n"
691 if len(test.servers) > 0 {
692 spec += "servers:\n"
693 for _, s := range test.servers {
694 spec += fmt.Sprintf(" - url: %q\n", s)
695 }
696 }
697 spec += "paths:\n /users:\n get:\n operationId: one\n"
698
699 doc, err := libopenapi.NewDocument([]byte(spec))
700 assert.NoError(t, err)
701 m, _ := doc.BuildV3Model()
702
703 req, _ := http.NewRequest(http.MethodGet, test.reqURL, nil)
704
705 assert.Equal(t, test.want, StripRequestPath(req, &m.Model))
706 })
707 }
708 }
709
710 func TestNewValidator_FindPath_BasePathFullyConsumesRequestPath(t *testing.T) {
711 spec := `openapi: 3.1.0
712 servers:
713 - url: https://things.com/v1beta/weather
714 paths:
715 /:
716 post:
717 operationId: rootOp
718 `
719
720 doc, err := libopenapi.NewDocument([]byte(spec))
721 if err != nil {
722 t.Fatal(err)
723 }
724 m, _ := doc.BuildV3Model()
725
726 request, _ := http.NewRequest(http.MethodPost,
727 "https://things.com/v1beta/weather", nil)
728
729 pathItem, errs, matched := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
730
731 assert.Empty(t, errs)
732 assert.NotNil(t, pathItem)
733 assert.Equal(t, "rootOp", pathItem.Post.OperationId)
734 assert.Equal(t, "/", matched)
735 }
736
737 func TestGetBasePaths(t *testing.T) {
738 spec := `openapi: 3.1.0
739 servers:
740 - url: 'https://things.com/'
741 - url: 'https://things.com/some/path'
742 - url: 'https://things.com/more//paths//please'
743 - url: 'https://{invalid}.com/'
744 - url: 'https://{invalid}.com/some/path'
745 - url: 'https://{invalid}.com/more//paths//please'
746 - url: 'https://{invalid}.com//even//more//paths//please'
747 paths:
748 /dishy:
749 get:
750 operationId: one
751 `
752
753 doc, err := libopenapi.NewDocument([]byte(spec))
754 if err != nil {
755 t.Fatal(err)
756 }
757 m, _ := doc.BuildV3Model()
758
759 basePaths := getBasePaths(&m.Model)
760
761 expectedPaths := []string{
762 "/",
763 "/some/path",
764 "/more//paths//please",
765 "/",
766 "/some/path",
767 "/more//paths//please",
768 "/even//more//paths//please",
769 }
770
771 assert.Equal(t, expectedPaths, basePaths)
772 }
773
774 func TestNewValidator_FindPathWithEncodedArg(t *testing.T) {
775 spec := `openapi: 3.1.0
776 paths:
777 /something/{string_contains_encoded}:
778 put:
779 operationId: putSomething
780 `
781
782 doc, _ := libopenapi.NewDocument([]byte(spec))
783
784 m, _ := doc.BuildV3Model()
785
786 request, _ := http.NewRequest(http.MethodPut, "https://things.com/something/pkg%3Agithub%2Frs%2Fzerolog%40v1.18.0", nil)
787
788 pathItem, errs, _ := FindPath(request, &m.Model, nil)
789
790 assert.Equal(t, 0, len(errs), "Errors found: %v", errs)
791 assert.NotNil(t, pathItem)
792 }
793
794 func TestNewValidator_ODataFormattedOpenAPISpecs(t *testing.T) {
795 spec := `openapi: 3.0.0
796 paths:
797 /entities('{Entity}'):
798 parameters:
799 - description: 'key: Entity'
800 in: path
801 name: Entity
802 required: true
803 schema:
804 type: integer
805 get:
806 operationId: one
807 /orders(RelationshipNumber='{RelationshipNumber}',ValidityEndDate=datetime'{ValidityEndDate}'):
808 parameters:
809 - name: RelationshipNumber
810 in: path
811 required: true
812 schema:
813 type: integer
814 - name: ValidityEndDate
815 in: path
816 required: true
817 schema:
818 type: string
819 get:
820 operationId: one
821 `
822 doc, _ := libopenapi.NewDocument([]byte(spec))
823
824 m, _ := doc.BuildV3Model()
825
826 request, _ := http.NewRequest(http.MethodGet, "https://things.com/entities('1')", nil)
827
828 pathItem, _, _ := FindPath(request, &m.Model, nil)
829 assert.NotNil(t, pathItem)
830 assert.Equal(t, "one", pathItem.Get.OperationId)
831
832 request, _ = http.NewRequest(http.MethodGet, "https://things.com/orders(RelationshipNumber='1234',ValidityEndDate=datetime'1492041600000')", nil)
833
834 pathItem, _, _ = FindPath(request, &m.Model, nil)
835 assert.NotNil(t, pathItem)
836 assert.Equal(t, "one", pathItem.Get.OperationId)
837
838 request, _ = http.NewRequest(http.MethodGet, "https://things.com/orders(RelationshipNumber='dummy',ValidityEndDate=datetime'1492041600000')", nil)
839
840 pathItem, _, _ = FindPath(request, &m.Model, nil)
841 assert.NotNil(t, pathItem)
842 assert.Equal(t, "one", pathItem.Get.OperationId)
843 }
844
845 func TestNewValidator_ODataFormattedOpenAPISpecsWithRegexCache(t *testing.T) {
846 spec := `openapi: 3.0.0
847 paths:
848 /entities('{Entity}'):
849 parameters:
850 - description: 'key: Entity'
851 in: path
852 name: Entity
853 required: true
854 schema:
855 type: integer
856 get:
857 operationId: one
858 /orders(RelationshipNumber='{RelationshipNumber}',ValidityEndDate=datetime'{ValidityEndDate}'):
859 parameters:
860 - name: RelationshipNumber
861 in: path
862 required: true
863 schema:
864 type: integer
865 - name: ValidityEndDate
866 in: path
867 required: true
868 schema:
869 type: string
870 get:
871 operationId: one
872 `
873 doc, _ := libopenapi.NewDocument([]byte(spec))
874
875 m, _ := doc.BuildV3Model()
876
877 request, _ := http.NewRequest(http.MethodGet, "https://things.com/entities('1')", nil)
878
879 opts := &config.ValidationOptions{RegexCache: &sync.Map{}}
880
881 pathItem, _, _ := FindPath(request, &m.Model, opts)
882 assert.NotNil(t, pathItem)
883 assert.Equal(t, "one", pathItem.Get.OperationId)
884
885 request, _ = http.NewRequest(http.MethodGet, "https://things.com/orders(RelationshipNumber='1234',ValidityEndDate=datetime'1492041600000')", nil)
886
887 pathItem, _, _ = FindPath(request, &m.Model, opts)
888 assert.NotNil(t, pathItem)
889 assert.Equal(t, "one", pathItem.Get.OperationId)
890
891 request, _ = http.NewRequest(http.MethodGet, "https://things.com/orders(RelationshipNumber='dummy',ValidityEndDate=datetime'1492041600000')", nil)
892
893 pathItem, _, _ = FindPath(request, &m.Model, opts)
894 assert.NotNil(t, pathItem)
895 assert.Equal(t, "one", pathItem.Get.OperationId)
896 }
897
898 func TestNewValidator_ODataFormattedOpenAPISpecs_Error(t *testing.T) {
899 spec := `openapi: 3.0.0
900 paths:
901 /entities('{Entity'):
902 parameters:
903 - in: path
904 name: Entity
905 required: true
906 schema:
907 type: integer
908 get:
909 operationId: one
910 `
911 doc, _ := libopenapi.NewDocument([]byte(spec))
912
913 m, _ := doc.BuildV3Model()
914
915 request, _ := http.NewRequest(http.MethodGet, "https://things.com/entities('1')", nil)
916
917 _, errs, _ := FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
918 assert.NotEmpty(t, errs)
919 }
920
921 func TestNewValidator_FindPathWithRegexpCache_ODataPath(t *testing.T) {
922 // OData-style paths have embedded parameters that the radix tree can't handle,
923 // so they fall back to regex matching which DOES populate the cache.
924 spec := `openapi: 3.1.0
925 paths:
926 /entities('{Entity}')/items:
927 head:
928 operationId: getEntityItems`
929
930 doc, _ := libopenapi.NewDocument([]byte(spec))
931 m, _ := doc.BuildV3Model()
932
933 request, _ := http.NewRequest(http.MethodHead, "https://things.com/entities('123')/items", nil)
934
935 syncMap := sync.Map{}
936 opts := &config.ValidationOptions{RegexCache: &syncMap}
937
938 _, errs, _ := FindPath(request, &m.Model, opts)
939
940 keys := []string{}
941 addresses := make(map[string]bool)
942
943 syncMap.Range(func(key, value any) bool {
944 keys = append(keys, key.(string))
945 addresses[fmt.Sprintf("%p", value)] = true
946 return true
947 })
948
949 // The OData segment should be cached
950 cached, found := syncMap.Load("entities('{Entity}')")
951
952 assert.True(t, found, "OData path segment should be in regex cache")
953 assert.NotNil(t, cached, "Cached regex should not be nil")
954 assert.True(t, cached.(*regexp.Regexp).MatchString("entities('123')"), "Cached regex should match")
955 assert.Len(t, errs, 0)
956 assert.Len(t, keys, 2, "Should have 2 path segments cached")
957 }
958
959 // Test cases for path precedence - Issue #181
960 // According to OpenAPI spec, literal paths take precedence over parameterized paths
961
962 func TestFindPath_LiteralTakesPrecedenceOverParameter(t *testing.T) {
963 // This is the exact bug case from issue #181
964 spec := `openapi: 3.1.0
965 info:
966 title: Path Precedence Bug
967 version: 1.0.0
968 paths:
969 /Messages/{message_id}:
970 parameters:
971 - name: message_id
972 in: path
973 required: true
974 schema:
975 type: string
976 pattern: '^comms_message_[0-7][a-hjkmnpqrstv-z0-9]{25,34}'
977 get:
978 operationId: getMessage
979 responses:
980 '200':
981 description: OK
982 /Messages/Operations:
983 get:
984 operationId: getOperations
985 summary: List Operations
986 responses:
987 '200':
988 description: OK
989 `
990 doc, _ := libopenapi.NewDocument([]byte(spec))
991 m, _ := doc.BuildV3Model()
992
993 // Request to literal path should match literal, not parameter
994 request, _ := http.NewRequest(http.MethodGet, "https://api.com/Messages/Operations", nil)
995 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
996
997 assert.Nil(t, errs, "Expected no errors")
998 assert.NotNil(t, pathItem, "Expected pathItem to be found")
999 assert.Equal(t, "getOperations", pathItem.Get.OperationId, "Should match literal path")
1000 assert.Equal(t, "/Messages/Operations", foundPath)
1001 }
1002
1003 func TestFindPath_LiteralPrecedence_ReverseOrder(t *testing.T) {
1004 // Same test but with paths defined in opposite order
1005 // Result should be the same - literal always wins
1006 spec := `openapi: 3.1.0
1007 info:
1008 title: Path Precedence Test
1009 version: 1.0.0
1010 paths:
1011 /Messages/Operations:
1012 get:
1013 operationId: getOperations
1014 responses:
1015 '200':
1016 description: OK
1017 /Messages/{message_id}:
1018 get:
1019 operationId: getMessage
1020 responses:
1021 '200':
1022 description: OK
1023 `
1024 doc, _ := libopenapi.NewDocument([]byte(spec))
1025 m, _ := doc.BuildV3Model()
1026
1027 request, _ := http.NewRequest(http.MethodGet, "https://api.com/Messages/Operations", nil)
1028 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1029
1030 assert.Nil(t, errs)
1031 assert.NotNil(t, pathItem)
1032 assert.Equal(t, "getOperations", pathItem.Get.OperationId)
1033 assert.Equal(t, "/Messages/Operations", foundPath)
1034 }
1035
1036 func TestFindPath_ParameterStillMatchesNonLiteral(t *testing.T) {
1037 spec := `openapi: 3.1.0
1038 info:
1039 title: Path Precedence Test
1040 version: 1.0.0
1041 paths:
1042 /Messages/{message_id}:
1043 get:
1044 operationId: getMessage
1045 responses:
1046 '200':
1047 description: OK
1048 /Messages/Operations:
1049 get:
1050 operationId: getOperations
1051 responses:
1052 '200':
1053 description: OK
1054 `
1055 doc, _ := libopenapi.NewDocument([]byte(spec))
1056 m, _ := doc.BuildV3Model()
1057
1058 // Request to a non-literal value should match parameter path
1059 request, _ := http.NewRequest(http.MethodGet, "https://api.com/Messages/12345", nil)
1060 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1061
1062 assert.Nil(t, errs)
1063 assert.NotNil(t, pathItem)
1064 assert.Equal(t, "getMessage", pathItem.Get.OperationId)
1065 assert.Equal(t, "/Messages/{message_id}", foundPath)
1066 }
1067
1068 func TestFindPath_MultipleParameterLevels(t *testing.T) {
1069 spec := `openapi: 3.1.0
1070 info:
1071 title: Path Precedence Test
1072 version: 1.0.0
1073 paths:
1074 /api/{version}/users/{id}:
1075 get:
1076 operationId: getUserVersioned
1077 responses:
1078 '200':
1079 description: OK
1080 /api/v1/users/{id}:
1081 get:
1082 operationId: getUserV1
1083 responses:
1084 '200':
1085 description: OK
1086 /api/v1/users/me:
1087 get:
1088 operationId: getCurrentUser
1089 responses:
1090 '200':
1091 description: OK
1092 `
1093 doc, _ := libopenapi.NewDocument([]byte(spec))
1094 m, _ := doc.BuildV3Model()
1095
1096 tests := []struct {
1097 url string
1098 expectedOp string
1099 expectedPath string
1100 }{
1101 // Most specific: all literals
1102 {"https://api.com/api/v1/users/me", "getCurrentUser", "/api/v1/users/me"},
1103 // More specific: 3 literals + 1 param
1104 {"https://api.com/api/v1/users/123", "getUserV1", "/api/v1/users/{id}"},
1105 // Least specific: 2 literals + 2 params
1106 {"https://api.com/api/v2/users/123", "getUserVersioned", "/api/{version}/users/{id}"},
1107 }
1108
1109 for _, tt := range tests {
1110 t.Run(tt.url, func(t *testing.T) {
1111 request, _ := http.NewRequest(http.MethodGet, tt.url, nil)
1112 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1113
1114 assert.Nil(t, errs)
1115 assert.NotNil(t, pathItem)
1116 assert.Equal(t, tt.expectedOp, pathItem.Get.OperationId)
1117 assert.Equal(t, tt.expectedPath, foundPath)
1118 })
1119 }
1120 }
1121
1122 func TestFindPath_PetsMinePrecedence(t *testing.T) {
1123 // Classic example from OpenAPI spec: /pets/mine vs /pets/{petId}
1124 spec := `openapi: 3.1.0
1125 info:
1126 title: Petstore
1127 version: 1.0.0
1128 paths:
1129 /pets/{petId}:
1130 get:
1131 operationId: getPet
1132 responses:
1133 '200':
1134 description: OK
1135 /pets/mine:
1136 get:
1137 operationId: getMyPets
1138 responses:
1139 '200':
1140 description: OK
1141 `
1142 doc, _ := libopenapi.NewDocument([]byte(spec))
1143 m, _ := doc.BuildV3Model()
1144
1145 // /pets/mine should match literal path
1146 request, _ := http.NewRequest(http.MethodGet, "https://api.com/pets/mine", nil)
1147 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1148
1149 assert.Nil(t, errs)
1150 assert.Equal(t, "getMyPets", pathItem.Get.OperationId)
1151 assert.Equal(t, "/pets/mine", foundPath)
1152
1153 // /pets/123 should match parameter path
1154 request, _ = http.NewRequest(http.MethodGet, "https://api.com/pets/123", nil)
1155 pathItem, errs, foundPath = FindPath(request, &m.Model, nil)
1156
1157 assert.Nil(t, errs)
1158 assert.Equal(t, "getPet", pathItem.Get.OperationId)
1159 assert.Equal(t, "/pets/{petId}", foundPath)
1160 }
1161
1162 func TestFindPath_DeepNestedPrecedence(t *testing.T) {
1163 spec := `openapi: 3.1.0
1164 info:
1165 title: Nested Paths
1166 version: 1.0.0
1167 paths:
1168 /api/{version}/resources/{id}/actions/{action}:
1169 get:
1170 operationId: genericAction
1171 responses:
1172 '200':
1173 description: OK
1174 /api/v1/resources/{id}/actions/delete:
1175 get:
1176 operationId: deleteResource
1177 responses:
1178 '200':
1179 description: OK
1180 /api/v1/resources/special/actions/delete:
1181 get:
1182 operationId: deleteSpecial
1183 responses:
1184 '200':
1185 description: OK
1186 `
1187 doc, _ := libopenapi.NewDocument([]byte(spec))
1188 m, _ := doc.BuildV3Model()
1189
1190 tests := []struct {
1191 url string
1192 expectedOp string
1193 expectedPath string
1194 }{
1195 // All literals - most specific
1196 {"https://api.com/api/v1/resources/special/actions/delete", "deleteSpecial", "/api/v1/resources/special/actions/delete"},
1197 // 5 literals + 1 param
1198 {"https://api.com/api/v1/resources/123/actions/delete", "deleteResource", "/api/v1/resources/{id}/actions/delete"},
1199 // 3 literals + 3 params - least specific
1200 {"https://api.com/api/v2/resources/123/actions/update", "genericAction", "/api/{version}/resources/{id}/actions/{action}"},
1201 }
1202
1203 for _, tt := range tests {
1204 t.Run(tt.url, func(t *testing.T) {
1205 request, _ := http.NewRequest(http.MethodGet, tt.url, nil)
1206 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1207
1208 assert.Nil(t, errs)
1209 assert.NotNil(t, pathItem)
1210 assert.Equal(t, tt.expectedOp, pathItem.Get.OperationId)
1211 assert.Equal(t, tt.expectedPath, foundPath)
1212 })
1213 }
1214 }
1215
1216 func TestFindPath_MethodMismatchUsesHighestScore(t *testing.T) {
1217 // When path matches but method doesn't exist, error should reference
1218 // the most specific matching path
1219 spec := `openapi: 3.1.0
1220 info:
1221 title: Method Mismatch Test
1222 version: 1.0.0
1223 paths:
1224 /users/{id}:
1225 get:
1226 operationId: getUser
1227 responses:
1228 '200':
1229 description: OK
1230 /users/admin:
1231 get:
1232 operationId: getAdmin
1233 responses:
1234 '200':
1235 description: OK
1236 `
1237 doc, _ := libopenapi.NewDocument([]byte(spec))
1238 m, _ := doc.BuildV3Model()
1239
1240 // POST to /users/admin - literal path should be chosen for error
1241 request, _ := http.NewRequest(http.MethodPost, "https://api.com/users/admin", nil)
1242 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1243
1244 assert.NotNil(t, errs)
1245 assert.Len(t, errs, 1)
1246 assert.Equal(t, "/users/admin", foundPath)
1247 assert.NotNil(t, pathItem)
1248 assert.True(t, errs[0].IsOperationMissingError())
1249 }
1250
1251 func TestFindPath_WithQueryParams(t *testing.T) {
1252 // Ensure query params don't affect path matching precedence
1253 spec := `openapi: 3.1.0
1254 info:
1255 title: Query Params Test
1256 version: 1.0.0
1257 paths:
1258 /Messages/{message_id}:
1259 get:
1260 operationId: getMessage
1261 responses:
1262 '200':
1263 description: OK
1264 /Messages/Operations:
1265 get:
1266 operationId: getOperations
1267 parameters:
1268 - name: start_date
1269 in: query
1270 schema:
1271 type: string
1272 - name: end_date
1273 in: query
1274 schema:
1275 type: string
1276 responses:
1277 '200':
1278 description: OK
1279 `
1280 doc, _ := libopenapi.NewDocument([]byte(spec))
1281 m, _ := doc.BuildV3Model()
1282
1283 // This is the exact request from issue #181
1284 request, _ := http.NewRequest(http.MethodGet,
1285 "https://api.com/Messages/Operations?start_date=2020-01-01T00:00:00Z&end_date=2025-12-31T23:59:59Z&page_size=10", nil)
1286 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1287
1288 assert.Nil(t, errs)
1289 assert.NotNil(t, pathItem)
1290 assert.Equal(t, "getOperations", pathItem.Get.OperationId)
1291 assert.Equal(t, "/Messages/Operations", foundPath)
1292 }
1293
1294 func TestFindPath_WithRegexCache(t *testing.T) {
1295 // Ensure precedence works correctly with regex cache
1296 spec := `openapi: 3.1.0
1297 info:
1298 title: Cache Test
1299 version: 1.0.0
1300 paths:
1301 /Messages/{message_id}:
1302 get:
1303 operationId: getMessage
1304 responses:
1305 '200':
1306 description: OK
1307 /Messages/Operations:
1308 get:
1309 operationId: getOperations
1310 responses:
1311 '200':
1312 description: OK
1313 `
1314 doc, _ := libopenapi.NewDocument([]byte(spec))
1315 m, _ := doc.BuildV3Model()
1316
1317 opts := &config.ValidationOptions{RegexCache: &sync.Map{}}
1318
1319 // First request - populates cache
1320 request, _ := http.NewRequest(http.MethodGet, "https://api.com/Messages/Operations", nil)
1321 pathItem, errs, foundPath := FindPath(request, &m.Model, opts)
1322
1323 assert.Nil(t, errs)
1324 assert.Equal(t, "getOperations", pathItem.Get.OperationId)
1325 assert.Equal(t, "/Messages/Operations", foundPath)
1326
1327 // Second request - uses cache
1328 request, _ = http.NewRequest(http.MethodGet, "https://api.com/Messages/12345", nil)
1329 pathItem, errs, foundPath = FindPath(request, &m.Model, opts)
1330
1331 assert.Nil(t, errs)
1332 assert.Equal(t, "getMessage", pathItem.Get.OperationId)
1333 assert.Equal(t, "/Messages/{message_id}", foundPath)
1334
1335 // Third request - still works correctly
1336 request, _ = http.NewRequest(http.MethodGet, "https://api.com/Messages/Operations", nil)
1337 pathItem, errs, foundPath = FindPath(request, &m.Model, opts)
1338
1339 assert.Nil(t, errs)
1340 assert.Equal(t, "getOperations", pathItem.Get.OperationId)
1341 assert.Equal(t, "/Messages/Operations", foundPath)
1342 }
1343
1344 func TestFindPath_WithFragment(t *testing.T) {
1345 // Test that request paths with fragments are handled correctly
1346 spec := `openapi: 3.1.0
1347 info:
1348 title: Fragment Test
1349 version: 1.0.0
1350 paths:
1351 /users/{id}:
1352 get:
1353 operationId: getUser
1354 responses:
1355 '200':
1356 description: OK
1357 `
1358 doc, _ := libopenapi.NewDocument([]byte(spec))
1359 m, _ := doc.BuildV3Model()
1360
1361 // Request with fragment in URL
1362 request, _ := http.NewRequest(http.MethodGet, "https://api.com/users/123#section", nil)
1363 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1364
1365 assert.Nil(t, errs)
1366 assert.NotNil(t, pathItem)
1367 assert.Equal(t, "getUser", pathItem.Get.OperationId)
1368 assert.Equal(t, "/users/{id}", foundPath)
1369 }
1370
1371 func TestFindPath_WithTrailingSlashBasePath(t *testing.T) {
1372 // Test that base paths with trailing slash work correctly
1373 spec := `openapi: 3.1.0
1374 info:
1375 title: Trailing Slash Test
1376 version: 1.0.0
1377 servers:
1378 - url: https://api.com/v1/
1379 paths:
1380 /users:
1381 get:
1382 operationId: getUsers
1383 responses:
1384 '200':
1385 description: OK
1386 `
1387 doc, _ := libopenapi.NewDocument([]byte(spec))
1388 m, _ := doc.BuildV3Model()
1389
1390 // Request to path that includes base with trailing slash
1391 request, _ := http.NewRequest(http.MethodGet, "https://api.com/v1/users", nil)
1392 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1393
1394 assert.Nil(t, errs)
1395 assert.NotNil(t, pathItem)
1396 assert.Equal(t, "getUsers", pathItem.Get.OperationId)
1397 assert.Equal(t, "/users", foundPath)
1398 }
1399
1400 func TestFindPath_PathTemplateWithFragment_RequestWithoutFragment(t *testing.T) {
1401 // Test that path templates with fragments are normalized when request has no fragment
1402 // This covers normalizePathForMatching stripping fragment from template (line 115-117)
1403 spec := `openapi: 3.1.0
1404 info:
1405 title: Fragment Normalization Test
1406 version: 1.0.0
1407 paths:
1408 /hashy#section:
1409 post:
1410 operationId: postHashy
1411 responses:
1412 '200':
1413 description: OK
1414 `
1415 doc, _ := libopenapi.NewDocument([]byte(spec))
1416 m, _ := doc.BuildV3Model()
1417
1418 // Request WITHOUT fragment should still match path template WITH fragment
1419 // because normalizePathForMatching strips the fragment from template
1420 request, _ := http.NewRequest(http.MethodPost, "https://api.com/hashy", nil)
1421 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1422
1423 assert.Nil(t, errs)
1424 assert.NotNil(t, pathItem)
1425 assert.Equal(t, "postHashy", pathItem.Post.OperationId)
1426 assert.Equal(t, "/hashy#section", foundPath)
1427 }
1428
1429 func TestFindPath_NilDocument(t *testing.T) {
1430 // Passing a nil document is a programming error and will panic.
1431 // This test verifies that behavior (callers should not pass nil).
1432 request, _ := http.NewRequest(http.MethodGet, "https://api.com/test", nil)
1433
1434 assert.Panics(t, func() {
1435 FindPath(request, nil, nil)
1436 }, "FindPath should panic when document is nil")
1437 }
1438
1439 func TestFindPath_NilPaths(t *testing.T) {
1440 // A spec without paths will have nil Paths - this is a programming error
1441 spec := `openapi: 3.1.0
1442 info:
1443 title: No Paths Test
1444 version: 1.0.0
1445 `
1446 doc, _ := libopenapi.NewDocument([]byte(spec))
1447 m, _ := doc.BuildV3Model()
1448
1449 request, _ := http.NewRequest(http.MethodGet, "https://api.com/test", nil)
1450
1451 // This panics because the original code doesn't handle nil Paths either
1452 assert.Panics(t, func() {
1453 FindPath(request, &m.Model, nil)
1454 }, "FindPath should panic when document has no paths")
1455 }
1456
1457 func TestFindPath_RequestWithFragment(t *testing.T) {
1458 // Test when request URL contains a fragment - normalizePathForMatching should NOT strip template fragment
1459 spec := `openapi: 3.1.0
1460 info:
1461 title: Fragment Test
1462 version: 1.0.0
1463 paths:
1464 /docs#section:
1465 get:
1466 operationId: getDocs
1467 responses:
1468 '200':
1469 description: OK
1470 `
1471 doc, _ := libopenapi.NewDocument([]byte(spec))
1472 m, _ := doc.BuildV3Model()
1473
1474 // Request WITH fragment should match path WITH same fragment
1475 request, _ := http.NewRequest(http.MethodGet, "https://api.com/docs#section", nil)
1476 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1477
1478 assert.Nil(t, errs)
1479 assert.NotNil(t, pathItem)
1480 assert.Equal(t, "getDocs", pathItem.Get.OperationId)
1481 assert.Equal(t, "/docs#section", foundPath)
1482 }
1483
1484 func TestFindPath_RadixTree_MethodMismatch(t *testing.T) {
1485 // Test that radix tree path match with wrong method returns proper error
1486 // This covers lines 72-83 in FindPath (missingOperation from radix tree)
1487 spec := `openapi: 3.1.0
1488 info:
1489 title: Method Mismatch Test
1490 version: 1.0.0
1491 paths:
1492 /users/{id}:
1493 get:
1494 operationId: getUser
1495 responses:
1496 '200':
1497 description: OK
1498 `
1499 doc, _ := libopenapi.NewDocument([]byte(spec))
1500 m, _ := doc.BuildV3Model()
1501
1502 // POST to a simple path that only has GET - radix tree handles this
1503 request, _ := http.NewRequest(http.MethodPost, "https://api.com/users/123", nil)
1504 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1505
1506 assert.NotNil(t, pathItem)
1507 assert.NotNil(t, errs)
1508 assert.Len(t, errs, 1)
1509 assert.Equal(t, "missingOperation", errs[0].ValidationSubType)
1510 assert.Equal(t, "/users/{id}", foundPath)
1511 }
1512
1513 func TestFindPath_RequestWithFragment_MatchesPathWithFragment(t *testing.T) {
1514 // Test normalizePathForMatching when REQUEST has fragment
1515 // This covers lines 167-168: if strings.Contains(requestPath, "#") { return path }
1516 // Using OData-style path to force regex fallback (radix tree can't handle embedded params)
1517 spec := `openapi: 3.1.0
1518 info:
1519 title: Fragment Test
1520 version: 1.0.0
1521 paths:
1522 /entities('{id}')#section1:
1523 get:
1524 operationId: getSection1
1525 /entities('{id}')#section2:
1526 get:
1527 operationId: getSection2
1528 `
1529 doc, _ := libopenapi.NewDocument([]byte(spec))
1530 m, _ := doc.BuildV3Model()
1531
1532 // Request with fragment should match exact path with fragment
1533 // The OData path forces regex fallback, which calls normalizePathForMatching
1534 request, _ := http.NewRequest(http.MethodGet, "https://api.com/entities('123')#section1", nil)
1535 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1536
1537 assert.Nil(t, errs)
1538 assert.NotNil(t, pathItem)
1539 assert.Equal(t, "getSection1", pathItem.Get.OperationId)
1540 assert.Equal(t, "/entities('{id}')#section1", foundPath)
1541
1542 // Different fragment should match different path
1543 request, _ = http.NewRequest(http.MethodGet, "https://api.com/entities('456')#section2", nil)
1544 pathItem, errs, foundPath = FindPath(request, &m.Model, nil)
1545
1546 assert.Nil(t, errs)
1547 assert.NotNil(t, pathItem)
1548 assert.Equal(t, "getSection2", pathItem.Get.OperationId)
1549 assert.Equal(t, "/entities('{id}')#section2", foundPath)
1550 }
1551
1552 func TestCheckPathAgainstBase_MergedPath(t *testing.T) {
1553 // Test checkPathAgainstBase when docPath == merged (basePath + urlPath)
1554 // This covers line 225-227
1555
1556 // Direct equality
1557 result := checkPathAgainstBase("/users", "/users", nil)
1558 assert.True(t, result)
1559
1560 // With base path merge
1561 basePaths := []string{"/api/v1"}
1562 result = checkPathAgainstBase("/api/v1/users", "/users", basePaths)
1563 assert.True(t, result)
1564
1565 // With trailing slash on base path
1566 basePaths = []string{"/api/v1/"}
1567 result = checkPathAgainstBase("/api/v1/users", "/users", basePaths)
1568 assert.True(t, result)
1569
1570 // No match
1571 result = checkPathAgainstBase("/other/path", "/users", basePaths)
1572 assert.False(t, result)
1573
1574 // Issue #27: basePath is just "/" — should not produce empty string
1575 basePaths = []string{"/"}
1576 result = checkPathAgainstBase("/users", "/users", basePaths)
1577 assert.True(t, result)
1578 }
1579
1580 func TestFindPath_RegexFallback_MethodMismatch(t *testing.T) {
1581 // Test missingOperation error from regex fallback path (lines 150-161)
1582 // Using OData-style path to force regex fallback, with wrong method
1583 spec := `openapi: 3.1.0
1584 info:
1585 title: Method Mismatch Test
1586 version: 1.0.0
1587 paths:
1588 /entities('{id}'):
1589 get:
1590 operationId: getEntity
1591 responses:
1592 '200':
1593 description: OK
1594 `
1595 doc, _ := libopenapi.NewDocument([]byte(spec))
1596 m, _ := doc.BuildV3Model()
1597
1598 // POST to OData path that only has GET - regex fallback handles this
1599 request, _ := http.NewRequest(http.MethodPost, "https://api.com/entities('123')", nil)
1600 pathItem, errs, foundPath := FindPath(request, &m.Model, nil)
1601
1602 assert.NotNil(t, pathItem)
1603 assert.NotNil(t, errs)
1604 assert.Len(t, errs, 1)
1605 assert.Equal(t, "missingOperation", errs[0].ValidationSubType)
1606 assert.Equal(t, "/entities('{id}')", foundPath)
1607 }
1608
1609 func TestFindPath_WithPathTree_MethodMatch(t *testing.T) {
1610 // Exercise radix tree fast-path: options.PathTree != nil, method matches → return pathItem, nil, matchedPath
1611 spec := `openapi: 3.1.0
1612 info:
1613 title: Radix Tree Test
1614 version: 1.0.0
1615 paths:
1616 /users/{id}:
1617 get:
1618 operationId: getUser
1619 responses:
1620 '200':
1621 description: OK
1622 `
1623 doc, _ := libopenapi.NewDocument([]byte(spec))
1624 m, _ := doc.BuildV3Model()
1625
1626 pathTree := radix.BuildPathTree(&m.Model)
1627 opts := config.NewValidationOptions(config.WithPathTree(pathTree))
1628
1629 request, _ := http.NewRequest(http.MethodGet, "https://api.com/users/123", nil)
1630 pathItem, errs, foundPath := FindPath(request, &m.Model, opts)
1631
1632 assert.Nil(t, errs)
1633 assert.NotNil(t, pathItem)
1634 assert.Equal(t, "getUser", pathItem.Get.OperationId)
1635 assert.Equal(t, "/users/{id}", foundPath)
1636 }
1637
1638 func TestFindPath_WithPathTree_MethodMismatch(t *testing.T) {
1639 // Exercise radix tree fast-path: options.PathTree != nil, path found but wrong method
1640 // → return pathItem, missingOperationError(...), matchedPath
1641 spec := `openapi: 3.1.0
1642 info:
1643 title: Radix Tree Test
1644 version: 1.0.0
1645 paths:
1646 /users/{id}:
1647 get:
1648 operationId: getUser
1649 responses:
1650 '200':
1651 description: OK
1652 `
1653 doc, _ := libopenapi.NewDocument([]byte(spec))
1654 m, _ := doc.BuildV3Model()
1655
1656 pathTree := radix.BuildPathTree(&m.Model)
1657 opts := config.NewValidationOptions(config.WithPathTree(pathTree))
1658
1659 request, _ := http.NewRequest(http.MethodPost, "https://api.com/users/123", nil)
1660 pathItem, errs, foundPath := FindPath(request, &m.Model, opts)
1661
1662 assert.NotNil(t, pathItem)
1663 assert.NotNil(t, errs)
1664 assert.Len(t, errs, 1)
1665 assert.True(t, errs[0].IsOperationMissingError())
1666 assert.Equal(t, "/users/{id}", foundPath)
1667 }