Files

322 lines
8.7 KiB
Go

package fiber
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"sync"
"testing"
"github.com/google/uuid"
"go.uber.org/zap"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/production"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/memory"
)
// testController creates an integration fixture with the real controller, service and store.
func testController(t *testing.T, change func(*config.Config)) *Controller {
t.Helper()
cfg := config.Default()
cfg.HTTP.MaxConnections = 256
cfg.HTTP.Admission.RequestsPerSecond = 100000
cfg.HTTP.Admission.Burst = 100000
if change != nil {
change(cfg)
}
repo, err := memory.New(cfg.Memory)
if err != nil {
t.Fatal(err)
}
codec, err := cursor.New()
if err != nil {
t.Fatal(err)
}
svc, err := production.New(repo, codec)
if err != nil {
t.Fatal(err)
}
registry, err := NewErrorRegistry()
if err != nil {
t.Fatal(err)
}
limiter, err := admission.New(admission.Options{
MaxInFlight: cfg.HTTP.Admission.MaxInFlight,
RequestsPerSecond: cfg.HTTP.Admission.RequestsPerSecond,
Burst: cfg.HTTP.Admission.Burst,
})
if err != nil {
t.Fatal(err)
}
ctrl, err := New(zap.NewNop(), cfg.HTTP, svc, registry, &fixtureAdmission{limiter}, fixtureAuthentication{svc}, fixtureReadiness{})
if err != nil {
t.Fatal(err)
}
return ctrl
}
// request sends a raw test request and decodes its response.
func request(ctrl *Controller, method, path, actor string, body []byte) (int, map[string]any, error) {
req := httptest.NewRequest(method, path, bytes.NewReader(body))
req.Header.Set("Idempotency-Key", uuid.NewString())
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if actor != "" {
req.Header.Set("Authorization", "Bearer "+actor)
}
resp, err := ctrl.server.Test(req, 10000)
if err != nil {
return 0, nil, err
}
defer func() {
_ = resp.Body.Close()
}()
b, err := io.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
var data map[string]any
if err = json.Unmarshal(b, &data); err != nil {
return resp.StatusCode, nil, fmt.Errorf("invalid JSON response: %w", err)
}
if resp.Header.Get("X-Request-Id") == "" {
return resp.StatusCode, data, fmt.Errorf("missing request ID")
}
if resp.StatusCode >= http.StatusBadRequest {
envelope, ok := data["error"].(map[string]any)
if !ok || envelope["request_id"] != resp.Header.Get("X-Request-Id") {
return resp.StatusCode, data, fmt.Errorf("invalid error envelope")
}
}
return resp.StatusCode, data, nil
}
// call sends a JSON test request and checks its expected HTTP status.
func call(t *testing.T, ctrl *Controller, method, path, actor string, body any, want int) map[string]any {
t.Helper()
var b []byte
var err error
if raw, ok := body.([]byte); ok {
b = raw
} else if body != nil {
b, err = json.Marshal(body)
if err != nil {
t.Fatal(err)
}
}
status, data, err := request(ctrl, method, path, actor, b)
if err != nil {
t.Fatal(err)
}
if status != want {
t.Fatalf("%s %s: got %d want %d: %v", method, path, status, want, data)
}
return data
}
// user creates a test user and returns its identifier.
func user(t *testing.T, c *Controller) string {
t.Helper()
r := call(t, c, http.MethodPost, "/api/v1/users", "", map[string]any{"username": "u_" + uuid.New().String()[:8], "display_name": "Алиса 👋", "password": "fixture-password-123"}, http.StatusCreated)
return r["id"].(string)
}
// chat creates a test chat containing the supplied user.
func chat(t *testing.T, c *Controller, u string) string {
t.Helper()
r := call(t, c, http.MethodPost, "/api/v1/chats", u, map[string]any{"title": "Чат", "member_ids": []string{u}}, http.StatusCreated)
return r["id"].(string)
}
// TestDuplicateUsernameRace checks username uniqueness under concurrent requests.
func TestDuplicateUsernameRace(t *testing.T) {
// Arrange.
c := testController(t, nil)
results := make(chan int, 10)
failures := make(chan error, 10)
var wg sync.WaitGroup
// Act.
for range 10 {
wg.Go(func() {
status, _, err := request(c, http.MethodPost, "/api/v1/users", "", []byte(`{"username":"same","display_name":"User","password":"fixture-password-123"}`))
if err != nil {
failures <- err
}
results <- status
})
}
wg.Wait()
close(results)
close(failures)
// Assert.
for err := range failures {
t.Error(err)
}
created, conflicts := 0, 0
for s := range results {
switch s {
case http.StatusCreated:
created++
case http.StatusConflict:
conflicts++
default:
t.Errorf("unexpected %d", s)
}
}
if created != 1 || conflicts != 9 {
t.Fatalf("created=%d conflicts=%d", created, conflicts)
}
}
// history collects all test messages by following pagination cursors.
func history(t *testing.T, c *Controller, u, path string) []any {
t.Helper()
var items []any
next := path + "?limit=7"
for range 100 {
r := call(t, c, http.MethodGet, next, u, nil, http.StatusOK)
items = append(items, r["items"].([]any)...)
if r["next_cursor"] == nil {
return items
}
next = path + "?limit=7&cursor=" + url.QueryEscape(r["next_cursor"].(string))
}
t.Fatal("pagination never finished")
return nil
}
// TestConcurrent100Messages10Clients recovers the exact acknowledged records after concurrent writes.
func TestConcurrent100Messages10Clients(t *testing.T) {
// Arrange.
const clients = 10
const messagesPerClient = 10
const total = clients * messagesPerClient
ctrl := testController(t, nil)
actor := user(t, ctrl)
chatID := chat(t, ctrl, actor)
path := "/api/v1/chats/" + chatID + "/messages"
acknowledgements := make(chan map[string]any, total)
failures := make(chan error, total)
var writers sync.WaitGroup
// Act.
for client := range clients {
writers.Go(func() {
for index := range messagesPerClient {
text := fmt.Sprintf("client %d message %d", client, index)
payload, err := json.Marshal(map[string]string{"text": text})
if err != nil {
failures <- err
continue
}
status, body, err := request(ctrl, http.MethodPost, path, actor, payload)
if err != nil {
failures <- err
continue
}
if status != http.StatusCreated || body["text"] != text || body["sender_id"] != actor || body["chat_id"] != chatID {
failures <- fmt.Errorf("incorrect acknowledgement: status=%d, body=%v", status, body)
continue
}
acknowledgements <- body
}
})
}
writers.Wait()
close(failures)
close(acknowledgements)
// Assert.
for err := range failures {
t.Error(err)
}
if t.Failed() {
t.FailNow()
}
expected := make(map[string]map[string]any, total)
for message := range acknowledgements {
id, ok := message["id"].(string)
if !ok || id == "" {
t.Fatalf("invalid message ID: %v", message)
}
if _, duplicate := expected[id]; duplicate {
t.Fatalf("duplicate acknowledgement ID %s", id)
}
expected[id] = message
}
if len(expected) != total {
t.Fatalf("acknowledged=%d, want=%d", len(expected), total)
}
items := history(t, ctrl, actor, path)
if len(items) != total {
t.Fatalf("recovered=%d, want=%d", len(items), total)
}
for _, item := range items {
message := item.(map[string]any)
id := message["id"].(string)
if !reflect.DeepEqual(message, expected[id]) {
t.Fatalf("stored record differs from acknowledgement: got=%v, want=%v", message, expected[id])
}
delete(expected, id)
}
}
// TestUnsupportedMediaType checks rejection of unsupported request content types.
func TestUnsupportedMediaType(t *testing.T) {
// Arrange.
c := testController(t, nil)
req := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{}`))
req.Header.Set("Content-Type", "text/plain")
// Act.
r, e := c.server.Test(req)
// Assert.
if e != nil {
t.Fatal(e)
}
defer func() {
_ = r.Body.Close()
}()
if r.StatusCode != http.StatusUnsupportedMediaType {
t.Fatalf("status %d", r.StatusCode)
}
}
// TestConfigIndependentState prevents one application instance from accepting another's identity.
func TestConfigIndependentState(t *testing.T) {
// Arrange.
first := testController(t, nil)
actor := user(t, first)
second := testController(t, nil)
// Act.
status, body, err := request(second, http.MethodGet, "/api/v1/users/me", actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
assertErrorCode(t, body, "unauthorized")
}
// mustJSON encodes fixture payloads and reports preparation failures at the caller.
func mustJSON(t *testing.T, value any) []byte {
t.Helper()
payload, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
return payload
}