-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrouter_test.go
121 lines (101 loc) · 2.26 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
package router
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
type mockResponseWriter struct{}
func TestRouterGET(t *testing.T) {
router := New()
routed := false
router.GET("/test", func(*Context) {
routed = true
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/test", nil)
router.ServeHTTP(w, req)
if !routed {
t.Fatal("routing get failed")
}
}
func TestRouterPOST(t *testing.T) {
router := New()
routed := false
router.POST("/test", func(*Context) {
routed = true
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/test", nil)
router.ServeHTTP(w, req)
if !routed {
t.Fatal("routing post failed")
}
}
func TestRouterGroup(t *testing.T) {
router := New()
routed := false
router.Group("api", func() {
router.GET("test", func(*Context) {
routed = true
})
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/test", nil)
router.ServeHTTP(w, req)
if !routed {
t.Fatal("routing group failed")
}
}
func TestRouterUse(t *testing.T) {
router := New()
routed := false
used := false
router.Use(func(c *Context) {
used = true
c.Next()
})
router.Group("api", func() {
router.GET("test", func(*Context) {
routed = true
})
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/test", nil)
router.ServeHTTP(w, req)
if !used || !routed {
t.Fatal("routing use failed")
}
}
func TestRouterNotFound(t *testing.T) {
router := New()
router.POST("/test", func(*Context) {
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/test1", nil)
router.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatal("NotFound handling route failed")
}
}
// func TestRouterMethodUnsupported(t *testing.T) {
// router := New()
// router.POST("/test", func(*Context) {
// })
// w := httptest.NewRecorder()
// req, _ := http.NewRequest("GET", "/test", nil)
// router.ServeHTTP(w, req)
// if w.Code != http.StatusNotImplemented {
// t.Fatal("Method unsupported handling route failed")
// }
// }
func TestRouterWithSameURL(t *testing.T) {
router := New()
router.Group("/api", func() {
router.GET("/test")
router.POST("/test")
})
for k, r := range router.routers {
fmt.Printf("method is %s, path is %v\n", r.method, k)
}
}