forked from mtusi2026/mtusi2026lab2
163 lines
3.6 KiB
Go
163 lines
3.6 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"mtusi2026/internal/model"
|
|
)
|
|
|
|
func TestConcurrentMessages_NoLostOrDuplicated(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
chat := mustCreateChat(t, srv, alice, "нагрузочный чат", []string{alice.ID})
|
|
const clients = 10
|
|
const perClients = 10
|
|
const total = clients * perClients
|
|
|
|
var wg sync.WaitGroup
|
|
errCh := make(chan error, total)
|
|
client := srv.Client()
|
|
|
|
for c := 0; c < clients; c++ {
|
|
wg.Add(1)
|
|
go func(clientNum int) {
|
|
defer wg.Done()
|
|
for i := 0; i < perClients; i++ {
|
|
text := fmt.Sprintf("client-%d-msg-%d", clientNum, i)
|
|
body, _ := json.Marshal(model.CreateMessageRequest{Text: text})
|
|
req, err := http.NewRequest(
|
|
http.MethodPost,
|
|
fmt.Sprintf("%s/api/v1/chats/%s/messages", srv.URL, chat.ID),
|
|
bytes.NewReader(body),
|
|
)
|
|
if err != nil {
|
|
errCh <- fmt.Errorf("client %d: build request: %w", clientNum, err)
|
|
continue
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+alice.Token)
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
errCh <- fmt.Errorf("client %d: do request: %w", clientNum, err)
|
|
continue
|
|
}
|
|
if resp.StatusCode != http.StatusCreated {
|
|
errCh <- fmt.Errorf("client %d msg %d: expected 201, got %d", clientNum, i, resp.StatusCode)
|
|
}
|
|
resp.Body.Close()
|
|
}
|
|
}(c)
|
|
}
|
|
wg.Wait()
|
|
close(errCh)
|
|
|
|
for err := range errCh {
|
|
t.Error(err)
|
|
}
|
|
if t.Failed() {
|
|
t.Fatal("прекращение из-за ошбок запросов")
|
|
}
|
|
|
|
resp := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?limit=100", chat.ID), alice.Token)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("list messages: expected 200, got %d", resp.StatusCode)
|
|
}
|
|
page := decodeBody[model.MessagePage](t, resp)
|
|
|
|
if page.NextCursor != nil {
|
|
t.Fatalf("expected all %d messages to fit on one page with limit=100, got next_cursor", total)
|
|
}
|
|
if len(page.Items) != total {
|
|
t.Fatalf("expected exactly %d messages, got %d", total, len(page.Items))
|
|
}
|
|
|
|
seen := make(map[string]bool, total)
|
|
for _, m := range page.Items {
|
|
if seen[m.ID] {
|
|
t.Fatalf("duplicate message ID found: %s", m.ID)
|
|
}
|
|
seen[m.ID] = true
|
|
if m.SenderID != alice.ID {
|
|
t.Fatalf("unexpected sender_id: %s", m.SenderID)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRegisterUser_ConcurrentDuplicateUsername_OnlyOneSucceeds(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
const workers = 20
|
|
|
|
statuses := make(chan int, workers)
|
|
|
|
var wg sync.WaitGroup
|
|
wg.Add(workers)
|
|
|
|
for i := 0; i < workers; i++ {
|
|
go func() {
|
|
defer wg.Done()
|
|
|
|
body := `{
|
|
"username": "raceuser",
|
|
"display_name": "Race User",
|
|
"password": "correct-horse-battery-staple"
|
|
}`
|
|
|
|
req, err := http.NewRequest(
|
|
http.MethodPost,
|
|
srv.URL+"/api/v1/users",
|
|
strings.NewReader(body),
|
|
)
|
|
if err != nil {
|
|
statuses <- -1
|
|
return
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := srv.Client().Do(req)
|
|
if err != nil {
|
|
statuses <- -1
|
|
return
|
|
}
|
|
|
|
statuses <- resp.StatusCode
|
|
resp.Body.Close()
|
|
}()
|
|
}
|
|
|
|
wg.Wait()
|
|
close(statuses)
|
|
|
|
created := 0
|
|
conflicts := 0
|
|
|
|
for status := range statuses {
|
|
switch status {
|
|
case http.StatusCreated:
|
|
created++
|
|
case http.StatusConflict:
|
|
conflicts++
|
|
default:
|
|
t.Errorf("unexpected status code: %d", status)
|
|
}
|
|
}
|
|
|
|
if created != 1 {
|
|
t.Fatalf("ожидалась одна успешная регистрация, got %d", created)
|
|
}
|
|
|
|
if conflicts != workers-1 {
|
|
t.Fatalf("expected %d conflicts, got %d", workers-1, conflicts)
|
|
}
|
|
}
|