66 lines
2.1 KiB
Go
66 lines
2.1 KiB
Go
package rest
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestLimitForRequest(t *testing.T) {
|
|
const (
|
|
defaultLimit = 1024
|
|
uploadLimit = 10 << 20
|
|
)
|
|
|
|
upload, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments", nil)
|
|
require.NoError(t, err)
|
|
require.Equal(t, int64(uploadLimit), limitForRequest(upload, defaultLimit, uploadLimit))
|
|
|
|
messages, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/messages", nil)
|
|
require.NoError(t, err)
|
|
require.Equal(t, int64(defaultLimit), limitForRequest(messages, defaultLimit, uploadLimit))
|
|
|
|
presign, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil)
|
|
require.NoError(t, err)
|
|
require.Equal(t, int64(defaultLimit), limitForRequest(presign, defaultLimit, uploadLimit))
|
|
}
|
|
|
|
func TestBodyLimitMiddlewareSelectsUploadLimit(t *testing.T) {
|
|
const (
|
|
defaultLimit = 16
|
|
uploadLimit = 64
|
|
)
|
|
|
|
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
_, _ = w.Write(body)
|
|
})
|
|
handler := bodyLimitMiddleware(defaultLimit, uploadLimit, nil, next)
|
|
|
|
upload := httptest.NewRequestWithContext(
|
|
t.Context(), http.MethodPost,
|
|
"/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments",
|
|
strings.NewReader(strings.Repeat("x", 32)),
|
|
)
|
|
uploadRecorder := httptest.NewRecorder()
|
|
handler.ServeHTTP(uploadRecorder, upload)
|
|
require.Equal(t, http.StatusOK, uploadRecorder.Code)
|
|
|
|
jsonRequest := httptest.NewRequestWithContext(
|
|
t.Context(), http.MethodPost,
|
|
"/api/v1/chats/11111111-1111-4111-8111-111111111111/messages",
|
|
strings.NewReader(strings.Repeat("x", 32)),
|
|
)
|
|
jsonRecorder := httptest.NewRecorder()
|
|
handler.ServeHTTP(jsonRecorder, jsonRequest)
|
|
require.Equal(t, http.StatusRequestEntityTooLarge, jsonRecorder.Code)
|
|
}
|