-
Notifications
You must be signed in to change notification settings - Fork 24
/
pat_test.go
82 lines (75 loc) · 2.45 KB
/
pat_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
// Copyright 2012 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pat
import (
"net/http"
"testing"
"github.com/gorilla/mux"
)
func myHandler(w http.ResponseWriter, r *http.Request) {
}
func testMatch(t *testing.T, meth, pat, path string, ok bool, vars map[string]string) {
r := New()
switch meth {
case "OPTIONS":
r.Options(pat, myHandler)
case "DELETE":
r.Delete(pat, myHandler)
case "HEAD":
r.Head(pat, myHandler)
case "GET":
r.Get(pat, myHandler)
case "POST":
r.Post(pat, myHandler)
case "PUT":
r.Put(pat, myHandler)
case "PATCH":
r.Patch(pat, myHandler)
}
req, _ := http.NewRequest(meth, "http://localhost"+path, nil)
m := mux.RouteMatch{}
if r.Match(req, &m) != ok {
if ok {
t.Errorf("Expected request to %q to match %q", path, pat)
} else {
t.Errorf("Expected request to %q to not match %q", path, pat)
}
} else if ok && vars != nil {
registerVars(req, m.Vars)
q := req.URL.Query()
for k, v := range vars {
if q.Get(k) != v {
t.Errorf("Variable missing: %q (value: %q)", k, q.Get(k))
}
}
}
}
func TestPatMatch(t *testing.T) {
testMatch(t, "OPTIONS", "/foo/{name}", "/foo/bar", true, map[string]string{":name": "bar"})
testMatch(t, "DELETE", "/foo/{name}", "/foo/bar", true, map[string]string{":name": "bar"})
testMatch(t, "HEAD", "/foo/{name}", "/foo/bar", true, map[string]string{":name": "bar"})
testMatch(t, "GET", "/foo/{name}", "/foo/bar/baz", true, map[string]string{":name": "bar"})
testMatch(t, "POST", "/foo/{name}/baz", "/foo/bar/baz", true, map[string]string{":name": "bar"})
testMatch(t, "PUT", "/foo/{name}/baz", "/foo/bar/baz/ding", true, map[string]string{":name": "bar"})
testMatch(t, "GET", "/foo/x{name}", "/foo/xbar", true, map[string]string{":name": "bar"})
testMatch(t, "GET", "/foo/x{name}", "/foo/xbar/baz", true, map[string]string{":name": "bar"})
testMatch(t, "PATCH", "/foo/x{name}", "/foo/xbar/baz", true, map[string]string{":name": "bar"})
}
func TestNamedRoutes(t *testing.T) {
router := New()
route := router.Get("/", nil)
name := "foo"
route.Name(name)
if route.GetError() != nil {
t.Errorf("Route name assign: %v", route.GetError())
}
gotRoute := router.Router.Get(name)
if gotRoute == nil {
t.Errorf("mux.Router.Get by name returned nil")
}
gotName := gotRoute.GetName()
if gotName != name {
t.Errorf("Unexpected route name: got=%q, want=%q", gotName, name)
}
}