-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware_test.go
More file actions
89 lines (73 loc) · 2.24 KB
/
middleware_test.go
File metadata and controls
89 lines (73 loc) · 2.24 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
87
88
89
package middleware
import (
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
)
func TestWrapper(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
res := httptest.NewRecorder()
expected := []string{
"First",
"Second",
"Third",
"Handler",
"Third-to-Last",
"Second-to-Last",
"Last",
}
t.Run("Append Test", func(t *testing.T) {
var actual []string
w := &Wrapper{}
w.Append(getFakeMiddleware(&actual, "First", "Last"))
w.Append(getFakeMiddleware(&actual, "Second", "Second-to-Last"))
w.Append(getFakeMiddleware(&actual, "Third", "Third-to-Last"))
w.WrapHandler(getFakeHandler(&actual))(res, req)
if !reflect.DeepEqual(expected, actual) {
t.Error("Expected:", stringify(expected), "| Actual:", stringify(actual))
}
})
t.Run("Prepend Test", func(t *testing.T) {
var actual []string
w := &Wrapper{}
w.Prepend(getFakeMiddleware(&actual, "Third", "Third-to-Last"))
w.Prepend(getFakeMiddleware(&actual, "Second", "Second-to-Last"))
w.Prepend(getFakeMiddleware(&actual, "First", "Last"))
w.WrapHandler(getFakeHandler(&actual))(res, req)
if !reflect.DeepEqual(expected, actual) {
t.Error("Expected:", stringify(expected), "| Actual:", stringify(actual))
}
})
t.Run("Mixed With Chaining Syntax", func(t *testing.T) {
var actual []string
w := &Wrapper{}
w.
Prepend(getFakeMiddleware(&actual, "Second", "Second-to-Last")).
Append(getFakeMiddleware(&actual, "Third", "Third-to-Last")).
Prepend(getFakeMiddleware(&actual, "First", "Last")).
WrapHandler(getFakeHandler(&actual))(res, req)
if !reflect.DeepEqual(expected, actual) {
t.Error("Expected:", stringify(expected), "| Actual:", stringify(actual))
}
})
}
// ==================== Test Fixtures/Props =====================
func stringify(s []string) string {
return strings.Join(s, ",")
}
func getFakeHandler(actual *[]string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
*actual = append(*actual, "Handler")
}
}
func getFakeMiddleware(actual *[]string, before, after string) Middleware {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
*actual = append(*actual, before)
next(w, r)
*actual = append(*actual, after)
}
}
}