forked from mtusi2026/mtusi2026lab2
604 lines
19 KiB
Go
604 lines
19 KiB
Go
package student_tests
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"sort"
|
|
"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))
|
|
}
|
|
}
|
|
|
|
func TestChatCursorPaginationMultiplePages(t *testing.T) {
|
|
ts, st := setupTestServer()
|
|
defer ts.Close()
|
|
|
|
user, err := st.CreateUser("chat_paging_user", "Пейджер чатов")
|
|
if err != nil {
|
|
t.Fatalf("failed to create user: %v", err)
|
|
}
|
|
|
|
outsider, err := st.CreateUser("chat_paging_outsider", "Посторонний")
|
|
if err != nil {
|
|
t.Fatalf("failed to create outsider: %v", err)
|
|
}
|
|
|
|
createdChats := make([]domain.Chat, 0, 5)
|
|
|
|
for i := 1; i <= 5; i++ {
|
|
chat, createErr := st.CreateChat(
|
|
fmt.Sprintf("Chat %d", i),
|
|
[]string{user.ID},
|
|
)
|
|
if createErr != nil {
|
|
t.Fatalf("failed to create chat %d: %v", i, createErr)
|
|
}
|
|
|
|
createdChats = append(createdChats, chat)
|
|
|
|
// Чужой чат создаётся между доступными чатами и не должен
|
|
// влиять на размер страницы или next_cursor пользователя.
|
|
if i == 3 {
|
|
if _, createErr = st.CreateChat(
|
|
"Outsider chat",
|
|
[]string{outsider.ID},
|
|
); createErr != nil {
|
|
t.Fatalf("failed to create outsider chat: %v", createErr)
|
|
}
|
|
}
|
|
}
|
|
|
|
sort.Slice(createdChats, func(i, j int) bool {
|
|
if createdChats[i].CreatedAt.Equal(createdChats[j].CreatedAt) {
|
|
return createdChats[i].ID < createdChats[j].ID
|
|
}
|
|
|
|
return createdChats[i].CreatedAt.Before(createdChats[j].CreatedAt)
|
|
})
|
|
|
|
var receivedIDs []string
|
|
seenIDs := make(map[string]bool)
|
|
seenCursors := make(map[string]bool)
|
|
cursor := ""
|
|
finished := false
|
|
|
|
for pageNumber := 1; pageNumber <= 10; pageNumber++ {
|
|
requestURL := ts.URL + "/api/v1/chats?limit=2"
|
|
if cursor != "" {
|
|
requestURL += "&cursor=" + url.QueryEscape(cursor)
|
|
}
|
|
|
|
req, err := http.NewRequest(http.MethodGet, requestURL, nil)
|
|
if err != nil {
|
|
t.Fatalf("failed to create request: %v", err)
|
|
}
|
|
req.Header.Set("X-User-Id", user.ID)
|
|
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatalf("failed to list chats: %v", err)
|
|
}
|
|
|
|
var page domain.ChatPage
|
|
decodeErr := json.NewDecoder(res.Body).Decode(&page)
|
|
res.Body.Close()
|
|
|
|
if res.StatusCode != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d", res.StatusCode)
|
|
}
|
|
if decodeErr != nil {
|
|
t.Fatalf("failed to decode chat page: %v", decodeErr)
|
|
}
|
|
if len(page.Items) > 2 {
|
|
t.Fatalf("page contains %d chats with limit=2", len(page.Items))
|
|
}
|
|
|
|
for _, chat := range page.Items {
|
|
if seenIDs[chat.ID] {
|
|
t.Fatalf("chat %s was returned more than once", chat.ID)
|
|
}
|
|
|
|
seenIDs[chat.ID] = true
|
|
receivedIDs = append(receivedIDs, chat.ID)
|
|
}
|
|
|
|
if page.NextCursor == nil {
|
|
finished = true
|
|
break
|
|
}
|
|
|
|
if seenCursors[*page.NextCursor] {
|
|
t.Fatalf("cursor cycle detected")
|
|
}
|
|
|
|
seenCursors[*page.NextCursor] = true
|
|
cursor = *page.NextCursor
|
|
}
|
|
|
|
if !finished {
|
|
t.Fatal("chat pagination did not finish")
|
|
}
|
|
|
|
if len(receivedIDs) != len(createdChats) {
|
|
t.Fatalf(
|
|
"expected %d chats across all pages, got %d",
|
|
len(createdChats),
|
|
len(receivedIDs),
|
|
)
|
|
}
|
|
|
|
for i, chat := range createdChats {
|
|
if receivedIDs[i] != chat.ID {
|
|
t.Fatalf(
|
|
"chat order differs at position %d: expected %s, got %s",
|
|
i,
|
|
chat.ID,
|
|
receivedIDs[i],
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestChatCursorValidation(t *testing.T) {
|
|
ts, st := setupTestServer()
|
|
defer ts.Close()
|
|
|
|
alice, err := st.CreateUser("chat_cursor_alice", "Алиса")
|
|
if err != nil {
|
|
t.Fatalf("failed to create Alice: %v", err)
|
|
}
|
|
|
|
bob, err := st.CreateUser("chat_cursor_bob", "Боб")
|
|
if err != nil {
|
|
t.Fatalf("failed to create Bob: %v", err)
|
|
}
|
|
|
|
for i := 1; i <= 2; i++ {
|
|
if _, err = st.CreateChat(
|
|
fmt.Sprintf("Alice chat %d", i),
|
|
[]string{alice.ID},
|
|
); err != nil {
|
|
t.Fatalf("failed to create Alice chat: %v", err)
|
|
}
|
|
}
|
|
|
|
if _, err = st.CreateChat("Bob chat", []string{bob.ID}); err != nil {
|
|
t.Fatalf("failed to create Bob chat: %v", err)
|
|
}
|
|
|
|
firstRequest, err := http.NewRequest(
|
|
http.MethodGet,
|
|
ts.URL+"/api/v1/chats?limit=1",
|
|
nil,
|
|
)
|
|
if err != nil {
|
|
t.Fatalf("failed to create first request: %v", err)
|
|
}
|
|
firstRequest.Header.Set("X-User-Id", alice.ID)
|
|
|
|
firstResponse, err := http.DefaultClient.Do(firstRequest)
|
|
if err != nil {
|
|
t.Fatalf("failed to request first page: %v", err)
|
|
}
|
|
|
|
var firstPage domain.ChatPage
|
|
decodeErr := json.NewDecoder(firstResponse.Body).Decode(&firstPage)
|
|
firstResponse.Body.Close()
|
|
|
|
if firstResponse.StatusCode != http.StatusOK {
|
|
t.Fatalf("expected first page status 200, got %d", firstResponse.StatusCode)
|
|
}
|
|
if decodeErr != nil {
|
|
t.Fatalf("failed to decode first page: %v", decodeErr)
|
|
}
|
|
if firstPage.NextCursor == nil {
|
|
t.Fatal("expected next_cursor for Alice")
|
|
}
|
|
|
|
foreignRequest, err := http.NewRequest(
|
|
http.MethodGet,
|
|
ts.URL+"/api/v1/chats?limit=1&cursor="+
|
|
url.QueryEscape(*firstPage.NextCursor),
|
|
nil,
|
|
)
|
|
if err != nil {
|
|
t.Fatalf("failed to create foreign cursor request: %v", err)
|
|
}
|
|
foreignRequest.Header.Set("X-User-Id", bob.ID)
|
|
|
|
foreignResponse, err := http.DefaultClient.Do(foreignRequest)
|
|
if err != nil {
|
|
t.Fatalf("failed to send foreign cursor request: %v", err)
|
|
}
|
|
foreignResponse.Body.Close()
|
|
|
|
if foreignResponse.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf(
|
|
"expected 400 for another user's cursor, got %d",
|
|
foreignResponse.StatusCode,
|
|
)
|
|
}
|
|
|
|
malformedRequest, err := http.NewRequest(
|
|
http.MethodGet,
|
|
ts.URL+"/api/v1/chats?cursor=not-valid-base64!",
|
|
nil,
|
|
)
|
|
if err != nil {
|
|
t.Fatalf("failed to create malformed cursor request: %v", err)
|
|
}
|
|
malformedRequest.Header.Set("X-User-Id", alice.ID)
|
|
|
|
malformedResponse, err := http.DefaultClient.Do(malformedRequest)
|
|
if err != nil {
|
|
t.Fatalf("failed to send malformed cursor request: %v", err)
|
|
}
|
|
malformedResponse.Body.Close()
|
|
|
|
if malformedResponse.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf(
|
|
"expected 400 for malformed cursor, got %d",
|
|
malformedResponse.StatusCode,
|
|
)
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|