-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodec_test.go
More file actions
86 lines (80 loc) · 2.43 KB
/
codec_test.go
File metadata and controls
86 lines (80 loc) · 2.43 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
package middleware
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/tiny-go/codec/driver"
"github.com/tiny-go/codec/driver/json"
"github.com/tiny-go/codec/driver/xml"
)
func TestCodecFromList(t *testing.T) {
type testCase struct {
title string
handler http.Handler
request *http.Request
ctype string
code int
body string
}
cases := []testCase{
{
title: "should throw an error if request codec in not supported",
handler: Codec(nil, driver.DummyRegistry{&json.JSON{}, &xml.XML{}})(nil),
request: func() *http.Request {
r, _ := http.NewRequest(http.MethodGet, "", nil)
r.Header.Set(contentTypeHeader, "unknown")
return r
}(),
code: http.StatusBadRequest,
body: "unsupported request codec: \"unknown\"\n",
},
{
title: "should throw an error if response codec in not supported",
handler: Codec(nil, driver.DummyRegistry{&json.JSON{}, &xml.XML{}})(nil),
request: func() *http.Request {
r, _ := http.NewRequest(http.MethodGet, "", nil)
r.Header.Set(contentTypeHeader, "application/json")
r.Header.Set(acceptHeader, "unknown")
return r
}(),
code: http.StatusBadRequest,
body: "unsupported response codec: \"unknown\"\n",
},
{
title: "should find corresponding codecs and handle the request successfully",
handler: Codec(nil, driver.DummyRegistry{&json.JSON{}, &xml.XML{}})(
BodyClose(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
type Data struct{ Test string }
var data Data
RequestCodecFromContext(r.Context()).Decoder(r.Body).Decode(&data)
ResponseCodecFromContext(r.Context()).Encoder(w).Encode(data)
}),
),
),
request: func() *http.Request {
r, _ := http.NewRequest(http.MethodGet, "", strings.NewReader("{\"test\":\"passed\"}\n"))
r.Header.Set(contentTypeHeader, "application/json")
r.Header.Set(acceptHeader, "application/xml")
return r
}(),
code: http.StatusOK,
body: "<Data><Test>passed</Test></Data>",
},
}
t.Run("Given middleware function", func(t *testing.T) {
for _, tc := range cases {
t.Run(tc.title, func(t *testing.T) {
w := httptest.NewRecorder()
tc.handler.ServeHTTP(w, tc.request)
if w.Code != tc.code {
t.Errorf("status code %d was expected to be %d", w.Code, tc.code)
}
if w.Body.String() != tc.body {
t.Errorf("response body %q was expected to be %q", w.Body.String(), tc.body)
}
})
}
})
}