-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathrequest_body_limit_test.go
More file actions
103 lines (88 loc) · 2.21 KB
/
request_body_limit_test.go
File metadata and controls
103 lines (88 loc) · 2.21 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/
package middleware
import (
"bytes"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/require"
"github.com/acronis/go-appkit/restapi"
)
type mockRequestBodyLimitNextHandler struct {
called int
}
func (h *mockRequestBodyLimitNextHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
h.called++
if _, err := io.ReadAll(r.Body); err != nil {
var reqTooLargeErr *restapi.RequestBodyTooLargeError
if errors.As(err, &reqTooLargeErr) {
rw.WriteHeader(http.StatusRequestEntityTooLarge)
return
}
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
func TestRequestBodyLimitHandler_ServeHTTP(t *testing.T) {
type testData struct {
ReqBodyMaxSize uint64
ReqBody string
SendContentLength bool
WantRespHTTPCode int
}
tests := []testData{
{
ReqBodyMaxSize: 32,
ReqBody: strings.Repeat("a", 64),
SendContentLength: true,
WantRespHTTPCode: http.StatusRequestEntityTooLarge,
},
{
ReqBodyMaxSize: 32,
ReqBody: strings.Repeat("a", 10),
WantRespHTTPCode: http.StatusOK,
},
{
ReqBodyMaxSize: 32,
ReqBody: strings.Repeat("a", 32),
WantRespHTTPCode: http.StatusOK,
},
{
ReqBodyMaxSize: 32,
ReqBody: strings.Repeat("a", 33),
WantRespHTTPCode: http.StatusRequestEntityTooLarge,
},
{
ReqBodyMaxSize: 0,
ReqBody: "a",
WantRespHTTPCode: http.StatusRequestEntityTooLarge,
},
{
ReqBodyMaxSize: 0,
ReqBody: "",
WantRespHTTPCode: http.StatusOK,
},
}
for _, test := range tests {
next := &mockRequestBodyLimitNextHandler{}
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString(test.ReqBody))
if !test.SendContentLength {
req.ContentLength = -1
}
h := RequestBodyLimit(test.ReqBodyMaxSize, "MyService")(next)
resp := httptest.NewRecorder()
h.ServeHTTP(resp, req)
wantNextCalled := 1
if test.SendContentLength && test.WantRespHTTPCode == http.StatusRequestEntityTooLarge {
wantNextCalled = 0
}
require.Equal(t, wantNextCalled, next.called)
require.Equal(t, test.WantRespHTTPCode, resp.Code)
}
}