Files
mtusi2026lab2/service/tests/api_test.go
T

240 lines
6.9 KiB
Go

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))
}
}