-
Notifications
You must be signed in to change notification settings - Fork 0
/
reqdecoder_test.go
112 lines (109 loc) · 2.32 KB
/
reqdecoder_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
package reqdecoder
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRequestDecoder(t *testing.T) {
type request struct {
contentEncoding string
}
type response struct {
status int
body string
}
tests := []struct {
name string
dFunc decoderFunc
req request
resp response
}{
{
name: "Empty Content-Encoding",
req: request{
contentEncoding: "",
},
resp: response{
status: http.StatusOK,
body: "",
},
},
{
name: "Content-Encoding identity",
req: request{
contentEncoding: "identity",
},
resp: response{
status: http.StatusOK,
body: "",
},
},
{
name: "Success decode",
dFunc: func(reader io.ReadCloser) io.ReadCloser {
return reader
},
req: request{
contentEncoding: "good_enc",
},
resp: response{
status: http.StatusOK,
body: "",
},
},
{
name: "Bad decode",
dFunc: func(reader io.ReadCloser) io.ReadCloser {
return nil
},
req: request{
contentEncoding: "bad_enc",
},
resp: response{
status: http.StatusInternalServerError,
body: "Can't decode body",
},
},
{
name: "Unknown enc",
req: request{
contentEncoding: "unknown",
},
resp: response{
status: http.StatusUnsupportedMediaType,
body: "Unsupported Content-Encoding",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.dFunc != nil {
AddDecoder(tt.req.contentEncoding, tt.dFunc)
}
svr := httptest.NewServer(RequestDecoder(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, tt.req.contentEncoding, r.Header.Get("Content-Encoding"))
w.WriteHeader(http.StatusOK)
_, err := w.Write(nil)
assert.NoError(t, err)
})))
defer svr.Close()
req, err := http.NewRequest(http.MethodPost, svr.URL, bytes.NewBuffer([]byte("test")))
assert.NoError(t, err)
req.Header.Set("Content-Encoding", tt.req.contentEncoding)
client := &http.Client{}
resp, err := client.Do(req)
assert.NoError(t, err)
defer func() {
err = resp.Body.Close()
assert.NoError(t, err)
}()
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, tt.resp.status, resp.StatusCode)
assert.Contains(t, string(body), tt.resp.body)
})
}
}