-
Notifications
You must be signed in to change notification settings - Fork 5
/
middleware_media_type_test.go
115 lines (100 loc) · 2.49 KB
/
middleware_media_type_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
111
112
113
114
115
package oas
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRequestContentTypeValidator(t *testing.T) {
testCases := map[string]struct {
consumes []string
expectHandlerCalled bool
expectedStatus int
}{
"consumes application/json": {
consumes: []string{
"application/json",
},
expectHandlerCalled: true,
expectedStatus: http.StatusOK,
},
"consumes application/xml": {
consumes: []string{
"application/xml",
},
expectHandlerCalled: false,
expectedStatus: http.StatusUnsupportedMediaType,
},
}
// TODO: test accept
var produces []string
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
h := &fakeHandler{}
v := &requestContentTypeValidator{next: h}
w := httptest.NewRecorder()
v.ServeHTTP(w, newRequest(nil), tc.consumes, produces, true)
assert.Equal(t, tc.expectHandlerCalled, h.called)
assert.Equal(t, tc.expectedStatus, w.Code)
})
}
}
func TestResponseContentTypeValidator(t *testing.T) {
testCases := map[string]struct {
accept []string
produces []string
expectedErrors int
}{
"accept and produces application/json": {
accept: []string{"application/json"},
produces: []string{"application/json"},
expectedErrors: 0,
},
"accept application/xml": {
accept: []string{"application/xml"},
expectedErrors: 1,
},
"produces application/xml": {
produces: []string{"application/xml"},
expectedErrors: 1,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
var errs []error
errHandler := func(problem Problem) {
errs = append(errs, problem.Cause())
}
h := &fakeHandler{}
v := &responseContentTypeValidator{
next: h,
problemHandler: ProblemHandlerFunc(errHandler),
}
w := httptest.NewRecorder()
req := newRequest(tc.accept)
v.ServeHTTP(w, req, tc.produces, true)
assert.Len(t, errs, tc.expectedErrors)
})
}
}
func newRequest(accept []string) *http.Request {
req := httptest.NewRequest(http.MethodPost, "/foo", bytes.NewBufferString(`
{
"foo": "bar"
}
`))
req.Header.Set("Content-Type", "application/json")
if len(accept) > 0 {
req.Header["Accept"] = accept
}
return req
}
type fakeHandler struct {
called bool
}
func (h *fakeHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
h.called = true
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"foo":"bar"}`))
}