2020-11-23 11:14:08 +00:00
|
|
|
package home
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"strings"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/AdguardTeam/AdGuardHome/internal/aghio"
|
|
|
|
"github.com/stretchr/testify/assert"
|
2021-02-12 10:27:44 +00:00
|
|
|
"github.com/stretchr/testify/require"
|
2020-11-23 11:14:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestLimitRequestBody(t *testing.T) {
|
|
|
|
errReqLimitReached := &aghio.LimitReachedError{
|
|
|
|
Limit: RequestBodySizeLimit,
|
|
|
|
}
|
|
|
|
|
|
|
|
testCases := []struct {
|
|
|
|
name string
|
|
|
|
body string
|
|
|
|
want []byte
|
|
|
|
wantErr error
|
|
|
|
}{{
|
|
|
|
name: "not_so_big",
|
|
|
|
body: "somestr",
|
|
|
|
want: []byte("somestr"),
|
|
|
|
wantErr: nil,
|
|
|
|
}, {
|
|
|
|
name: "so_big",
|
|
|
|
body: string(make([]byte, RequestBodySizeLimit+1)),
|
|
|
|
want: make([]byte, RequestBodySizeLimit),
|
|
|
|
wantErr: errReqLimitReached,
|
|
|
|
}, {
|
|
|
|
name: "empty",
|
|
|
|
body: "",
|
|
|
|
want: []byte(nil),
|
|
|
|
wantErr: nil,
|
|
|
|
}}
|
|
|
|
|
|
|
|
makeHandler := func(err *error) http.HandlerFunc {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
var b []byte
|
|
|
|
b, *err = ioutil.ReadAll(r.Body)
|
2021-02-04 12:12:34 +00:00
|
|
|
_, werr := w.Write(b)
|
|
|
|
if werr != nil {
|
|
|
|
panic(werr)
|
|
|
|
}
|
2020-11-23 11:14:08 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, tc := range testCases {
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
var err error
|
|
|
|
handler := makeHandler(&err)
|
|
|
|
lim := limitRequestBody(handler)
|
|
|
|
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "https://www.example.com", strings.NewReader(tc.body))
|
|
|
|
res := httptest.NewRecorder()
|
|
|
|
|
|
|
|
lim.ServeHTTP(res, req)
|
|
|
|
|
2021-02-12 10:27:44 +00:00
|
|
|
require.Equal(t, tc.wantErr, err)
|
2020-11-23 11:14:08 +00:00
|
|
|
assert.Equal(t, tc.want, res.Body.Bytes())
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|