Files
mtusi2026lab2/student-tests/race_test.go
T

101 lines
2.1 KiB
Go

//go:build race
package studenttests_test
import (
"net/http"
"sync"
"testing"
"mtusi2026-messenger/internal/dto"
)
func TestConcurrentMessages(t *testing.T) {
const clients = 10
const messagesPerClient = 10
const total = clients * messagesPerClient
user1 := createUser(t)
user2 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
var wg sync.WaitGroup
var mu sync.Mutex
sentIDs := make(map[string]bool, total)
start := make(chan struct{})
for worker := 0; worker < clients; worker++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
actor := user1
if workerID%2 == 1 {
actor = user2
}
<-start
for i := 0; i < messagesPerClient; i++ {
resp := sendMessage(t, actor, chat.ID, "race-msg")
if resp.StatusCode != http.StatusCreated {
t.Errorf("worker %d msg %d: expected 201, got %d", workerID, i, resp.StatusCode)
resp.Body.Close()
continue
}
var m dto.MessageResponse
mustDecode(t, resp, &m)
mu.Lock()
sentIDs[m.ID.String()] = true
mu.Unlock()
}
}(worker)
}
close(start)
wg.Wait()
if t.Failed() {
t.Fatal("one or more send requests failed, see errors above")
}
if len(sentIDs) != total {
t.Fatalf("expected %d successful sends, got %d unique ids", total, len(sentIDs))
}
seen := make(map[string]bool, total)
path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=100"
resp := doRequest(t, http.MethodGet, path, user1.Token, nil)
requireStatus(t, resp, http.StatusOK)
var page dto.MessagePageResponse
mustDecode(t, resp, &page)
if page.NextCursor != nil {
t.Fatalf("expected next_cursor to be nil, history may contain more than %d messages", total)
}
for _, msg := range page.Items {
id := msg.ID.String()
if seen[id] {
t.Fatalf("duplicate message id in history: %s", id)
}
if !sentIDs[id] {
t.Fatalf("message %s in history was never sent by this test", id)
}
seen[id] = true
}
if len(seen) != total {
t.Fatalf("expected exactly %d unique messages in history, got %d", total, len(seen))
}
t.Logf("PASS: %d concurrent clients sent %d messages, exactly %d unique messages persisted",
clients, total, len(seen))
}