Перенес основы lab3 в lab4
This commit is contained in:
@@ -0,0 +1,502 @@
|
||||
package httpapi_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type chatTestClient struct {
|
||||
base string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newChatTestClient(t *testing.T) *chatTestClient {
|
||||
t.Helper()
|
||||
|
||||
server := httptest.NewServer(newAPI())
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client := server.Client()
|
||||
client.Timeout = 10 * time.Second
|
||||
|
||||
return &chatTestClient{
|
||||
base: server.URL,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *chatTestClient) call(
|
||||
method string,
|
||||
path string,
|
||||
actorID string,
|
||||
body any,
|
||||
wantStatus int,
|
||||
result any,
|
||||
) error {
|
||||
var encoded []byte
|
||||
var err error
|
||||
|
||||
if body != nil {
|
||||
encoded, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(
|
||||
method,
|
||||
c.base+path,
|
||||
bytes.NewReader(encoded),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if actorID != "" {
|
||||
req.Header.Set("X-User-Id", actorID)
|
||||
}
|
||||
|
||||
response, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if response.StatusCode != wantStatus {
|
||||
return fmt.Errorf(
|
||||
"%s %s: status=%d, want=%d, body=%s",
|
||||
method, path, response.StatusCode, wantStatus, data,
|
||||
)
|
||||
}
|
||||
|
||||
requestID := response.Header.Get("X-Request-Id")
|
||||
if requestID == "" {
|
||||
return fmt.Errorf("%s %s: missing request ID", method, path)
|
||||
}
|
||||
|
||||
if wantStatus >= 400 {
|
||||
var problem struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, &problem); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if problem.Error.Code == "" ||
|
||||
problem.Error.RequestID != requestID {
|
||||
return fmt.Errorf("invalid error response: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
if result != nil {
|
||||
return json.Unmarshal(data, result)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func mustCall(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
method string,
|
||||
path string,
|
||||
actorID string,
|
||||
body any,
|
||||
status int,
|
||||
result any,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
if err := c.call(method, path, actorID, body, status, result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func createTestUser(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
username string,
|
||||
) model.User {
|
||||
t.Helper()
|
||||
|
||||
var user model.User
|
||||
mustCall(
|
||||
t, c, http.MethodPost, "/api/v1/users", "",
|
||||
map[string]any{
|
||||
"username": username,
|
||||
"display_name": username,
|
||||
},
|
||||
http.StatusCreated, &user,
|
||||
)
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func createTestChat(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
actorID string,
|
||||
members []string,
|
||||
) model.Chat {
|
||||
t.Helper()
|
||||
|
||||
var chat model.Chat
|
||||
mustCall(
|
||||
t, c, http.MethodPost, "/api/v1/chats", actorID,
|
||||
map[string]any{
|
||||
"title": "Test chat",
|
||||
"member_ids": members,
|
||||
},
|
||||
http.StatusCreated, &chat,
|
||||
)
|
||||
|
||||
return chat
|
||||
}
|
||||
|
||||
func readAllMessages(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
actorID string,
|
||||
chatID string,
|
||||
limit int,
|
||||
) ([]model.Message, int) {
|
||||
t.Helper()
|
||||
|
||||
var messages []model.Message
|
||||
cursor := ""
|
||||
pages := 0
|
||||
seenCursors := make(map[string]bool)
|
||||
|
||||
for {
|
||||
path := fmt.Sprintf(
|
||||
"/api/v1/chats/%s/messages?limit=%d",
|
||||
chatID, limit,
|
||||
)
|
||||
|
||||
if cursor != "" {
|
||||
path += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
|
||||
var page service.Page[model.Message]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path, actorID,
|
||||
nil, http.StatusOK, &page,
|
||||
)
|
||||
|
||||
pages++
|
||||
|
||||
if page.Items == nil {
|
||||
t.Fatal("items must be an array, not null")
|
||||
}
|
||||
if len(page.Items) > limit {
|
||||
t.Fatal("page exceeds requested limit")
|
||||
}
|
||||
|
||||
messages = append(messages, page.Items...)
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = *page.NextCursor
|
||||
if cursor == "" || seenCursors[cursor] || pages > 100 {
|
||||
t.Fatal("invalid or repeating pagination cursor")
|
||||
}
|
||||
seenCursors[cursor] = true
|
||||
}
|
||||
|
||||
return messages, pages
|
||||
}
|
||||
|
||||
func TestChatAccessAndValidation(t *testing.T) {
|
||||
c := newChatTestClient(t)
|
||||
|
||||
alice := createTestUser(t, c, "alice")
|
||||
bob := createTestUser(t, c, "bob")
|
||||
eve := createTestUser(t, c, "eve")
|
||||
|
||||
chat := createTestChat(
|
||||
t, c, alice.ID, []string{alice.ID, bob.ID},
|
||||
)
|
||||
path := "/api/v1/chats/" + chat.ID
|
||||
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path, eve.ID,
|
||||
nil, http.StatusNotFound, nil,
|
||||
)
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path+"/messages", eve.ID,
|
||||
nil, http.StatusNotFound, nil,
|
||||
)
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path+"/messages", eve.ID,
|
||||
map[string]any{"text": "not allowed"},
|
||||
http.StatusNotFound, nil,
|
||||
)
|
||||
|
||||
var hidden service.Page[model.Chat]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, "/api/v1/chats", eve.ID,
|
||||
nil, http.StatusOK, &hidden,
|
||||
)
|
||||
if len(hidden.Items) != 0 {
|
||||
t.Fatal("outsider sees a private chat")
|
||||
}
|
||||
|
||||
for _, text := range []string{"", " \t\n"} {
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path+"/messages", alice.ID,
|
||||
map[string]any{"text": text},
|
||||
http.StatusBadRequest, nil,
|
||||
)
|
||||
}
|
||||
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path+"/messages", alice.ID,
|
||||
map[string]any{
|
||||
"text": "hello",
|
||||
"sender_id": bob.ID,
|
||||
},
|
||||
http.StatusBadRequest, nil,
|
||||
)
|
||||
|
||||
for _, members := range [][]string{
|
||||
{alice.ID, alice.ID},
|
||||
{bob.ID},
|
||||
{alice.ID, "00000000-0000-4000-8000-000000000000"},
|
||||
} {
|
||||
mustCall(
|
||||
t, c, http.MethodPost, "/api/v1/chats", alice.ID,
|
||||
map[string]any{
|
||||
"title": "Invalid chat",
|
||||
"member_ids": members,
|
||||
},
|
||||
http.StatusBadRequest, nil,
|
||||
)
|
||||
}
|
||||
|
||||
var chats service.Page[model.Chat]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, "/api/v1/chats", alice.ID,
|
||||
nil, http.StatusOK, &chats,
|
||||
)
|
||||
if len(chats.Items) != 1 {
|
||||
t.Fatalf("expected one chat, got %d", len(chats.Items))
|
||||
}
|
||||
|
||||
messages, _ := readAllMessages(t, c, alice.ID, chat.ID, 10)
|
||||
if len(messages) != 0 {
|
||||
t.Fatal("rejected messages were saved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagePagination(t *testing.T) {
|
||||
c := newChatTestClient(t)
|
||||
alice := createTestUser(t, c, "alice")
|
||||
|
||||
chat := createTestChat(t, c, alice.ID, []string{alice.ID})
|
||||
other := createTestChat(t, c, alice.ID, []string{alice.ID})
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
var sent []model.Message
|
||||
|
||||
for i := 0; i < 7; i++ {
|
||||
var message model.Message
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path, alice.ID,
|
||||
map[string]any{"text": fmt.Sprintf("Сообщение %d 👋", i)},
|
||||
http.StatusCreated, &message,
|
||||
)
|
||||
sent = append(sent, message)
|
||||
}
|
||||
|
||||
got, pages := readAllMessages(t, c, alice.ID, chat.ID, 2)
|
||||
|
||||
if len(got) != len(sent) || pages != 4 {
|
||||
t.Fatalf("got %d messages on %d pages", len(got), pages)
|
||||
}
|
||||
|
||||
for i := range sent {
|
||||
if got[i] != sent[i] {
|
||||
t.Fatalf("message %d differs or is out of order", i)
|
||||
}
|
||||
}
|
||||
|
||||
var first service.Page[model.Message]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path+"?limit=2", alice.ID,
|
||||
nil, http.StatusOK, &first,
|
||||
)
|
||||
|
||||
if first.NextCursor == nil {
|
||||
t.Fatal("expected next cursor")
|
||||
}
|
||||
|
||||
cursor := url.QueryEscape(*first.NextCursor)
|
||||
|
||||
var next service.Page[model.Message]
|
||||
mustCall(
|
||||
t, c, http.MethodGet,
|
||||
path+"?limit=3&cursor="+cursor, alice.ID,
|
||||
nil, http.StatusOK, &next,
|
||||
)
|
||||
|
||||
if len(next.Items) != 3 || next.Items[0].ID != sent[2].ID {
|
||||
t.Fatal("changing page size lost or repeated a message")
|
||||
}
|
||||
|
||||
mustCall(
|
||||
t, c, http.MethodGet,
|
||||
"/api/v1/chats/"+other.ID+"/messages?cursor="+cursor,
|
||||
alice.ID, nil, http.StatusBadRequest, nil,
|
||||
)
|
||||
|
||||
for _, query := range []string{
|
||||
"limit=0",
|
||||
"limit=101",
|
||||
"limit=abc",
|
||||
"cursor=invalid",
|
||||
} {
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path+"?"+query, alice.ID,
|
||||
nil, http.StatusBadRequest, nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessages100From10Clients(t *testing.T) {
|
||||
c := newChatTestClient(t)
|
||||
|
||||
const clients = 10
|
||||
const messagesPerClient = 10
|
||||
const total = clients * messagesPerClient
|
||||
|
||||
users := make([]model.User, clients)
|
||||
memberIDs := make([]string, clients)
|
||||
|
||||
for i := range users {
|
||||
users[i] = createTestUser(t, c, fmt.Sprintf("user_%02d", i))
|
||||
memberIDs[i] = users[i].ID
|
||||
}
|
||||
|
||||
chat := createTestChat(t, c, users[0].ID, memberIDs)
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
type outcome struct {
|
||||
message model.Message
|
||||
err error
|
||||
}
|
||||
|
||||
results := make(chan outcome, total)
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for clientIndex := 0; clientIndex < clients; clientIndex++ {
|
||||
wg.Add(1)
|
||||
|
||||
go func(index int) {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
|
||||
for j := 0; j < messagesPerClient; j++ {
|
||||
text := fmt.Sprintf("client-%d-message-%d", index, j)
|
||||
var message model.Message
|
||||
|
||||
err := c.call(
|
||||
http.MethodPost,
|
||||
path,
|
||||
users[index].ID,
|
||||
map[string]any{"text": text},
|
||||
http.StatusCreated,
|
||||
&message,
|
||||
)
|
||||
|
||||
if err == nil &&
|
||||
(message.SenderID != users[index].ID ||
|
||||
message.Text != text ||
|
||||
message.ChatID != chat.ID) {
|
||||
err = fmt.Errorf("incorrect message response")
|
||||
}
|
||||
|
||||
results <- outcome{message: message, err: err}
|
||||
}
|
||||
}(clientIndex)
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
expected := make(map[string]model.Message, total)
|
||||
|
||||
for result := range results {
|
||||
if result.err != nil {
|
||||
t.Errorf("send failed: %v", result.err)
|
||||
continue
|
||||
}
|
||||
|
||||
if _, exists := expected[result.message.ID]; exists {
|
||||
t.Errorf("duplicate response ID: %s", result.message.ID)
|
||||
}
|
||||
|
||||
expected[result.message.ID] = result.message
|
||||
}
|
||||
|
||||
if t.Failed() {
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
if len(expected) != total {
|
||||
t.Fatalf("expected %d unique responses, got %d", total, len(expected))
|
||||
}
|
||||
|
||||
history, pages := readAllMessages(
|
||||
t, c, users[0].ID, chat.ID, 17,
|
||||
)
|
||||
|
||||
if len(history) != total {
|
||||
t.Fatalf("expected %d stored messages, got %d", total, len(history))
|
||||
}
|
||||
|
||||
seen := make(map[string]bool, total)
|
||||
|
||||
for _, message := range history {
|
||||
if seen[message.ID] {
|
||||
t.Fatalf("duplicate history ID: %s", message.ID)
|
||||
}
|
||||
seen[message.ID] = true
|
||||
|
||||
want, exists := expected[message.ID]
|
||||
if !exists || want != message {
|
||||
t.Fatalf("missing or changed message: %s", message.ID)
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf(
|
||||
"clients=%d sent=%d unique_responses=%d stored=%d unique_stored=%d pages=%d",
|
||||
clients, total, len(expected), len(history), len(seen), pages,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user