github.com/golazy/golazy@v0.0.7-0.20221012133820-968fe65a0b65/lazyaction/route_table_test.go (about) 1 package lazyaction 2 3 import ( 4 "math/rand" 5 "testing" 6 "time" 7 ) 8 9 func TestRouteTable(t *testing.T) { 10 11 rt := NewRouteTable[string]() 12 examples := []struct{ route, url string }{} 13 add := func(p, example string) { 14 examples = append(examples, struct{ route, url string }{p, example}) 15 rt.Add(p, &p) 16 } 17 18 add("/", "/") 19 add("/:name", "/welcome") 20 add("/:name/show", "/photo/show") 21 add("/:page/publish", "/about/publish") 22 add("/posts/old", "/posts/33") 23 add("/users/:id", "/users/33") 24 add("/users/new", "/users/33") 25 add("/users/:id/censor", "/users/33/censor") 26 27 for _, e := range examples { 28 r := rt.Find(e.route) 29 if r == nil { 30 t.Errorf("route %q not found", e.route) 31 continue 32 } 33 if *r != e.route { 34 t.Errorf("expected %q to route to %q", e.route, *r) 35 } 36 } 37 } 38 39 func BenchmarkRouteTableFind(b *testing.B) { 40 41 rt := NewRouteTable[string]() 42 for _, r := range routes { 43 if rt.Find(r[1]) != nil { 44 rt.Add(r[1], &r[1]) 45 } 46 } 47 48 rand.Seed(time.Now().Unix()) 49 order := rand.Perm(10) 50 51 // run the Fib function b.N times 52 for n := 0; n < b.N; n++ { 53 r := routes[order[n%len(order)]] 54 rt.Find(r[1]) 55 } 56 }