-
Notifications
You must be signed in to change notification settings - Fork 0
/
router_test.go
123 lines (103 loc) · 2.66 KB
/
router_test.go
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
package handlr
import (
"net/http"
"net/http/httptest"
"testing"
)
type unitTests struct {
r *http.Request
w *httptest.ResponseRecorder
m string
rt func()
fh func() *ActionHandlerFunc
}
func TestRegisterRoute(t *testing.T) {
h := New()
h.RouteFunc("/", func(r *Router) {
t.Logf("Route registered correctly.")
})
}
func TestRegisterHandler(t *testing.T) {
h := New()
r := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
h.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
t.Logf("Handler for %s registered correctly.", r.URL.Path)
})
h.mux.Handle("/", &h.router)
h.mux.ServeHTTP(w, r)
}
func TestBuildPath(t *testing.T) {
h := New()
f := func(bp string, rp string) bool {
pass := bp == rp
if pass {
t.Logf(bp)
} else {
t.Fatalf("Wrong path built: %s should've been %s.", bp, rp)
}
return pass
}
h.RouteFunc("a", func(r1 *Router) {
r1.RouteFunc("b", func(r2 *Router) {
r2.RouteFunc("c", func(r3 *Router) {
r3.RouteFunc("/", func(r4 *Router) {
if f(r4.buildPath(), "/a/b/c") && f(r3.buildPath(), "/a/b/c") && f(r2.buildPath(), "/a/b") && f(r1.buildPath(), "/a") {
t.Logf("Paths generated correctly.")
}
})
})
})
})
}
func TestFindHandler(t *testing.T) {
h := New()
tests := []unitTests{
{
r: httptest.NewRequest(http.MethodGet, "/a/b", nil),
w: httptest.NewRecorder(),
m: "Handler matched correctly.",
rt: func() {
h.RouteFunc("/", func(r1 *Router) {
r1.RouteFunc("/a", func(r2 *Router) {
r2.HandleFunc("/b", func(w http.ResponseWriter, r *http.Request) {
t.Logf("Handler for %s matched correctly.", r.URL.Path)
})
})
})
},
fh: func() *ActionHandlerFunc {
e := len(h.router.children) - 1 // For /
a := len(h.router.children[e].children) - 1 // For /a
b := len(h.router.children[e].children[a].children) - 1 // For /b
return h.router.children[e].children[a].children[b].handler
},
},
{
r: httptest.NewRequest(http.MethodGet, "/x/y/z", nil),
w: httptest.NewRecorder(),
m: "Handler matched correctly.",
rt: func() {
h.HandleFunc("/x/y/z", func(w http.ResponseWriter, r *http.Request) {
t.Logf("Handler for %s matched correctly.", r.URL.Path)
})
},
fh: func() *ActionHandlerFunc {
return h.router.children[1].handler
},
},
}
h.mux.Handle("/", &h.router)
for i := 0; i < len(tests); i++ {
u := tests[i]
u.rt()
fh := u.fh()
rh := h.router.findHandler(u.r)
if rh == fh {
h.mux.ServeHTTP(u.w, u.r)
} else {
t.Fatalf("Handler couldn't be found: %d != %d", fh, rh)
}
}
t.Logf("Handlers found without problems.")
}