Начало реализации сервиса.

This commit is contained in:
Grbisba
2026-10-30 12:25:56 +03:00
parent 65003b6119
commit 20f2f00a60
52 changed files with 4351 additions and 1 deletions
+239
View File
@@ -0,0 +1,239 @@
package tests
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
controller "gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http"
inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
)
type apiClient struct {
handler http.Handler
}
type apiResponse struct {
status int
requestID string
body []byte
}
func newAPI(t *testing.T) *apiClient {
t.Helper()
router := controller.NewRouter()
users := inmemory2.NewUserCache()
chats := inmemory2.NewChatCache(users)
messages := inmemory2.NewMessageCache(chats)
base := controller.NewBaseHandler(router)
controller.NewUserHandler(base, users).RegisterRoutes()
controller.NewChatHandler(base, users, chats, messages).RegisterRoutes()
return &apiClient{handler: router}
}
func (api *apiClient) request(t *testing.T, method, path, userID, body string) apiResponse {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
if userID != "" {
req.Header.Set("X-User-Id", userID)
}
recorder := httptest.NewRecorder()
api.handler.ServeHTTP(recorder, req)
resp := recorder.Result()
defer resp.Body.Close()
requestID := resp.Header.Get("X-Request-Id")
if requestID == "" {
t.Fatalf("%s %s: missing X-Request-Id", method, path)
}
return apiResponse{status: resp.StatusCode, requestID: requestID, body: recorder.Body.Bytes()}
}
func jsonString(t *testing.T, value any) string {
t.Helper()
data, err := json.Marshal(value)
if err != nil {
t.Fatalf("encode request: %v", err)
}
return string(data)
}
func decodeOK(t *testing.T, resp apiResponse, wantStatus int, target any) {
t.Helper()
if resp.status != wantStatus {
t.Fatalf("status = %d, want %d; body: %s", resp.status, wantStatus, resp.body)
}
if err := json.Unmarshal(resp.body, target); err != nil {
t.Fatalf("decode response %s: %v", resp.body, err)
}
}
func assertError(t *testing.T, resp apiResponse, wantStatus int, wantCode string) {
t.Helper()
if resp.status != wantStatus {
t.Fatalf("status = %d, want %d; body: %s", resp.status, wantStatus, resp.body)
}
var body struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
if err := json.Unmarshal(resp.body, &body); err != nil {
t.Fatalf("decode error response %s: %v", resp.body, err)
}
if body.Error.Code != wantCode || body.Error.Message == "" || body.Error.RequestID != resp.requestID {
t.Fatalf("invalid error response: header request ID %q, body %s", resp.requestID, resp.body)
}
}
func (api *apiClient) createUser(t *testing.T, username string) string {
t.Helper()
resp := api.request(t, http.MethodPost, "/api/v1/users", "", jsonString(t, map[string]string{
"username": username, "display_name": username,
}))
var user struct {
ID string `json:"id"`
}
decodeOK(t, resp, http.StatusCreated, &user)
if user.ID == "" {
t.Fatal("created user has no ID")
}
return user.ID
}
func (api *apiClient) createChat(t *testing.T, creatorID string, memberIDs ...string) string {
t.Helper()
resp := api.request(t, http.MethodPost, "/api/v1/chats", creatorID, jsonString(t, map[string]any{
"title": "Test chat", "member_ids": memberIDs,
}))
var chat struct {
ID string `json:"id"`
}
decodeOK(t, resp, http.StatusCreated, &chat)
if chat.ID == "" {
t.Fatal("created chat has no ID")
}
return chat.ID
}
func TestInvalidJSON(t *testing.T) {
api := newAPI(t)
for _, tc := range []struct {
name string
body string
}{
{name: "malformed", body: `{"username":`},
{name: "wrong type", body: `{"username":42,"display_name":"Alice"}`},
{name: "unknown field", body: `{"username":"alice","display_name":"Alice","admin":true}`},
} {
t.Run(tc.name, func(t *testing.T) {
resp := api.request(t, http.MethodPost, "/api/v1/users", "", tc.body)
assertError(t, resp, http.StatusBadRequest, "invalid_request")
})
}
}
func TestForeignChatIsHidden(t *testing.T) {
api := newAPI(t)
alice := api.createUser(t, "alice")
bob := api.createUser(t, "bob")
eve := api.createUser(t, "eve")
chatID := api.createChat(t, alice, alice, bob)
for _, tc := range []struct {
method string
path string
body string
}{
{method: http.MethodGet, path: "/api/v1/chats/" + chatID},
{method: http.MethodGet, path: "/api/v1/chats/" + chatID + "/messages"},
{method: http.MethodPost, path: "/api/v1/chats/" + chatID + "/messages", body: `{"text":"secret"}`},
} {
resp := api.request(t, tc.method, tc.path, eve, tc.body)
assertError(t, resp, http.StatusNotFound, "not_found")
}
}
func TestEmptyMessage(t *testing.T) {
api := newAPI(t)
alice := api.createUser(t, "alice")
chatID := api.createChat(t, alice, alice)
path := "/api/v1/chats/" + chatID + "/messages"
for _, body := range []string{`{"text":""}`, `{"text":" \t\n "}`} {
resp := api.request(t, http.MethodPost, path, alice, body)
assertError(t, resp, http.StatusBadRequest, "invalid_request")
}
}
func TestDuplicateUsername(t *testing.T) {
api := newAPI(t)
api.createUser(t, "alice")
resp := api.request(t, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Another Alice"}`)
assertError(t, resp, http.StatusConflict, "conflict")
}
func TestMessagePagination(t *testing.T) {
api := newAPI(t)
alice := api.createUser(t, "alice")
chatID := api.createChat(t, alice, alice)
wantIDs := make(map[string]bool)
for i := range 5 {
resp := api.request(t, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", alice,
jsonString(t, map[string]string{"text": fmt.Sprintf("message %d", i)}))
var message struct {
ID string `json:"id"`
}
decodeOK(t, resp, http.StatusCreated, &message)
if message.ID == "" || wantIDs[message.ID] {
t.Fatalf("invalid or duplicate created message ID %q", message.ID)
}
wantIDs[message.ID] = true
}
seen := make(map[string]bool)
cursor := ""
pages := 0
for {
path := "/api/v1/chats/" + chatID + "/messages?limit=2"
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
resp := api.request(t, http.MethodGet, path, alice, "")
var page struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
NextCursor *string `json:"next_cursor"`
}
decodeOK(t, resp, http.StatusOK, &page)
pages++
if pages > 3 || len(page.Items) == 0 || len(page.Items) > 2 {
t.Fatalf("unexpected page %d: %s", pages, resp.body)
}
for _, message := range page.Items {
if !wantIDs[message.ID] || seen[message.ID] {
t.Fatalf("unexpected or repeated message ID %q on page %d", message.ID, pages)
}
seen[message.ID] = true
}
if page.NextCursor == nil {
break
}
if *page.NextCursor == "" || *page.NextCursor == cursor {
t.Fatalf("invalid next cursor on page %d: %s", pages, resp.body)
}
cursor = *page.NextCursor
}
if pages != 3 || len(seen) != len(wantIDs) {
t.Fatalf("got %d pages and %d unique messages, want 3 pages and %d messages", pages, len(seen), len(wantIDs))
}
}
+162
View File
@@ -0,0 +1,162 @@
package tests
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
)
type createdMessage struct {
ID string `json:"id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
}
func postMessage(client *http.Client, endpoint, userID, text string) (createdMessage, error) {
body, err := json.Marshal(struct {
Text string `json:"text"`
}{Text: text})
if err != nil {
return createdMessage{}, err
}
req, err := http.NewRequest(http.MethodPost, endpoint, strings.NewReader(string(body)))
if err != nil {
return createdMessage{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User-Id", userID)
resp, err := client.Do(req)
if err != nil {
return createdMessage{}, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return createdMessage{}, err
}
if resp.StatusCode != http.StatusCreated {
return createdMessage{}, fmt.Errorf("POST status %d: %s", resp.StatusCode, data)
}
if resp.Header.Get("X-Request-Id") == "" {
return createdMessage{}, fmt.Errorf("POST response has no X-Request-Id")
}
var message createdMessage
if err := json.Unmarshal(data, &message); err != nil {
return createdMessage{}, fmt.Errorf("decode POST response: %w", err)
}
return message, nil
}
func TestConcurrentMessages(t *testing.T) {
const clients = 10
const messagesPerClient = 10
const total = clients * messagesPerClient
api := newAPI(t)
users := make([]string, clients)
for i := range users {
users[i] = api.createUser(t, fmt.Sprintf("user%02d", i))
}
chatID := api.createChat(t, users[0], users...)
server := httptest.NewServer(api.handler)
t.Cleanup(server.Close)
endpoint := server.URL + "/api/v1/chats/" + chatID + "/messages"
type result struct {
message createdMessage
wantSenderID string
wantText string
err error
}
results := make(chan result, total)
start := make(chan struct{})
var ready sync.WaitGroup
var workers sync.WaitGroup
ready.Add(clients)
workers.Add(clients)
for i, userID := range users {
go func(workerID int, userID string) {
defer workers.Done()
client := &http.Client{Timeout: 5 * time.Second}
defer client.CloseIdleConnections()
ready.Done()
<-start
for j := range messagesPerClient {
text := fmt.Sprintf("client-%02d-message-%02d", workerID, j)
message, err := postMessage(client, endpoint, userID, text)
results <- result{message: message, wantSenderID: userID, wantText: text, err: err}
}
}(i, userID)
}
ready.Wait()
close(start)
workers.Wait()
close(results)
created := make(map[string]createdMessage, total)
count := 0
for item := range results {
count++
if item.err != nil {
t.Errorf("send %q: %v", item.wantText, item.err)
continue
}
if item.message.ID == "" || item.message.SenderID != item.wantSenderID || item.message.Text != item.wantText {
t.Errorf("unexpected response for %q: %+v", item.wantText, item.message)
continue
}
if _, duplicate := created[item.message.ID]; duplicate {
t.Errorf("duplicate message ID %q", item.message.ID)
continue
}
created[item.message.ID] = item.message
}
if count != total || len(created) != total {
t.Fatalf("sent %d requests, created %d unique messages; want %d", count, len(created), total)
}
seen := make(map[string]bool, total)
cursor := ""
pages := 0
for {
path := "/api/v1/chats/" + chatID + "/messages?limit=17"
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
resp := api.request(t, http.MethodGet, path, users[0], "")
var page struct {
Items []createdMessage `json:"items"`
NextCursor *string `json:"next_cursor"`
}
decodeOK(t, resp, http.StatusOK, &page)
pages++
if pages > total || len(page.Items) == 0 || len(page.Items) > 17 {
t.Fatalf("unexpected page %d: %s", pages, resp.body)
}
for _, message := range page.Items {
want, exists := created[message.ID]
if !exists || seen[message.ID] || message != want {
t.Fatalf("unexpected or repeated message on page %d: %+v", pages, message)
}
seen[message.ID] = true
}
if page.NextCursor == nil {
break
}
if *page.NextCursor == "" || *page.NextCursor == cursor {
t.Fatalf("invalid cursor on page %d: %s", pages, resp.body)
}
cursor = *page.NextCursor
}
if len(seen) != total {
t.Fatalf("history has %d unique messages across %d pages; want %d", len(seen), pages, total)
}
t.Logf("%d clients sent %d messages; history contains %d unique messages across %d pages", clients, total, len(seen), pages)
}