Files
mtusi2026lab2/internal/app/app_test.go
T

445 lines
17 KiB
Go

package app_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"sort"
"strings"
"sync"
"testing"
"messenger/internal/app"
"messenger/internal/chat"
"messenger/internal/platform/pagination"
"messenger/internal/testenv"
"messenger/internal/user"
)
var db *testenv.DB
func TestMain(m *testing.M) {
var err error
db, err = testenv.StartPostgres(context.Background())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
db.Close()
os.Exit(code)
}
const testPassword = "correct-horse-battery"
// errorBody mirrors the contract error envelope.
type errorBody struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
type response struct {
status int
requestID string
raw []byte
}
// tester drives the assembled application in-process.
type tester struct {
t *testing.T
a *app.App
}
// newTester assembles the application over an empty database.
func newTester(t *testing.T) *tester {
t.Helper()
db.Reset(t)
log := slog.New(slog.NewTextHandler(io.Discard, nil))
return &tester{t: t, a: app.New(app.Deps{Log: log, DB: db.Pool, MaxBodyBytes: 64 * 1024})}
}
// do sends one request. A string body is sent verbatim, anything else is
// JSON-encoded; both get a JSON content type. Every response is checked for
// X-Request-Id, and error bodies for the contract envelope.
func (ts *tester) do(method, path, actor string, body any, headers map[string]string) response {
ts.t.Helper()
req := httptest.NewRequest(method, path, encode(ts.t, body))
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if actor != "" {
req.Header.Set("X-User-Id", actor)
}
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
ts.a.Engine.ServeHTTP(rec, req)
res := response{status: rec.Code, requestID: rec.Header().Get("X-Request-Id"), raw: rec.Body.Bytes()}
if res.requestID == "" {
ts.t.Fatalf("%s %s: missing X-Request-Id", method, path)
}
if res.status >= 400 {
var eb errorBody
if err := json.Unmarshal(res.raw, &eb); err != nil {
ts.t.Fatalf("%s %s: error body is not the contract envelope: %v: %s", method, path, err, res.raw)
}
if eb.Error.RequestID != res.requestID || eb.Error.Code == "" || eb.Error.Message == "" {
ts.t.Fatalf("%s %s: bad error envelope: %s", method, path, res.raw)
}
}
return res
}
func encode(t *testing.T, body any) io.Reader {
t.Helper()
switch b := body.(type) {
case nil:
return nil
case string:
return strings.NewReader(b)
default:
raw, err := json.Marshal(b)
if err != nil {
t.Fatal(err)
}
return bytes.NewReader(raw)
}
}
// expect asserts the status and, for errors, the contract code.
func (ts *tester) expect(res response, status int, code string) {
ts.t.Helper()
if res.status != status {
ts.t.Fatalf("status = %d, want %d; body %s", res.status, status, res.raw)
}
if code != "" {
var eb errorBody
_ = json.Unmarshal(res.raw, &eb)
if eb.Error.Code != code {
ts.t.Fatalf("code = %q, want %q; body %s", eb.Error.Code, code, res.raw)
}
}
}
// decode parses a success body into a typed DTO and rejects unknown fields,
// which enforces the additionalProperties=false rule of the contract.
func decode[T any](t *testing.T, res response) T {
t.Helper()
var out T
dec := json.NewDecoder(bytes.NewReader(res.raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&out); err != nil {
t.Fatalf("body does not match %T: %v: %s", out, err, res.raw)
}
return out
}
func (ts *tester) user(username, display string) user.Response {
ts.t.Helper()
body := map[string]string{"username": username, "display_name": display, "password": testPassword}
res := ts.do(http.MethodPost, "/api/v1/users", "", body, nil)
ts.expect(res, http.StatusCreated, "")
return decode[user.Response](ts.t, res)
}
func (ts *tester) chat(actor, title string, members ...string) chat.ChatResponse {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats", actor, map[string]any{"title": title, "member_ids": members}, nil)
ts.expect(res, http.StatusCreated, "")
return decode[chat.ChatResponse](ts.t, res)
}
func (ts *tester) message(actor, chatID, text string) chat.MessageResponse {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor, map[string]string{"text": text}, nil)
ts.expect(res, http.StatusCreated, "")
return decode[chat.MessageResponse](ts.t, res)
}
func (ts *tester) chats(actor, query string) pagination.PageResponse[chat.ChatResponse] {
ts.t.Helper()
res := ts.do(http.MethodGet, "/api/v1/chats"+query, actor, nil, nil)
ts.expect(res, http.StatusOK, "")
return decode[pagination.PageResponse[chat.ChatResponse]](ts.t, res)
}
func (ts *tester) history(actor, chatID, query string) pagination.PageResponse[chat.MessageResponse] {
ts.t.Helper()
res := ts.do(http.MethodGet, "/api/v1/chats/"+chatID+"/messages"+query, actor, nil, nil)
ts.expect(res, http.StatusOK, "")
return decode[pagination.PageResponse[chat.MessageResponse]](ts.t, res)
}
func cursorQuery(limit int, cursor *string) string {
q := fmt.Sprintf("?limit=%d", limit)
if cursor != nil {
q += "&cursor=" + url.QueryEscape(*cursor)
}
return q
}
func TestHealthEndpoints(t *testing.T) {
ts := newTester(t)
for _, path := range []string{"/health/live", "/health/ready"} {
res := ts.do(http.MethodGet, path, "", nil, nil)
ts.expect(res, http.StatusOK, "")
if strings.TrimSpace(string(res.raw)) != `{"status":"ok"}` {
t.Fatalf("%s body = %s", path, res.raw)
}
}
ts.a.Health.SetReady(false)
ts.expect(ts.do(http.MethodGet, "/health/ready", "", nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/health/live", "", nil, nil), http.StatusOK, "")
}
func TestRegisterUserShapeAndConflicts(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "Алиса")
if alice.ID == "" || alice.Username != "alice" || alice.DisplayName != "Алиса" {
t.Fatalf("user = %+v", alice)
}
if !strings.HasSuffix(alice.CreatedAt, "Z") || len(alice.CreatedAt) != len("2026-09-01T12:00:00.000Z") {
t.Fatalf("created_at = %q", alice.CreatedAt)
}
post := func(body any) response { return ts.do(http.MethodPost, "/api/v1/users", "", body, nil) }
ts.expect(post(map[string]string{"username": "alice", "display_name": "Other", "password": testPassword}), http.StatusConflict, "conflict")
ts.expect(post(map[string]string{"username": "bob", "display_name": "Bob"}), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]string{"username": "Alice", "display_name": "x"}), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]string{"username": "bob", "display_name": " "}), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]any{"username": "bob", "display_name": "x", "password": "no"}), http.StatusBadRequest, "invalid_request")
ts.expect(post(`{"username":`), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]any{"username": 5, "display_name": "x"}), http.StatusBadRequest, "invalid_request")
}
func TestCurrentUserRequiresIdentity(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "Алиса")
me := func(actor string) response { return ts.do(http.MethodGet, "/api/v1/users/me", actor, nil, nil) }
ts.expect(me(""), http.StatusUnauthorized, "unauthorized")
ts.expect(me("garbage"), http.StatusUnauthorized, "unauthorized")
ts.expect(me("11111111-1111-4111-8111-111111111111"), http.StatusUnauthorized, "unauthorized")
res := me(alice.ID)
ts.expect(res, http.StatusOK, "")
if got := decode[user.Response](t, res); got != alice {
t.Fatalf("me = %+v, want %+v", got, alice)
}
}
func TestChatCreationRules(t *testing.T) {
ts := newTester(t)
alice, bob := ts.user("alice", "A"), ts.user("bob", "B")
created := ts.chat(alice.ID, "Проект по ВНП", alice.ID, bob.ID)
if created.Title != "Проект по ВНП" || len(created.MemberIDs) != 2 || created.MemberIDs[0] != alice.ID || created.MemberIDs[1] != bob.ID {
t.Fatalf("chat = %+v", created)
}
unknown := "22222222-2222-4222-8222-222222222222"
invalid := map[string]any{
"creator missing": map[string]any{"title": "t", "member_ids": []string{bob.ID}},
"duplicate": map[string]any{"title": "t", "member_ids": []string{alice.ID, alice.ID}},
"unknown member": map[string]any{"title": "t", "member_ids": []string{alice.ID, unknown}},
"malformed uuid": map[string]any{"title": "t", "member_ids": []string{alice.ID, "not-a-uuid"}},
"empty members": map[string]any{"title": "t", "member_ids": []string{}},
"blank title": map[string]any{"title": "", "member_ids": []string{alice.ID}},
"long title": map[string]any{"title": strings.Repeat("я", 101), "member_ids": []string{alice.ID}},
"missing members": map[string]any{"title": "t"},
"extra field": map[string]any{"title": "t", "member_ids": []string{alice.ID}, "owner": alice.ID},
}
for name, body := range invalid {
res := ts.do(http.MethodPost, "/api/v1/chats", alice.ID, body, nil)
if res.status != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400; body %s", name, res.status, res.raw)
}
}
ts.expect(ts.do(http.MethodPost, "/api/v1/chats", "", map[string]any{"title": "t", "member_ids": []string{alice.ID}}, nil), http.StatusUnauthorized, "unauthorized")
}
func TestChatVisibilityAndListing(t *testing.T) {
ts := newTester(t)
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
created := ts.chat(alice.ID, "Контрактный тест", alice.ID, bob.ID)
path := "/api/v1/chats/" + created.ID
res := ts.do(http.MethodGet, path, bob.ID, nil, nil)
ts.expect(res, http.StatusOK, "")
if got := decode[chat.ChatResponse](t, res); got.ID != created.ID || len(got.MemberIDs) != 2 {
t.Fatalf("GET chat = %+v", got)
}
ts.expect(ts.do(http.MethodGet, path, eve.ID, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/33333333-3333-4333-8333-333333333333", alice.ID, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/not-a-uuid", alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, path, "", nil, nil), http.StatusUnauthorized, "unauthorized")
listed := ts.chats(bob.ID, "?limit=100")
if len(listed.Items) != 1 || listed.Items[0].ID != created.ID || listed.NextCursor != nil {
t.Fatalf("bob list = %+v", listed)
}
hidden := ts.do(http.MethodGet, "/api/v1/chats?limit=100", eve.ID, nil, nil)
ts.expect(hidden, http.StatusOK, "")
if !strings.Contains(string(hidden.raw), `"items":[]`) || !strings.Contains(string(hidden.raw), `"next_cursor":null`) {
t.Fatalf("empty list must serialize items as [] and next_cursor as null: %s", hidden.raw)
}
}
func TestChatListPagination(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
var expected []string
for i := 0; i < 5; i++ {
expected = append(expected, ts.chat(alice.ID, fmt.Sprintf("chat %d", i), alice.ID).ID)
}
var walked []string
var cursor *string
for pages := 0; pages < 10; pages++ {
page := ts.chats(alice.ID, cursorQuery(2, cursor))
for _, c := range page.Items {
walked = append(walked, c.ID)
}
if page.NextCursor == nil {
break
}
cursor = page.NextCursor
}
if strings.Join(walked, ",") != strings.Join(expected, ",") {
t.Fatalf("walked %v, want %v", walked, expected)
}
bob := ts.user("bob", "B")
foreign := ts.chats(alice.ID, "?limit=1").NextCursor
ts.expect(ts.do(http.MethodGet, "/api/v1/chats"+cursorQuery(50, foreign), bob.ID, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?cursor=", alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?limit=abc", alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
}
func TestMessagesEndToEnd(t *testing.T) {
ts := newTester(t)
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
room := ts.chat(alice.ID, "Контрактный тест", alice.ID, bob.ID)
path := "/api/v1/chats/" + room.ID + "/messages"
first := ts.message(alice.ID, room.ID, "Привет, мир 👋")
second := ts.message(bob.ID, room.ID, "Сообщение Боба")
if first.SenderID != alice.ID || second.SenderID != bob.ID {
t.Fatalf("sender must come from X-User-Id: %+v %+v", first, second)
}
if first.ChatID != room.ID || first.Text != "Привет, мир 👋" {
t.Fatalf("message = %+v", first)
}
page1 := ts.history(bob.ID, room.ID, "?limit=1")
if len(page1.Items) != 1 || page1.NextCursor == nil || page1.Items[0] != first {
t.Fatalf("page1 = %+v", page1)
}
page2 := ts.history(alice.ID, room.ID, cursorQuery(1, page1.NextCursor))
if len(page2.Items) != 1 || page2.NextCursor != nil || page2.Items[0] != second {
t.Fatalf("page2 = %+v", page2)
}
post := func(actor string, body any) response { return ts.do(http.MethodPost, path, actor, body, nil) }
ts.expect(post(alice.ID, map[string]string{"text": ""}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.ID, map[string]string{"text": " "}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.ID, map[string]string{"text": strings.Repeat("я", 4001)}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.ID, map[string]string{"text": "x", "sender_id": bob.ID}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.ID, `{"text":`), http.StatusBadRequest, "invalid_request")
ts.expect(post(eve.ID, map[string]string{"text": "чужое"}), http.StatusNotFound, "not_found")
ts.expect(post(eve.ID, map[string]string{"text": ""}), http.StatusNotFound, "not_found")
ts.expect(post("", map[string]string{"text": "x"}), http.StatusUnauthorized, "unauthorized")
ts.expect(post(alice.ID, map[string]string{"text": strings.Repeat("я", 4000)}), http.StatusCreated, "")
get := func(actor, query string) response { return ts.do(http.MethodGet, path+query, actor, nil, nil) }
ts.expect(get(eve.ID, ""), http.StatusNotFound, "not_found")
ts.expect(get(alice.ID, "?limit=0"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.ID, "?limit=101"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.ID, "?cursor=garbage"), http.StatusBadRequest, "invalid_request")
other := ts.chat(alice.ID, "другой", alice.ID)
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/"+other.ID+"/messages"+cursorQuery(50, page1.NextCursor), alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
}
func TestMessageHistoryWalkAcrossPages(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.ID, "t", alice.ID)
var expected []string
for i := 0; i < 23; i++ {
expected = append(expected, ts.message(alice.ID, room.ID, fmt.Sprintf("m%d", i)).ID)
}
var walked []string
var cursor *string
for {
page := ts.history(alice.ID, room.ID, cursorQuery(5, cursor))
for _, m := range page.Items {
walked = append(walked, m.ID)
}
if page.NextCursor == nil {
break
}
cursor = page.NextCursor
}
if strings.Join(walked, ",") != strings.Join(expected, ",") {
t.Fatalf("walk mismatch:\n%v\n%v", walked, expected)
}
}
func TestConcurrentSendsProduceExactlyUniqueMessages(t *testing.T) {
ts := newTester(t)
const clients, perClient = 10, 10
members := make([]string, 0, clients)
for i := 0; i < clients; i++ {
members = append(members, ts.user(fmt.Sprintf("client_%d", i), "C").ID)
}
room := ts.chat(members[0], "нагрузка", members...)
var wg sync.WaitGroup
for n, actor := range members {
wg.Add(1)
go func(n int, actor string) {
defer wg.Done()
for i := 0; i < perClient; i++ {
res := ts.do(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", actor, map[string]string{"text": fmt.Sprintf("c%d-m%d", n, i)}, nil)
if res.status != http.StatusCreated {
t.Errorf("client %d: status %d body %s", n, res.status, res.raw)
}
}
}(n, actor)
}
wg.Wait()
page := ts.history(members[0], room.ID, "?limit=100")
if len(page.Items) != clients*perClient || page.NextCursor != nil {
t.Fatalf("got %d messages, next=%v; want %d and null", len(page.Items), page.NextCursor, clients*perClient)
}
ids := make([]string, 0, len(page.Items))
unique := make(map[string]struct{}, len(page.Items))
for _, m := range page.Items {
ids = append(ids, m.ID)
unique[m.ID] = struct{}{}
}
if !sort.StringsAreSorted(ids) {
t.Fatal("history is not ordered by id")
}
if len(unique) != clients*perClient {
t.Fatalf("%d unique ids, want %d", len(unique), clients*perClient)
}
}
func TestUnknownRouteAndMethodAreContractErrors(t *testing.T) {
ts := newTester(t)
ts.expect(ts.do(http.MethodGet, "/api/v1/nothing", "", nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodDelete, "/api/v1/users", "", nil, nil), http.StatusMethodNotAllowed, "invalid_request")
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", "{}", map[string]string{"Content-Type": "text/plain"}), http.StatusUnsupportedMediaType, "unsupported_media_type")
big := map[string]string{"username": "big", "display_name": strings.Repeat("x", 70*1024)}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", big, nil), http.StatusRequestEntityTooLarge, "payload_too_large")
}