-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontext_test.go
More file actions
86 lines (70 loc) · 2.08 KB
/
context_test.go
File metadata and controls
86 lines (70 loc) · 2.08 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
package shift
import (
"net/http"
"testing"
)
func TestContext_FromContext(t *testing.T) {
t.Run("param route", func(t *testing.T) {
ip := newInternalParams(1)
ip.setKeys(&[]string{"name"})
ip.appendValue("dino")
paramRoute := Route{
Params: newParams(ip),
Path: "/foo/:name",
}
req, _ := http.NewRequest(http.MethodGet, "/foo/dino", nil)
req = req.WithContext(WithRoute(req.Context(), paramRoute))
route, ok := FromContext(req.Context())
assert(t, ok, "expected to find a route context")
assert(t, route == paramRoute, "expected routes to be equal")
})
t.Run("static route", func(t *testing.T) {
staticRoute := Route{
Params: Params{},
Path: "/foo",
}
req, _ := http.NewRequest(http.MethodGet, "/foo", nil)
req = req.WithContext(WithRoute(req.Context(), staticRoute))
route, ok := FromContext(req.Context())
assert(t, ok, "expected to find a route context")
assert(t, route == staticRoute, "expected routes to be equal")
})
}
func BenchmarkContext_FromContext(b *testing.B) {
b.Run("routeCtx context", func(b *testing.B) {
req, _ := http.NewRequest(http.MethodGet, "/movies/111/segments/222/frames/333", nil)
ctx := req.Context()
ip := newInternalParams(3)
ip.setKeys(&[]string{"id", "segmentId", "frameId"})
ip.appendValue("111")
ip.appendValue("222")
ip.appendValue("333")
req = req.WithContext(WithRoute(ctx, Route{
Params: newParams(ip),
Path: "/movies/:id/segments/:segmentId/frames/:frameId",
}))
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
FromContext(req.Context())
}
})
b.Run("non-routeCtx context", func(b *testing.B) {
req, _ := http.NewRequest(http.MethodGet, "/movies/genres/noir", nil)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
FromContext(req.Context())
}
})
}
func TestContext_RouteOf(t *testing.T) {
abcRoute := Route{
Params: newParams(nil),
Path: "/abc",
}
req, _ := http.NewRequest("GET", "/abc", nil)
ctx := WithRoute(req.Context(), abcRoute)
req = req.WithContext(ctx)
assert(t, RouteOf(req) == abcRoute, "expected routes to be equal")
}