Debian Codegraph @

radix/tree_test.go

raw
1 // Copyright 2025 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package radix
5
6 import (
7 "fmt"
8 "sort"
9 "testing"
10
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 )
14
15 func TestNew(t *testing.T) {
16 tree := New[string]()
17 require.NotNil(t, tree)
18 assert.NotNil(t, tree.root)
19 assert.Equal(t, 0, tree.Size())
20 }
21
22 func TestTree_Insert_LiteralPaths(t *testing.T) {
23 tree := New[string]()
24
25 // Insert literal paths
26 assert.True(t, tree.Insert("/users", "users handler"))
27 assert.True(t, tree.Insert("/users/admin", "admin handler"))
28 assert.True(t, tree.Insert("/posts", "posts handler"))
29 assert.True(t, tree.Insert("/posts/trending", "trending handler"))
30
31 assert.Equal(t, 4, tree.Size())
32
33 // Verify lookups
34 val, path, found := tree.Lookup("/users")
35 assert.True(t, found)
36 assert.Equal(t, "users handler", val)
37 assert.Equal(t, "/users", path)
38
39 val, path, found = tree.Lookup("/users/admin")
40 assert.True(t, found)
41 assert.Equal(t, "admin handler", val)
42 assert.Equal(t, "/users/admin", path)
43 }
44
45 func TestTree_Insert_ParameterizedPaths(t *testing.T) {
46 tree := New[string]()
47
48 tree.Insert("/users/{id}", "user by id")
49 tree.Insert("/users/{id}/posts", "user posts")
50 tree.Insert("/users/{id}/posts/{postId}", "single post")
51
52 assert.Equal(t, 3, tree.Size())
53
54 // Verify parameter matching
55 val, path, found := tree.Lookup("/users/123")
56 assert.True(t, found)
57 assert.Equal(t, "user by id", val)
58 assert.Equal(t, "/users/{id}", path)
59
60 val, path, found = tree.Lookup("/users/abc")
61 assert.True(t, found)
62 assert.Equal(t, "user by id", val)
63 assert.Equal(t, "/users/{id}", path)
64
65 val, path, found = tree.Lookup("/users/123/posts")
66 assert.True(t, found)
67 assert.Equal(t, "user posts", val)
68 assert.Equal(t, "/users/{id}/posts", path)
69
70 val, path, found = tree.Lookup("/users/123/posts/456")
71 assert.True(t, found)
72 assert.Equal(t, "single post", val)
73 assert.Equal(t, "/users/{id}/posts/{postId}", path)
74 }
75
76 func TestTree_Specificity_LiteralOverParam(t *testing.T) {
77 tree := New[string]()
78
79 // Insert both literal and parameterized for same depth
80 tree.Insert("/users/{id}", "user by id")
81 tree.Insert("/users/admin", "admin user")
82 tree.Insert("/users/me", "current user")
83
84 // Literal matches should take precedence
85 val, path, found := tree.Lookup("/users/admin")
86 assert.True(t, found)
87 assert.Equal(t, "admin user", val)
88 assert.Equal(t, "/users/admin", path)
89
90 val, path, found = tree.Lookup("/users/me")
91 assert.True(t, found)
92 assert.Equal(t, "current user", val)
93 assert.Equal(t, "/users/me", path)
94
95 // Non-literal should fall back to param
96 val, path, found = tree.Lookup("/users/123")
97 assert.True(t, found)
98 assert.Equal(t, "user by id", val)
99 assert.Equal(t, "/users/{id}", path)
100 }
101
102 func TestTree_Specificity_DeepPaths(t *testing.T) {
103 tree := New[string]()
104
105 // Deeper literal path should match over param
106 tree.Insert("/api/{version}/users", "versioned users")
107 tree.Insert("/api/v1/users", "v1 users")
108 tree.Insert("/api/v2/users", "v2 users")
109 tree.Insert("/api/v1/users/{id}", "v1 user by id")
110
111 val, path, found := tree.Lookup("/api/v1/users")
112 assert.True(t, found)
113 assert.Equal(t, "v1 users", val)
114 assert.Equal(t, "/api/v1/users", path)
115
116 val, path, found = tree.Lookup("/api/v2/users")
117 assert.True(t, found)
118 assert.Equal(t, "v2 users", val)
119 assert.Equal(t, "/api/v2/users", path)
120
121 val, path, found = tree.Lookup("/api/v3/users")
122 assert.True(t, found)
123 assert.Equal(t, "versioned users", val)
124 assert.Equal(t, "/api/{version}/users", path)
125
126 val, path, found = tree.Lookup("/api/v1/users/123")
127 assert.True(t, found)
128 assert.Equal(t, "v1 user by id", val)
129 assert.Equal(t, "/api/v1/users/{id}", path)
130 }
131
132 func TestTree_Lookup_NoMatch(t *testing.T) {
133 tree := New[string]()
134
135 tree.Insert("/users", "users")
136 tree.Insert("/users/{id}", "user by id")
137
138 // Path doesn't exist
139 _, _, found := tree.Lookup("/posts")
140 assert.False(t, found)
141
142 // Path too deep
143 _, _, found = tree.Lookup("/users/123/posts/456/comments")
144 assert.False(t, found)
145
146 // Empty tree lookup
147 emptyTree := New[string]()
148 _, _, found = emptyTree.Lookup("/anything")
149 assert.False(t, found)
150 }
151
152 func TestTree_Lookup_EdgeCases(t *testing.T) {
153 tree := New[string]()
154
155 tree.Insert("/", "root")
156 tree.Insert("/users", "users")
157
158 // Root path
159 val, path, found := tree.Lookup("/")
160 assert.True(t, found)
161 assert.Equal(t, "root", val)
162 assert.Equal(t, "/", path)
163
164 // Empty path treated as root
165 val, path, found = tree.Lookup("")
166 assert.True(t, found)
167 assert.Equal(t, "root", val)
168 assert.Equal(t, "/", path)
169
170 // Trailing slash normalization
171 val, path, found = tree.Lookup("/users/")
172 assert.True(t, found)
173 assert.Equal(t, "users", val)
174 assert.Equal(t, "/users", path)
175
176 // Double slashes
177 val, path, found = tree.Lookup("//users//")
178 assert.True(t, found)
179 assert.Equal(t, "users", val)
180 assert.Equal(t, "/users", path)
181 }
182
183 func TestTree_Insert_Update(t *testing.T) {
184 tree := New[string]()
185
186 // First insert
187 isNew := tree.Insert("/users", "v1")
188 assert.True(t, isNew)
189 assert.Equal(t, 1, tree.Size())
190
191 // Update existing path
192 isNew = tree.Insert("/users", "v2")
193 assert.False(t, isNew)
194 assert.Equal(t, 1, tree.Size())
195
196 // Verify updated value
197 val, _, _ := tree.Lookup("/users")
198 assert.Equal(t, "v2", val)
199 }
200
201 func TestTree_MultipleParameters(t *testing.T) {
202 tree := New[string]()
203
204 tree.Insert("/orgs/{orgId}/teams/{teamId}/members/{memberId}", "org team member")
205 tree.Insert("/accounts/{accountId}/ads/{adId}/metrics/{metricId}/breakdown/{breakdownId}", "deep nested")
206
207 val, path, found := tree.Lookup("/orgs/org1/teams/team2/members/member3")
208 assert.True(t, found)
209 assert.Equal(t, "org team member", val)
210 assert.Equal(t, "/orgs/{orgId}/teams/{teamId}/members/{memberId}", path)
211
212 val, path, found = tree.Lookup("/accounts/acc1/ads/ad2/metrics/met3/breakdown/bd4")
213 assert.True(t, found)
214 assert.Equal(t, "deep nested", val)
215 assert.Equal(t, "/accounts/{accountId}/ads/{adId}/metrics/{metricId}/breakdown/{breakdownId}", path)
216 }
217
218 func TestTree_Clear(t *testing.T) {
219 tree := New[string]()
220
221 tree.Insert("/users", "users")
222 tree.Insert("/posts", "posts")
223 assert.Equal(t, 2, tree.Size())
224
225 tree.Clear()
226 assert.Equal(t, 0, tree.Size())
227
228 _, _, found := tree.Lookup("/users")
229 assert.False(t, found)
230 }
231
232 func TestTree_Walk(t *testing.T) {
233 tree := New[string]()
234
235 tree.Insert("/users", "users")
236 tree.Insert("/users/{id}", "user by id")
237 tree.Insert("/posts", "posts")
238
239 var paths []string
240 tree.Walk(func(path string, value string) bool {
241 paths = append(paths, path)
242 return true
243 })
244
245 assert.Len(t, paths, 3)
246 sort.Strings(paths)
247 assert.Contains(t, paths, "/posts")
248 assert.Contains(t, paths, "/users")
249 assert.Contains(t, paths, "/users/{id}")
250 }
251
252 func TestTree_Walk_EarlyStop(t *testing.T) {
253 tree := New[string]()
254
255 for i := 0; i < 10; i++ {
256 tree.Insert(fmt.Sprintf("/path%d", i), fmt.Sprintf("handler%d", i))
257 }
258
259 count := 0
260 tree.Walk(func(path string, value string) bool {
261 count++
262 return count < 3 // Stop after 3
263 })
264
265 assert.Equal(t, 3, count)
266 }
267
268 func TestTree_Size(t *testing.T) {
269 tree := New[string]()
270
271 assert.Equal(t, 0, tree.Size())
272
273 tree.Insert("/a", "a")
274 assert.Equal(t, 1, tree.Size())
275
276 tree.Insert("/b", "b")
277 assert.Equal(t, 2, tree.Size())
278
279 // Update shouldn't increase size
280 tree.Insert("/a", "a2")
281 assert.Equal(t, 2, tree.Size())
282
283 tree.Clear()
284 assert.Equal(t, 0, tree.Size())
285 }
286
287 // OpenAPI-specific test cases
288
289 func TestTree_OpenAPIStylePaths(t *testing.T) {
290 tree := New[string]()
291
292 // Common OpenAPI-style paths
293 paths := []string{
294 "/api/v3/ad_accounts",
295 "/api/v3/ad_accounts/{ad_account_id}",
296 "/api/v3/ad_accounts/{ad_account_id}/ads",
297 "/api/v3/ad_accounts/{ad_account_id}/ads/{ad_id}",
298 "/api/v3/ad_accounts/{ad_account_id}/campaigns",
299 "/api/v3/ad_accounts/{ad_account_id}/campaigns/{campaign_id}",
300 "/api/v3/ad_accounts/{ad_account_id}/bulk_actions",
301 "/api/v3/ad_accounts/{ad_account_id}/bulk_actions/{bulk_action_id}",
302 }
303
304 for _, p := range paths {
305 tree.Insert(p, "handler:"+p)
306 }
307
308 assert.Equal(t, len(paths), tree.Size())
309
310 // Test various lookups
311 tests := []struct {
312 input string
313 expected string
314 }{
315 {"/api/v3/ad_accounts", "/api/v3/ad_accounts"},
316 {"/api/v3/ad_accounts/123", "/api/v3/ad_accounts/{ad_account_id}"},
317 {"/api/v3/ad_accounts/abc-def-ghi", "/api/v3/ad_accounts/{ad_account_id}"},
318 {"/api/v3/ad_accounts/123/ads", "/api/v3/ad_accounts/{ad_account_id}/ads"},
319 {"/api/v3/ad_accounts/123/ads/456", "/api/v3/ad_accounts/{ad_account_id}/ads/{ad_id}"},
320 {"/api/v3/ad_accounts/acc1/campaigns/camp1", "/api/v3/ad_accounts/{ad_account_id}/campaigns/{campaign_id}"},
321 {"/api/v3/ad_accounts/acc1/bulk_actions", "/api/v3/ad_accounts/{ad_account_id}/bulk_actions"},
322 {"/api/v3/ad_accounts/acc1/bulk_actions/ba1", "/api/v3/ad_accounts/{ad_account_id}/bulk_actions/{bulk_action_id}"},
323 }
324
325 for _, tc := range tests {
326 t.Run(tc.input, func(t *testing.T) {
327 val, path, found := tree.Lookup(tc.input)
328 require.True(t, found, "path should be found: %s", tc.input)
329 assert.Equal(t, tc.expected, path)
330 assert.Equal(t, "handler:"+tc.expected, val)
331 })
332 }
333 }
334
335 func TestTree_ConsistentWithVaryingIDs(t *testing.T) {
336 // This test verifies that the radix tree performs consistently
337 // regardless of the specific parameter values used
338 tree := New[string]()
339
340 tree.Insert("/api/v3/ad_accounts/{ad_account_id}/bulk_actions", "bulk_actions")
341
342 // All of these should match the same path template
343 testCases := []string{
344 "/api/v3/ad_accounts/1/bulk_actions",
345 "/api/v3/ad_accounts/999999/bulk_actions",
346 "/api/v3/ad_accounts/uuid-here/bulk_actions",
347 "/api/v3/ad_accounts/acc_123abc/bulk_actions",
348 }
349
350 for _, tc := range testCases {
351 val, path, found := tree.Lookup(tc)
352 require.True(t, found, "should find path for %s", tc)
353 assert.Equal(t, "/api/v3/ad_accounts/{ad_account_id}/bulk_actions", path)
354 assert.Equal(t, "bulk_actions", val)
355 }
356 }
357
358 func TestTree_NilRoot(t *testing.T) {
359 // Test that a tree with nil root handles gracefully
360 tree := &Tree[string]{root: nil}
361
362 _, _, found := tree.Lookup("/anything")
363 assert.False(t, found)
364
365 // Insert should work even with nil root
366 tree.Insert("/users", "users")
367 val, _, found := tree.Lookup("/users")
368 assert.True(t, found)
369 assert.Equal(t, "users", val)
370 }
371
372 func TestTree_ComplexParamNames(t *testing.T) {
373 tree := New[string]()
374
375 // Various parameter naming styles
376 tree.Insert("/users/{user_id}", "underscore")
377 tree.Insert("/posts/{postId}", "camelCase")
378 tree.Insert("/items/{item-id}", "kebab-case")
379 tree.Insert("/things/{THING_ID}", "screaming")
380
381 tests := []struct {
382 input string
383 expected string
384 }{
385 {"/users/123", "/users/{user_id}"},
386 {"/posts/abc", "/posts/{postId}"},
387 {"/items/xyz", "/items/{item-id}"},
388 {"/things/T1", "/things/{THING_ID}"},
389 }
390
391 for _, tc := range tests {
392 _, path, found := tree.Lookup(tc.input)
393 assert.True(t, found)
394 assert.Equal(t, tc.expected, path)
395 }
396 }
397
398 // Additional edge case tests for full coverage
399
400 func TestTree_Walk_NilRoot(t *testing.T) {
401 // Verify Walk handles nil root gracefully
402 tree := &Tree[string]{root: nil}
403
404 count := 0
405 tree.Walk(func(path string, value string) bool {
406 count++
407 return true
408 })
409
410 assert.Equal(t, 0, count, "Walk on nil root should not call callback")
411 }
412
413 func TestTree_Walk_EarlyStopOnParamChild(t *testing.T) {
414 // Test that Walk respects early stop when iterating paramChild
415 tree := New[string]()
416
417 // Create a structure where we have literal children AND a param child
418 tree.Insert("/users/admin", "admin")
419 tree.Insert("/users/{id}", "user by id")
420 tree.Insert("/users/{id}/posts", "posts")
421
422 // Stop immediately
423 count := 0
424 tree.Walk(func(path string, value string) bool {
425 count++
426 return false // Stop after first
427 })
428
429 assert.Equal(t, 1, count, "Walk should stop after first callback returns false")
430 }
431
432 func TestTree_Walk_StopInParamChildBranch(t *testing.T) {
433 // Specifically test stopping while in the paramChild branch
434 tree := New[string]()
435
436 tree.Insert("/a", "a")
437 tree.Insert("/b/{id}", "b-id")
438 tree.Insert("/b/{id}/c", "b-id-c")
439
440 paths := []string{}
441 tree.Walk(func(path string, value string) bool {
442 paths = append(paths, path)
443 // Stop when we hit the param child's nested path
444 return path != "/b/{id}/c"
445 })
446
447 // Should have stopped at or after /b/{id}/c
448 assert.LessOrEqual(t, len(paths), 3)
449 }
450
451 func TestExtractParamName_NonParam(t *testing.T) {
452 // Test extractParamName with non-parameter segments (fallback case)
453 // This tests the "return seg" branch
454
455 // These are NOT valid params, should return as-is
456 testCases := []struct {
457 input string
458 expected string
459 }{
460 {"users", "users"}, // normal segment
461 {"{}", "{}"}, // empty param - not valid (len <= 2)
462 {"{a", "{a"}, // missing closing brace
463 {"a}", "a}"}, // missing opening brace
464 {"{", "{"}, // single char
465 {"}", "}"}, // single char
466 {"", ""}, // empty string
467 {"ab", "ab"}, // two chars, not a param
468 {"{x}", "x"}, // Valid param - extracts "x"
469 {"{ab}", "ab"}, // Valid param - extracts "ab"
470 }
471
472 for _, tc := range testCases {
473 result := extractParamName(tc.input)
474 assert.Equal(t, tc.expected, result, "extractParamName(%q)", tc.input)
475 }
476 }
477
478 func TestIsParam(t *testing.T) {
479 testCases := []struct {
480 input string
481 expected bool
482 }{
483 {"{id}", true},
484 {"{userId}", true},
485 {"{a}", true},
486 {"{}", false}, // empty param name
487 {"{a", false}, // missing close
488 {"a}", false}, // missing open
489 {"id", false}, // no braces
490 {"{", false}, // single char
491 {"}", false}, // single char
492 {"", false}, // empty
493 {"ab", false}, // two chars
494 {"{ab", false}, // three chars, missing close
495 {"ab}", false}, // three chars, missing open
496 }
497
498 for _, tc := range testCases {
499 result := isParam(tc.input)
500 assert.Equal(t, tc.expected, result, "isParam(%q)", tc.input)
501 }
502 }
503
504 func TestSplitPath(t *testing.T) {
505 testCases := []struct {
506 input string
507 expected []string
508 }{
509 {"/users/{id}/posts", []string{"users", "{id}", "posts"}},
510 {"/users", []string{"users"}},
511 {"/", nil},
512 {"", nil},
513 {"users", []string{"users"}},
514 {"/a/b/c", []string{"a", "b", "c"}},
515 {"//a//b//", []string{"a", "b"}}, // double slashes filtered
516 {"/a/", []string{"a"}},
517 {"///", nil}, // all slashes
518 }
519
520 for _, tc := range testCases {
521 result := splitPath(tc.input)
522 assert.Equal(t, tc.expected, result, "splitPath(%q)", tc.input)
523 }
524 }
525
526 func TestTree_SpecialCharacters(t *testing.T) {
527 tree := New[string]()
528
529 // Paths with special characters (URL-safe ones)
530 tree.Insert("/api/v1/users", "users")
531 tree.Insert("/api/v1/users/{id}", "user")
532 tree.Insert("/api/v1/items-list", "items-list")
533 tree.Insert("/api/v1/snake_case", "snake")
534 tree.Insert("/api/v1/CamelCase", "camel")
535
536 tests := []struct {
537 lookup string
538 expected string
539 found bool
540 }{
541 {"/api/v1/users", "/api/v1/users", true},
542 {"/api/v1/users/user-123", "/api/v1/users/{id}", true},
543 {"/api/v1/users/user_456", "/api/v1/users/{id}", true},
544 {"/api/v1/items-list", "/api/v1/items-list", true},
545 {"/api/v1/snake_case", "/api/v1/snake_case", true},
546 {"/api/v1/CamelCase", "/api/v1/CamelCase", true},
547 }
548
549 for _, tc := range tests {
550 _, path, found := tree.Lookup(tc.lookup)
551 assert.Equal(t, tc.found, found, "lookup %q", tc.lookup)
552 if tc.found {
553 assert.Equal(t, tc.expected, path, "lookup %q", tc.lookup)
554 }
555 }
556 }
557
558 func TestTree_SingleCharSegments(t *testing.T) {
559 tree := New[string]()
560
561 tree.Insert("/a", "a")
562 tree.Insert("/a/b", "ab")
563 tree.Insert("/a/{x}", "ax")
564 tree.Insert("/a/b/c", "abc")
565
566 _, path, found := tree.Lookup("/a")
567 assert.True(t, found)
568 assert.Equal(t, "/a", path)
569
570 _, path, found = tree.Lookup("/a/b")
571 assert.True(t, found)
572 assert.Equal(t, "/a/b", path)
573
574 _, path, found = tree.Lookup("/a/z")
575 assert.True(t, found)
576 assert.Equal(t, "/a/{x}", path)
577 }
578
579 func TestTree_URLEncodedSegments(t *testing.T) {
580 // URL-encoded values should be matched as literals
581 tree := New[string]()
582
583 tree.Insert("/users/{id}", "user")
584
585 // These are all different IDs that should match the param
586 testIDs := []string{
587 "123",
588 "abc",
589 "user%40example.com", // @ encoded
590 "hello%20world", // space encoded
591 "100%25", // % encoded
592 }
593
594 for _, id := range testIDs {
595 _, path, found := tree.Lookup("/users/" + id)
596 assert.True(t, found, "should find path for /users/%s", id)
597 assert.Equal(t, "/users/{id}", path)
598 }
599 }
600
601 func TestTree_NumericSegments(t *testing.T) {
602 tree := New[string]()
603
604 tree.Insert("/v1/resource", "v1")
605 tree.Insert("/v2/resource", "v2")
606 tree.Insert("/{version}/resource", "versioned")
607
608 _, path, found := tree.Lookup("/v1/resource")
609 assert.True(t, found)
610 assert.Equal(t, "/v1/resource", path)
611
612 _, path, found = tree.Lookup("/v2/resource")
613 assert.True(t, found)
614 assert.Equal(t, "/v2/resource", path)
615
616 _, path, found = tree.Lookup("/v999/resource")
617 assert.True(t, found)
618 assert.Equal(t, "/{version}/resource", path)
619 }
620
621 func TestTree_DeepNesting(t *testing.T) {
622 tree := New[string]()
623
624 // Very deep path
625 deepPath := "/a/{b}/c/{d}/e/{f}/g/{h}/i/{j}/k"
626 tree.Insert(deepPath, "deep")
627
628 _, path, found := tree.Lookup("/a/1/c/2/e/3/g/4/i/5/k")
629 assert.True(t, found)
630 assert.Equal(t, deepPath, path)
631 }
632
633 func TestTree_LookupPartialMatch(t *testing.T) {
634 tree := New[string]()
635
636 tree.Insert("/users/{id}/posts/{postId}", "post")
637
638 // Partial path should not match
639 _, _, found := tree.Lookup("/users/123/posts")
640 assert.False(t, found, "partial path should not match")
641
642 _, _, found = tree.Lookup("/users/123")
643 assert.False(t, found, "partial path should not match")
644 }
645
646 func TestTree_OverlappingPaths(t *testing.T) {
647 tree := New[string]()
648
649 // Insert paths that could conflict
650 tree.Insert("/api/users", "users list")
651 tree.Insert("/api/users/search", "users search")
652 tree.Insert("/api/users/{id}", "user by id")
653 tree.Insert("/api/users/{id}/profile", "user profile")
654 tree.Insert("/api/users/{userId}/posts/{postId}", "user post")
655
656 tests := []struct {
657 lookup string
658 expected string
659 }{
660 {"/api/users", "/api/users"},
661 {"/api/users/search", "/api/users/search"},
662 {"/api/users/123", "/api/users/{id}"},
663 {"/api/users/123/profile", "/api/users/{id}/profile"},
664 {"/api/users/u1/posts/p1", "/api/users/{userId}/posts/{postId}"},
665 }
666
667 for _, tc := range tests {
668 _, path, found := tree.Lookup(tc.lookup)
669 require.True(t, found, "should find %s", tc.lookup)
670 assert.Equal(t, tc.expected, path, "lookup %s", tc.lookup)
671 }
672 }
673
674 func TestTree_ConcurrentAccess(t *testing.T) {
675 // Test concurrent reads (tree is read-only after construction)
676 tree := New[string]()
677
678 paths := []string{
679 "/api/v1/users",
680 "/api/v1/users/{id}",
681 "/api/v1/posts",
682 "/api/v1/posts/{id}",
683 }
684
685 for _, p := range paths {
686 tree.Insert(p, "handler:"+p)
687 }
688
689 // Concurrent lookups
690 done := make(chan bool)
691 for i := 0; i < 100; i++ {
692 go func(n int) {
693 for j := 0; j < 100; j++ {
694 path := paths[n%len(paths)]
695 testPath := path
696 if n%2 == 0 {
697 // Replace params with values
698 testPath = "/api/v1/users/123"
699 }
700 _, _, _ = tree.Lookup(testPath)
701 }
702 done <- true
703 }(i)
704 }
705
706 // Wait for all goroutines
707 for i := 0; i < 100; i++ {
708 <-done
709 }
710 }
711
712 func TestTree_EmptyValue(t *testing.T) {
713 // Test that empty values are stored correctly
714 tree := New[string]()
715
716 tree.Insert("/empty", "")
717
718 val, path, found := tree.Lookup("/empty")
719 assert.True(t, found)
720 assert.Equal(t, "/empty", path)
721 assert.Equal(t, "", val) // Empty string is a valid value
722 }
723
724 func TestTree_PointerValues(t *testing.T) {
725 // Test with pointer values to ensure nil handling
726 type Handler struct {
727 Name string
728 }
729
730 tree := New[*Handler]()
731
732 h1 := &Handler{Name: "h1"}
733 tree.Insert("/a", h1)
734 tree.Insert("/b", nil) // nil pointer value
735
736 val, _, found := tree.Lookup("/a")
737 assert.True(t, found)
738 assert.Equal(t, "h1", val.Name)
739
740 val, _, found = tree.Lookup("/b")
741 assert.True(t, found)
742 assert.Nil(t, val) // nil is a valid value
743
744 _, _, found = tree.Lookup("/c")
745 assert.False(t, found)
746 }
747
748 // Benchmark tests
749
750 func BenchmarkTree_Insert(b *testing.B) {
751 paths := []string{
752 "/api/v3/ad_accounts",
753 "/api/v3/ad_accounts/{ad_account_id}",
754 "/api/v3/ad_accounts/{ad_account_id}/ads",
755 "/api/v3/ad_accounts/{ad_account_id}/ads/{ad_id}",
756 "/api/v3/ad_accounts/{ad_account_id}/campaigns",
757 "/api/v3/ad_accounts/{ad_account_id}/campaigns/{campaign_id}",
758 }
759
760 b.ResetTimer()
761 for i := 0; i < b.N; i++ {
762 tree := New[string]()
763 for _, p := range paths {
764 tree.Insert(p, p)
765 }
766 }
767 }
768
769 func BenchmarkTree_Lookup_Literal(b *testing.B) {
770 tree := New[string]()
771 tree.Insert("/api/v3/ad_accounts", "accounts")
772
773 b.ResetTimer()
774 for i := 0; i < b.N; i++ {
775 tree.Lookup("/api/v3/ad_accounts")
776 }
777 }
778
779 func BenchmarkTree_Lookup_SingleParam(b *testing.B) {
780 tree := New[string]()
781 tree.Insert("/api/v3/ad_accounts/{ad_account_id}", "account")
782
783 b.ResetTimer()
784 for i := 0; i < b.N; i++ {
785 tree.Lookup("/api/v3/ad_accounts/123456")
786 }
787 }
788
789 func BenchmarkTree_Lookup_MultipleParams(b *testing.B) {
790 tree := New[string]()
791 tree.Insert("/api/v3/ad_accounts/{ad_account_id}/campaigns/{campaign_id}/ads/{ad_id}", "ad")
792
793 b.ResetTimer()
794 for i := 0; i < b.N; i++ {
795 tree.Lookup("/api/v3/ad_accounts/acc1/campaigns/camp1/ads/ad1")
796 }
797 }
798
799 func BenchmarkTree_Lookup_ManyPaths(b *testing.B) {
800 tree := New[string]()
801
802 // Simulate a realistic API with many paths
803 for i := 0; i < 100; i++ {
804 tree.Insert(fmt.Sprintf("/api/v3/resource%d", i), fmt.Sprintf("handler%d", i))
805 tree.Insert(fmt.Sprintf("/api/v3/resource%d/{id}", i), fmt.Sprintf("handler%d-id", i))
806 }
807
808 b.ResetTimer()
809 for i := 0; i < b.N; i++ {
810 tree.Lookup("/api/v3/resource50/abc123")
811 }
812 }
813
814 func BenchmarkTree_Lookup_VaryingIDs(b *testing.B) {
815 tree := New[string]()
816 tree.Insert("/api/v3/ad_accounts/{ad_account_id}/bulk_actions", "bulk")
817
818 // Pre-generate test paths
819 testPaths := make([]string, 1000)
820 for i := 0; i < 1000; i++ {
821 testPaths[i] = fmt.Sprintf("/api/v3/ad_accounts/account_%d/bulk_actions", i)
822 }
823
824 b.ResetTimer()
825 for i := 0; i < b.N; i++ {
826 tree.Lookup(testPaths[i%1000])
827 }
828 }