forked from mtusi2026/mtusi2026lab2
Перенесена ЛР1
This commit is contained in:
@@ -0,0 +1,401 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
func fetchCursorPage(
|
||||
t *testing.T,
|
||||
baseURL, chatID, userID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) domain.MessagePage {
|
||||
t.Helper()
|
||||
|
||||
endpoint := fmt.Sprintf(
|
||||
"%s/api/v1/chats/%s/messages?limit=%d",
|
||||
baseURL,
|
||||
chatID,
|
||||
limit,
|
||||
)
|
||||
if cursor != "" {
|
||||
endpoint += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("X-User-Id", userID)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
t.Fatalf("expected 200, got %d: %s", res.StatusCode, body)
|
||||
}
|
||||
|
||||
var page domain.MessagePage
|
||||
if err := json.NewDecoder(res.Body).Decode(&page); err != nil {
|
||||
t.Fatalf("decode message page: %v", err)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
func TestCursorTraversalAfterConcurrentWrites(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
const (
|
||||
clients = 10
|
||||
messagesPerClient = 100
|
||||
expectedMessages = clients * messagesPerClient
|
||||
)
|
||||
|
||||
memberIDs := make([]string, 0, clients)
|
||||
for client := 0; client < clients; client++ {
|
||||
user, err := st.CreateUser(
|
||||
fmt.Sprintf("cursor_client_%d", client),
|
||||
fmt.Sprintf("Cursor client %d", client),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
memberIDs = append(memberIDs, user.ID)
|
||||
}
|
||||
|
||||
chat, err := st.CreateChat("Concurrent cursor test", memberIDs)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
start := make(chan struct{})
|
||||
var writers sync.WaitGroup
|
||||
for client := 0; client < clients; client++ {
|
||||
writers.Add(1)
|
||||
go func(client int) {
|
||||
defer writers.Done()
|
||||
<-start
|
||||
for message := 0; message < messagesPerClient; message++ {
|
||||
_, err := st.CreateMessage(
|
||||
chat.ID,
|
||||
memberIDs[client],
|
||||
fmt.Sprintf("client=%d message=%d", client, message),
|
||||
)
|
||||
if err != nil {
|
||||
t.Errorf("create message: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}(client)
|
||||
}
|
||||
|
||||
close(start)
|
||||
writers.Wait()
|
||||
|
||||
seen := make(map[string]struct{}, expectedMessages)
|
||||
duplicateCount := 0
|
||||
var previous *domain.Message
|
||||
firstOrderingViolation := ""
|
||||
cursor := ""
|
||||
pageCount := 0
|
||||
|
||||
for {
|
||||
pageCount++
|
||||
if pageCount > expectedMessages {
|
||||
t.Fatal("pagination did not terminate")
|
||||
}
|
||||
|
||||
page := fetchCursorPage(t, ts.URL, chat.ID, memberIDs[0], 17, cursor)
|
||||
for index := range page.Items {
|
||||
message := page.Items[index]
|
||||
if _, duplicate := seen[message.ID]; duplicate {
|
||||
duplicateCount++
|
||||
}
|
||||
seen[message.ID] = struct{}{}
|
||||
|
||||
if previous != nil {
|
||||
outOfOrder := message.CreatedAt.Before(previous.CreatedAt) ||
|
||||
(message.CreatedAt.Equal(previous.CreatedAt) && message.ID <= previous.ID)
|
||||
if outOfOrder && firstOrderingViolation == "" {
|
||||
firstOrderingViolation = fmt.Sprintf(
|
||||
"previous=(%s,%s), current=(%s,%s)",
|
||||
previous.CreatedAt.Format("15:04:05.999999999"), previous.ID,
|
||||
message.CreatedAt.Format("15:04:05.999999999"), message.ID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
messageCopy := message
|
||||
previous = &messageCopy
|
||||
}
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
|
||||
if len(seen) != expectedMessages || duplicateCount != 0 {
|
||||
t.Fatalf(
|
||||
"cursor traversal returned %d unique messages of %d and %d duplicates; first ordering violation: %s",
|
||||
len(seen), expectedMessages, duplicateCount, firstOrderingViolation,
|
||||
)
|
||||
}
|
||||
if firstOrderingViolation != "" {
|
||||
t.Fatalf("history is not ordered: %s", firstOrderingViolation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorTraversalDuringConcurrentWrites(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
const (
|
||||
clients = 16
|
||||
messagesPerClient = 100
|
||||
seedMessages = 100
|
||||
pageLimit = 7
|
||||
expectedTotal = seedMessages + clients*messagesPerClient
|
||||
)
|
||||
|
||||
memberIDs := make([]string, 0, clients)
|
||||
for client := 0; client < clients; client++ {
|
||||
user, err := st.CreateUser(
|
||||
fmt.Sprintf("live_cursor_client_%d", client),
|
||||
fmt.Sprintf("Live cursor client %d", client),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create user %d: %v", client, err)
|
||||
}
|
||||
memberIDs = append(memberIDs, user.ID)
|
||||
}
|
||||
|
||||
chat, err := st.CreateChat("Live concurrent cursor test", memberIDs)
|
||||
if err != nil {
|
||||
t.Fatalf("create chat: %v", err)
|
||||
}
|
||||
|
||||
// Начальные сообщения нужны, чтобы читатель сразу начал
|
||||
// двигать курсор, пока остальные сообщения ещё записываются.
|
||||
expectedIDs := make(map[string]struct{}, expectedTotal)
|
||||
for index := 0; index < seedMessages; index++ {
|
||||
message, err := st.CreateMessage(
|
||||
chat.ID,
|
||||
memberIDs[0],
|
||||
fmt.Sprintf("seed message=%d", index),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create seed message %d: %v", index, err)
|
||||
}
|
||||
expectedIDs[message.ID] = struct{}{}
|
||||
}
|
||||
|
||||
var expectedMu sync.Mutex
|
||||
var writers sync.WaitGroup
|
||||
var ready sync.WaitGroup
|
||||
|
||||
start := make(chan struct{})
|
||||
writerErrors := make(chan error, clients)
|
||||
|
||||
for client := 0; client < clients; client++ {
|
||||
writers.Add(1)
|
||||
ready.Add(1)
|
||||
|
||||
go func(client int) {
|
||||
defer writers.Done()
|
||||
|
||||
ready.Done()
|
||||
<-start
|
||||
|
||||
for index := 0; index < messagesPerClient; index++ {
|
||||
// Отдаём планировщику возможность чаще переключать
|
||||
// конкурентные горутины.
|
||||
runtime.Gosched()
|
||||
|
||||
message, err := st.CreateMessage(
|
||||
chat.ID,
|
||||
memberIDs[client],
|
||||
fmt.Sprintf("client=%d message=%d", client, index),
|
||||
)
|
||||
if err != nil {
|
||||
writerErrors <- fmt.Errorf(
|
||||
"client %d, message %d: %w",
|
||||
client,
|
||||
index,
|
||||
err,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
expectedMu.Lock()
|
||||
expectedIDs[message.ID] = struct{}{}
|
||||
expectedMu.Unlock()
|
||||
|
||||
// Не даём всем писателям завершиться до того,
|
||||
// как читатель успеет продвинуть курсор.
|
||||
time.Sleep(50 * time.Microsecond)
|
||||
}
|
||||
}(client)
|
||||
}
|
||||
|
||||
// Сначала убеждаемся, что все горутины готовы,
|
||||
// и только потом одновременно разрешаем запись.
|
||||
ready.Wait()
|
||||
|
||||
writersDone := make(chan struct{})
|
||||
go func() {
|
||||
writers.Wait()
|
||||
close(writersDone)
|
||||
}()
|
||||
|
||||
close(start)
|
||||
|
||||
seen := make(map[string]struct{}, expectedTotal)
|
||||
cursor := ""
|
||||
var previous *domain.Message
|
||||
|
||||
const maxPageRequests = expectedTotal * 4
|
||||
finished := false
|
||||
|
||||
for requestNumber := 0; requestNumber < maxPageRequests; requestNumber++ {
|
||||
page := fetchCursorPage(
|
||||
t,
|
||||
ts.URL,
|
||||
chat.ID,
|
||||
memberIDs[0],
|
||||
pageLimit,
|
||||
cursor,
|
||||
)
|
||||
|
||||
for index := range page.Items {
|
||||
message := page.Items[index]
|
||||
|
||||
if _, duplicate := seen[message.ID]; duplicate {
|
||||
t.Fatalf(
|
||||
"message %s was returned more than once",
|
||||
message.ID,
|
||||
)
|
||||
}
|
||||
|
||||
if previous != nil {
|
||||
outOfOrder :=
|
||||
message.CreatedAt.Before(previous.CreatedAt) ||
|
||||
(message.CreatedAt.Equal(previous.CreatedAt) &&
|
||||
message.ID <= previous.ID)
|
||||
|
||||
if outOfOrder {
|
||||
t.Fatalf(
|
||||
"messages are out of order: previous=(%s,%s), current=(%s,%s)",
|
||||
previous.CreatedAt.Format(time.RFC3339Nano),
|
||||
previous.ID,
|
||||
message.CreatedAt.Format(time.RFC3339Nano),
|
||||
message.ID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
seen[message.ID] = struct{}{}
|
||||
messageCopy := message
|
||||
previous = &messageCopy
|
||||
}
|
||||
|
||||
// Для продолжающегося чтения строим курсор по последнему
|
||||
// фактически полученному сообщению. Это позволяет опрашивать
|
||||
// историю, даже если в промежуточный момент сервер вернул
|
||||
// NextCursor=nil.
|
||||
if len(page.Items) > 0 {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
cursor = domain.EncodeCursor(
|
||||
last.CreatedAt,
|
||||
last.ID,
|
||||
chat.ID,
|
||||
)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-writersDone:
|
||||
finished = true
|
||||
default:
|
||||
}
|
||||
|
||||
// Все писатели завершились, а после текущего курсора
|
||||
// больше ничего нет: обход закончен.
|
||||
if finished && len(page.Items) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
if len(page.Items) == 0 {
|
||||
runtime.Gosched()
|
||||
}
|
||||
|
||||
if requestNumber == maxPageRequests-1 {
|
||||
t.Fatalf(
|
||||
"pagination did not terminate after %d requests",
|
||||
maxPageRequests,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
<-writersDone
|
||||
close(writerErrors)
|
||||
|
||||
for writerErr := range writerErrors {
|
||||
t.Errorf("create message: %v", writerErr)
|
||||
}
|
||||
|
||||
expectedMu.Lock()
|
||||
missingIDs := make([]string, 0)
|
||||
for id := range expectedIDs {
|
||||
if _, found := seen[id]; !found {
|
||||
missingIDs = append(missingIDs, id)
|
||||
}
|
||||
}
|
||||
expectedCount := len(expectedIDs)
|
||||
expectedMu.Unlock()
|
||||
|
||||
if expectedCount != expectedTotal {
|
||||
t.Fatalf(
|
||||
"writers confirmed %d messages, expected %d",
|
||||
expectedCount,
|
||||
expectedTotal,
|
||||
)
|
||||
}
|
||||
|
||||
if len(missingIDs) != 0 {
|
||||
const displayedMissingIDs = 5
|
||||
if len(missingIDs) > displayedMissingIDs {
|
||||
missingIDs = missingIDs[:displayedMissingIDs]
|
||||
}
|
||||
|
||||
t.Fatalf(
|
||||
"cursor traversal returned %d of %d confirmed messages; "+
|
||||
"examples of missing IDs: %v",
|
||||
len(seen),
|
||||
expectedTotal,
|
||||
missingIDs,
|
||||
)
|
||||
}
|
||||
|
||||
if len(seen) != expectedTotal {
|
||||
t.Fatalf(
|
||||
"cursor traversal returned %d messages, expected %d",
|
||||
len(seen),
|
||||
expectedTotal,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/handlers"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
// изолированный серв для тестов
|
||||
func setupTestServer() (*httptest.Server, *store.MemoryStore) {
|
||||
st := store.NewMemoryStore()
|
||||
h := handlers.NewHandler(st)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/users", h.CreateUser)
|
||||
mux.HandleFunc("GET /api/v1/users/me", middleware.RequireAuth(st, h.GetMe))
|
||||
mux.HandleFunc("POST /api/v1/chats", middleware.RequireAuth(st, h.CreateChat))
|
||||
mux.HandleFunc("GET /api/v1/chats", middleware.RequireAuth(st, h.ListChats))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", middleware.RequireAuth(st, h.GetChat))
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(st, h.CreateMessage))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(st, h.GetMessages))
|
||||
|
||||
var root http.Handler = mux
|
||||
root = middleware.Recovery(root)
|
||||
root = middleware.RequestID(root)
|
||||
|
||||
return httptest.NewServer(root), st
|
||||
}
|
||||
|
||||
// 1 тест на дубликат username -> 409 Conflict
|
||||
func TestDuplicateUsername(t *testing.T) {
|
||||
ts, _ := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
body := `{"username":"bob_the_builder","display_name":"Боб"}`
|
||||
|
||||
// Первый раз — 201 Created
|
||||
res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body))
|
||||
if res1.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// Второй раз тот же username — 409 Conflict
|
||||
res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body))
|
||||
if res2.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("expected 409 Conflict for duplicate username, got %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 2 тест на неверный JSON и лишние поля -> 400 Invalid Request
|
||||
func TestInvalidAndExtraJSON(t *testing.T) {
|
||||
ts, _ := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
// Кривой JSON (malformed)
|
||||
res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username": "bad"`))
|
||||
if res1.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for malformed json, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// Лишнее поле "age" (проверка DisallowUnknownFields)
|
||||
res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username":"valid_user","display_name":"User","age":25}`))
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for extra fields, got %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 3 тст на пустое сообщение и сообщение из одних пробелов -> 400 Invalid Request
|
||||
func TestEmptyMessageValidation(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("user_msg_test", "Tester")
|
||||
chat, _ := st.CreateChat("Test Chat", []string{u.ID})
|
||||
|
||||
// Пустой текст
|
||||
req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":""}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", u.ID)
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for empty text, got %d", res.StatusCode)
|
||||
}
|
||||
|
||||
// Текст только из пробелов
|
||||
reqSpaces, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":" "}`))
|
||||
reqSpaces.Header.Set("Content-Type", "application/json")
|
||||
reqSpaces.Header.Set("X-User-Id", u.ID)
|
||||
|
||||
resSpaces, _ := http.DefaultClient.Do(reqSpaces)
|
||||
if resSpaces.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for whitespace-only text, got %d", resSpaces.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 4 тест: чужой чат для постороннего -> 404 Not Found (не 403!)
|
||||
func TestOutsiderChatAccess(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
alice, _ := st.CreateUser("alice_secret", "Алиса")
|
||||
eve, _ := st.CreateUser("eve_eavesdropper", "Ева")
|
||||
|
||||
chat, _ := st.CreateChat("Секретный чат", []string{alice.ID})
|
||||
|
||||
// Ева пытается прочитать чат Алисы
|
||||
req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/chats/%s", ts.URL, chat.ID), nil)
|
||||
req.Header.Set("X-User-Id", eve.ID)
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
if res.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 Not Found (no leak via 403), got %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 5 Тест: пагинация по нескольким страницам с курсором
|
||||
func TestCursorPaginationMultiplePages(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("paging_user", "Пейджер")
|
||||
chat, _ := st.CreateChat("Чат пагинации", []string{u.ID})
|
||||
|
||||
// Отправляем 5 сообщений
|
||||
for i := 1; i <= 5; i++ {
|
||||
st.CreateMessage(chat.ID, u.ID, fmt.Sprintf("Message %d", i))
|
||||
}
|
||||
|
||||
// Запрашиваем порциями по limit=2
|
||||
var allReceived []string
|
||||
cursor := ""
|
||||
|
||||
for {
|
||||
url := fmt.Sprintf("%s/api/v1/chats/%s/messages?limit=2", ts.URL, chat.ID)
|
||||
if cursor != "" {
|
||||
url += "&cursor=" + cursor
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, url, nil)
|
||||
req.Header.Set("X-User-Id", u.ID)
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
|
||||
var page domain.MessagePage
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
json.Unmarshal(body, &page)
|
||||
res.Body.Close()
|
||||
|
||||
for _, m := range page.Items {
|
||||
allReceived = append(allReceived, m.Text)
|
||||
}
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
|
||||
if len(allReceived) != 5 {
|
||||
t.Fatalf("expected 5 messages total across pages, got %d", len(allReceived))
|
||||
}
|
||||
}
|
||||
|
||||
// 6 тест: 100 сообщений от 10 клиентов одновременно, защита от гонок
|
||||
func TestConcurrent100MessagesFrom10Clients(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
// Создаем 10 пользователей
|
||||
var memberIDs []string
|
||||
for i := 0; i < 10; i++ {
|
||||
u, _ := st.CreateUser(fmt.Sprintf("client_%d", i), fmt.Sprintf("Client %d", i))
|
||||
memberIDs = append(memberIDs, u.ID)
|
||||
}
|
||||
|
||||
chat, err := st.CreateChat("Highload Chat", memberIDs)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create chat: %v", err)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
totalClients := 10
|
||||
messagesPerClient := 10
|
||||
|
||||
for i := 0; i < totalClients; i++ {
|
||||
wg.Add(1)
|
||||
clientID := memberIDs[i]
|
||||
|
||||
go func(senderID string, clientIndex int) {
|
||||
defer wg.Done()
|
||||
|
||||
for m := 0; m < messagesPerClient; m++ {
|
||||
text := fmt.Sprintf("Client %d - Message %d", clientIndex, m)
|
||||
payload := fmt.Sprintf(`{"text":"%s"}`, text)
|
||||
|
||||
req, _ := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID),
|
||||
bytes.NewBufferString(payload),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", senderID)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil || res.StatusCode != http.StatusCreated {
|
||||
t.Errorf("failed to send concurrent message: %v", err)
|
||||
}
|
||||
if res != nil {
|
||||
res.Body.Close()
|
||||
}
|
||||
}
|
||||
}(clientID, i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// должно быть 100 сообщений в чате
|
||||
page, err := st.GetMessages(chat.ID, memberIDs[0], 200, "")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get messages: %v", err)
|
||||
}
|
||||
|
||||
if len(page.Items) != 100 {
|
||||
t.Fatalf("RACE CONDITION DETECTED: expected exactly 100 messages, got %d", len(page.Items))
|
||||
}
|
||||
|
||||
// уникальность ID
|
||||
seenIDs := make(map[string]bool)
|
||||
for _, m := range page.Items {
|
||||
if seenIDs[m.ID] {
|
||||
t.Fatalf("duplicate message ID found: %s", m.ID)
|
||||
}
|
||||
seenIDs[m.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
// 7 тест: защита от подделки курсора (чужой чат или битый Base64) -> 400
|
||||
func TestForeignAndMalformedCursor(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("cursor_tester", "Tester")
|
||||
chatA, _ := st.CreateChat("Chat A", []string{u.ID})
|
||||
chatB, _ := st.CreateChat("Chat B", []string{u.ID})
|
||||
|
||||
// В Чат А кладем несколько сообщений, чтобы при limit=1 появился NextCursor
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 1 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 2 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 3 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 4 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 5 in A")
|
||||
|
||||
st.CreateMessage(chatB.ID, u.ID, "Message 1 in B")
|
||||
st.CreateMessage(chatB.ID, u.ID, "Message 2 in B")
|
||||
|
||||
// Получаем валидный курсор из Чата А (запрашиваем 1 из 2)
|
||||
pageA, err := st.GetMessages(chatA.ID, u.ID, 1, "")
|
||||
if err != nil || pageA.NextCursor == nil {
|
||||
t.Fatalf("expected next_cursor in Chat A, err: %v", err)
|
||||
}
|
||||
|
||||
// 1. Пытаемся применить курсор от Чата А к Чату Б -> строго 400!
|
||||
urlForeign := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=%s", ts.URL, chatB.ID, *pageA.NextCursor)
|
||||
reqForeign, _ := http.NewRequest(http.MethodGet, urlForeign, nil)
|
||||
reqForeign.Header.Set("X-User-Id", u.ID)
|
||||
resForeign, _ := http.DefaultClient.Do(reqForeign)
|
||||
|
||||
if resForeign.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for foreign chat cursor, got %d", resForeign.StatusCode)
|
||||
}
|
||||
|
||||
// 2. Битый (невалидный) Base64 -> 400
|
||||
urlBad := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=not-a-valid-base64!@#", ts.URL, chatB.ID)
|
||||
reqBad, _ := http.NewRequest(http.MethodGet, urlBad, nil)
|
||||
reqBad.Header.Set("X-User-Id", u.ID)
|
||||
resBad, _ := http.DefaultClient.Do(reqBad)
|
||||
|
||||
if resBad.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for malformed cursor, got %d", resBad.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 8 тест валидации создания чата (создателя нет в списке / несуществующий юзер / дубликат) -> 400
|
||||
func TestChatCreationValidation(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
alice, _ := st.CreateUser("alice_chat_val", "Alice")
|
||||
bob, _ := st.CreateUser("bob_chat_val", "Bob")
|
||||
|
||||
// 1. Создатель (Alice) забыла добавить себя в member_ids
|
||||
bodyNoCaller := fmt.Sprintf(`{"title":"No Caller Chat","member_ids":["%s"]}`, bob.ID)
|
||||
req1, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyNoCaller))
|
||||
req1.Header.Set("Content-Type", "application/json")
|
||||
req1.Header.Set("X-User-Id", alice.ID)
|
||||
res1, _ := http.DefaultClient.Do(req1)
|
||||
if res1.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 when caller is not in member_ids, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// 2. В участниках передан несуществующий UUID
|
||||
bodyFakeUser := fmt.Sprintf(`{"title":"Fake User Chat","member_ids":["%s","00000000-0000-0000-0000-000000000000"]}`, alice.ID)
|
||||
req2, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyFakeUser))
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
req2.Header.Set("X-User-Id", alice.ID)
|
||||
res2, _ := http.DefaultClient.Do(req2)
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for non-existent member_id, got %d", res2.StatusCode)
|
||||
}
|
||||
|
||||
// 3. Дубликат участника в списке
|
||||
bodyDuplicate := fmt.Sprintf(`{"title":"Duplicate Member","member_ids":["%s","%s"]}`, alice.ID, alice.ID)
|
||||
req3, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyDuplicate))
|
||||
req3.Header.Set("Content-Type", "application/json")
|
||||
req3.Header.Set("X-User-Id", alice.ID)
|
||||
res3, _ := http.DefaultClient.Do(req3)
|
||||
if res3.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for duplicate member_ids, got %d", res3.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 9 тест лимитов символов Unicode (длина до 4000 рун и отказ при >4000)
|
||||
func TestUnicodeLimits(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("unicode_master", "Иван 🚀")
|
||||
chat, _ := st.CreateChat("Unicode Chat", []string{u.ID})
|
||||
|
||||
// Ровно 4000 смайликов (в байтах это 16000 байт, но в рунах — ровно 4000!)
|
||||
validRunes := make([]rune, 4000)
|
||||
for i := range validRunes {
|
||||
validRunes[i] = '🔥'
|
||||
}
|
||||
bodyValid := fmt.Sprintf(`{"text":"%s"}`, string(validRunes))
|
||||
req1, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyValid))
|
||||
req1.Header.Set("Content-Type", "application/json")
|
||||
req1.Header.Set("X-User-Id", u.ID)
|
||||
res1, _ := http.DefaultClient.Do(req1)
|
||||
if res1.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 201 for 4000 unicode runes, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// 4001 символ -> строго 400 Invalid Request!
|
||||
tooLongRunes := make([]rune, 4001)
|
||||
for i := range tooLongRunes {
|
||||
tooLongRunes[i] = 'a'
|
||||
}
|
||||
bodyTooLong := fmt.Sprintf(`{"text":"%s"}`, string(tooLongRunes))
|
||||
req2, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyTooLong))
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
req2.Header.Set("X-User-Id", u.ID)
|
||||
res2, _ := http.DefaultClient.Do(req2)
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for 4001 runes, got %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user