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
|
// SPDX-FileCopyrightText: © 2022 Grégoire Duchêne <gduchene@awhk.org>
// SPDX-License-Identifier: ISC
package core_test
import (
"net/http"
"net/http/httptest"
"testing"
"go.awhk.org/core"
)
func TestFilteringHTTPHandler(s *testing.T) {
t := core.T{T: s}
handler := core.FilteringHTTPHandler(
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }),
core.FilterHTTPMethod(http.MethodHead),
)
for _, tc := range []struct {
name string
method string
expHeader http.Header
expStatusCode int
}{
{
name: "Success",
method: http.MethodHead,
expHeader: http.Header{},
expStatusCode: http.StatusOK,
},
{
name: "WhenFiltered",
method: http.MethodGet,
expHeader: http.Header{"Allowed": {"HEAD"}},
expStatusCode: http.StatusMethodNotAllowed,
},
} {
t.Run(tc.name, func(t *core.T) {
var (
req = httptest.NewRequest(tc.method, "/", nil)
w = httptest.NewRecorder()
)
handler.ServeHTTP(w, req)
res := w.Result()
t.AssertEqual(tc.expHeader, res.Header)
t.AssertEqual(tc.expStatusCode, res.StatusCode)
})
}
}
func TestFilterHTTPMethod(s *testing.T) {
t := core.T{T: s}
filter := core.FilterHTTPMethod(http.MethodPost, http.MethodGet)
for _, tc := range []struct {
name string
method string
expAllowed string
expFiltered bool
expStatusCode int
}{
{
name: "Success",
method: http.MethodPost,
expFiltered: false,
expStatusCode: http.StatusOK,
},
{
name: "WhenFiltered",
method: http.MethodHead,
expAllowed: "GET, POST",
expFiltered: true,
expStatusCode: http.StatusMethodNotAllowed,
},
} {
t.Run(tc.name, func(t *core.T) {
var (
req = httptest.NewRequest(tc.method, "/", nil)
w = httptest.NewRecorder()
)
t.AssertEqual(tc.expFiltered, filter(w, req))
res := w.Result()
t.AssertEqual(tc.expAllowed, res.Header.Get("Allowed"))
t.AssertEqual(tc.expStatusCode, res.StatusCode)
})
}
}
|