forked from mtusi2026/mtusi2026lab2
85 lines
2.5 KiB
Go
85 lines
2.5 KiB
Go
package http
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
func TestConcurrency_100MessagesFrom10Clients(t *testing.T) {
|
|
const clients = 10
|
|
const perClient = 10
|
|
const total = clients * perClient
|
|
|
|
r := newTestRig(t)
|
|
users := make([]testUser, clients)
|
|
memberIDs := make([]string, clients)
|
|
for i := range users {
|
|
users[i] = r.createUser(fmt.Sprintf("race_%02d_%s", i, randomSuffix()), fmt.Sprintf("Клиент %d", i))
|
|
memberIDs[i] = users[i].ID
|
|
}
|
|
chat := r.createChat(users[0], "Гонка", memberIDs...)
|
|
|
|
type result struct {
|
|
id, text string
|
|
err error
|
|
}
|
|
results := make(chan result, total)
|
|
start := make(chan struct{})
|
|
var wg sync.WaitGroup
|
|
for i, actor := range users {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
<-start
|
|
for j := 0; j < perClient; j++ {
|
|
text := fmt.Sprintf("race-c%02d-m%02d", i, j)
|
|
status, msg, body := r.sendRaw(actor, chat.ID, mustJSON(map[string]string{"text": text}))
|
|
if status != http.StatusCreated {
|
|
results <- result{err: fmt.Errorf("%s: status %d: %s", text, status, body)}
|
|
continue
|
|
}
|
|
results <- result{id: msg.ID, text: msg.Text}
|
|
}
|
|
}()
|
|
}
|
|
close(start)
|
|
wg.Wait()
|
|
close(results)
|
|
|
|
sentIDs := make(map[string]string, total)
|
|
for res := range results {
|
|
if res.err != nil {
|
|
t.Fatal(res.err)
|
|
}
|
|
if _, dup := sentIDs[res.id]; dup {
|
|
t.Fatalf("сервер выдал один id %s двум сообщениям", res.id)
|
|
}
|
|
sentIDs[res.id] = res.text
|
|
}
|
|
if len(sentIDs) != total {
|
|
t.Fatalf("подтверждено %d сообщений, ожидалось %d", len(sentIDs), total)
|
|
}
|
|
|
|
history, _ := r.listMessages(users[0], chat.ID, 100)
|
|
if len(history) != total {
|
|
t.Fatalf("в истории %d сообщений, ожидалось ровно %d", len(history), total)
|
|
}
|
|
seen := make(map[string]struct{}, total)
|
|
for i, m := range history {
|
|
if _, dup := seen[m.ID]; dup {
|
|
t.Fatalf("id %s встречается в истории дважды", m.ID)
|
|
}
|
|
seen[m.ID] = struct{}{}
|
|
if text, ok := sentIDs[m.ID]; !ok || text != m.Text {
|
|
t.Fatalf("сообщение %s (%q) в истории не совпадает с подтверждённым", m.ID, m.Text)
|
|
}
|
|
if i > 0 && !history[i-1].CreatedAt.Before(m.CreatedAt) {
|
|
t.Fatalf("порядок (created_at) нарушен на индексе %d", i)
|
|
}
|
|
}
|
|
t.Logf("%d клиентов × %d сообщений = %d уникальных сообщений в истории, 0 дубликатов",
|
|
clients, perClient, total)
|
|
}
|