forked from mtusi2026/mtusi2026lab6
70 lines
1.9 KiB
Go
70 lines
1.9 KiB
Go
package fiber
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
|
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/http"
|
|
)
|
|
|
|
// TestBodyLimitInstanceHeader verifies parser-generated 413 responses over a real TCP listener.
|
|
func TestBodyLimitInstanceHeader(t *testing.T) {
|
|
// Arrange.
|
|
ctrl := testController(t, func(cfg *config.Config) {
|
|
cfg.HTTP.MaxBodyBytes = 64 << 10
|
|
cfg.HTTP.InstanceID = "body-limit-test-instance"
|
|
})
|
|
ctrl.cfg.Host = "127.0.0.1"
|
|
ctrl.cfg.Port = 0
|
|
address := make(chan string, 1)
|
|
ctrl.server.Hooks().OnListen(func(data fiber.ListenData) error {
|
|
address <- net.JoinHostPort(data.Host, data.Port)
|
|
return nil
|
|
})
|
|
if err := ctrl.Start(t.Context()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancel()
|
|
if err := ctrl.Stop(ctx); err != nil {
|
|
t.Error(err)
|
|
}
|
|
})
|
|
client := &http.Client{Timeout: 3 * time.Second}
|
|
|
|
// Act.
|
|
response, err := client.Post("http://"+<-address+"/api/v1/users", "application/json", strings.NewReader(strings.Repeat("x", ctrl.cfg.MaxBodyBytes+1)))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() {
|
|
if err := response.Body.Close(); err != nil {
|
|
t.Error(err)
|
|
}
|
|
}()
|
|
|
|
// Assert.
|
|
if response.StatusCode != http.StatusRequestEntityTooLarge {
|
|
t.Fatalf("status=%d", response.StatusCode)
|
|
}
|
|
if instance := response.Header.Get("X-Instance-Id"); instance != ctrl.instanceID {
|
|
t.Fatalf("instance=%q, want %q", instance, ctrl.instanceID)
|
|
}
|
|
var body httpmodel.ErrorResponse
|
|
if err := json.NewDecoder(response.Body).Decode(&body); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if body.Error.Code != "payload_too_large" || body.Error.RequestID == "" || body.Error.RequestID != response.Header.Get(headerRequestID) {
|
|
t.Fatalf("invalid error envelope: %+v", body)
|
|
}
|
|
}
|