-
-
Notifications
You must be signed in to change notification settings - Fork 988
/
path_value_test.go
77 lines (67 loc) · 1.74 KB
/
path_value_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
//go:build go1.22
// +build go1.22
package chi
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestPathValue(t *testing.T) {
testCases := []struct {
name string
pattern string
method string
pathKeys []string
requestPath string
expectedBody string
}{
{
name: "Basic path value",
pattern: "/hubs/{hubID}",
method: "GET",
pathKeys: []string{"hubID"},
requestPath: "/hubs/392",
expectedBody: "392",
},
{
name: "Two path values",
pattern: "/users/{userID}/conversations/{conversationID}",
method: "POST",
pathKeys: []string{"userID", "conversationID"},
requestPath: "/users/Gojo/conversations/2948",
expectedBody: "Gojo 2948",
},
{
name: "Wildcard path",
pattern: "/users/{userID}/friends/*",
method: "POST",
pathKeys: []string{"userID", "*"},
requestPath: "/users/Gojo/friends/all-of-them/and/more",
expectedBody: "Gojo all-of-them/and/more",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
r := NewRouter()
r.Handle(tc.method+" "+tc.pattern, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pathValues := []string{}
for _, pathKey := range tc.pathKeys {
pathValue := r.PathValue(pathKey)
if pathValue == "" {
pathValue = "NOT_FOUND:" + pathKey
}
pathValues = append(pathValues, pathValue)
}
body := strings.Join(pathValues, " ")
w.Write([]byte(body))
}))
ts := httptest.NewServer(r)
defer ts.Close()
_, body := testRequest(t, ts, tc.method, tc.requestPath, nil)
if body != tc.expectedBody {
t.Fatalf("expecting %q, got %q", tc.expectedBody, body)
}
})
}
}