middleware: add tests for RequestSize (#1252)
This commit is contained in:
parent
9f8adb1aab
commit
c64ed7d663
1 changed files with 61 additions and 0 deletions
61
middleware/request_size_test.go
Normal file
61
middleware/request_size_test.go
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func TestRequestSize(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const limit = 10
|
||||
|
||||
var tests = []struct {
|
||||
name string
|
||||
body string
|
||||
want int
|
||||
}{
|
||||
{"should accept a body smaller than the limit", "short", http.StatusOK},
|
||||
{"should accept a body exactly at the limit", strings.Repeat("a", limit), http.StatusOK},
|
||||
{"should reject a body one byte over the limit", strings.Repeat("a", limit+1), http.StatusRequestEntityTooLarge},
|
||||
{"should accept an empty body", "", http.StatusOK},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Use(RequestSize(limit))
|
||||
r.Post("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
b, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
var maxErr *http.MaxBytesError
|
||||
if !errors.As(err, &maxErr) {
|
||||
t.Errorf("expected *http.MaxBytesError, got %T: %v", err, err)
|
||||
}
|
||||
w.WriteHeader(http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
if string(b) != tt.body {
|
||||
t.Errorf("got body %q, want %q", b, tt.body)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(tt.body))
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != tt.want {
|
||||
t.Errorf("got status %d, want %d", rec.Code, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue