forked from mtusi2026/mtusi2026lab2
368 lines
13 KiB
Go
368 lines
13 KiB
Go
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)
|
|
}
|
|
}
|