-
Notifications
You must be signed in to change notification settings - Fork 6
/
chain_test.go
110 lines (99 loc) · 2.52 KB
/
chain_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
// Copyright (c) 2016, Janoš Guljaš <janos@resenje.org>
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestChain(t *testing.T) {
handlers := []func(http.Handler) http.Handler{
func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("0"))
if h != nil {
h.ServeHTTP(w, r)
}
})
},
func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("1"))
if h != nil {
h.ServeHTTP(w, r)
}
})
},
func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("2"))
if h != nil {
h.ServeHTTP(w, r)
}
})
},
}
r := httptest.NewRequest("", "/", nil)
w := httptest.NewRecorder()
ChainHandlers(handlers...).ServeHTTP(w, r)
b, err := io.ReadAll(w.Result().Body)
if err != nil {
t.Error(err)
}
if string(b) != "012" {
t.Errorf("expected body %q, got %q", "012", string(b))
}
}
func TestFinalHandler(t *testing.T) {
handlers := []func(http.Handler) http.Handler{
func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("0"))
if h != nil {
h.ServeHTTP(w, r)
}
})
},
FinalHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("1"))
})),
}
r := httptest.NewRequest("", "/", nil)
w := httptest.NewRecorder()
ChainHandlers(handlers...).ServeHTTP(w, r)
b, err := io.ReadAll(w.Result().Body)
if err != nil {
t.Error(err)
}
if string(b) != "01" {
t.Errorf("expected body %q, got %q", "01", string(b))
}
}
func TestFinalHandlerFunc(t *testing.T) {
handlers := []func(http.Handler) http.Handler{
func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("0"))
if h != nil {
h.ServeHTTP(w, r)
}
})
},
FinalHandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("1"))
}),
}
r := httptest.NewRequest("", "/", nil)
w := httptest.NewRecorder()
ChainHandlers(handlers...).ServeHTTP(w, r)
b, err := io.ReadAll(w.Result().Body)
if err != nil {
t.Error(err)
}
if string(b) != "01" {
t.Errorf("expected body %q, got %q", "01", string(b))
}
}