Files
mtusi2026lab2/internal/app/app_test.go
T

511 lines
19 KiB
Go

package app_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"sort"
"strings"
"sync"
"testing"
"time"
"messenger/internal/app"
"messenger/internal/chat"
"messenger/internal/platform/pagination"
"messenger/internal/testenv"
"messenger/internal/user"
)
var (
db *testenv.DB
kv *testenv.KV
)
func TestMain(m *testing.M) {
ctx := context.Background()
var err error
if db, err = testenv.StartPostgres(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if kv, err = testenv.StartValkey(ctx); err != nil {
db.Close()
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
kv.Close()
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
challenge string
raw []byte
}
// tester drives the assembled application in-process.
type tester struct {
t *testing.T
a *app.App
}
// account is a registered user with a live session.
type account struct {
user.Response
token string
}
// sessionBody mirrors the contract Session schema.
type sessionBody struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User user.Response `json:"user"`
}
func newTester(t *testing.T) *tester {
t.Helper()
return newTesterWithTTL(t, time.Hour)
}
// newTesterWithTTL assembles the application over empty stores.
func newTesterWithTTL(t *testing.T, ttl time.Duration) *tester {
t.Helper()
db.Reset(t)
kv.Reset(t)
log := slog.New(slog.NewTextHandler(io.Discard, nil))
return &tester{t: t, a: app.New(app.Deps{
Log: log,
DB: db.Pool,
Sessions: kv.Client,
SessionTTL: ttl,
MaxBodyBytes: 64 * 1024,
})}
}
// do sends one request, authenticated with the bearer token when it is set.
// 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, error
// bodies for the contract envelope, and every 401 for the challenge of the
// scheme the route expects.
func (ts *tester) do(method, path, token 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 token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
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"),
challenge: rec.Header().Get("WWW-Authenticate"),
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)
}
}
if res.status == http.StatusUnauthorized {
scheme := "Bearer "
if path == "/api/v1/auth/sessions" {
scheme = "Basic "
}
if !strings.HasPrefix(res.challenge, scheme) {
ts.t.Fatalf("%s %s: 401 challenge = %q, want scheme %q", method, path, res.challenge, scheme)
}
}
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
}
// user registers a user and logs it in.
func (ts *tester) user(username, display string) account {
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, "")
registered := decode[user.Response](ts.t, res)
return account{Response: registered, token: ts.login(username, testPassword).Token}
}
func basic(username, password string) map[string]string {
raw := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return map[string]string{"Authorization": "Basic " + raw}
}
func (ts *tester) login(username, password string) sessionBody {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic(username, password))
ts.expect(res, http.StatusCreated, "")
return decode[sessionBody](ts.t, res)
}
func (ts *tester) chat(token, title string, members ...string) chat.ChatResponse {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats", token, 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(token, chatID, text string) chat.MessageResponse {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", token, map[string]string{"text": text}, nil)
ts.expect(res, http.StatusCreated, "")
return decode[chat.MessageResponse](ts.t, res)
}
func (ts *tester) chats(token, query string) pagination.PageResponse[chat.ChatResponse] {
ts.t.Helper()
res := ts.do(http.MethodGet, "/api/v1/chats"+query, token, nil, nil)
ts.expect(res, http.StatusOK, "")
return decode[pagination.PageResponse[chat.ChatResponse]](ts.t, res)
}
func (ts *tester) history(token, chatID, query string) pagination.PageResponse[chat.MessageResponse] {
ts.t.Helper()
res := ts.do(http.MethodGet, "/api/v1/chats/"+chatID+"/messages"+query, token, 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 TestCurrentUserIsTheTokenOwner(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "Алиса")
ts.user("bob", "Боб")
res := ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil)
ts.expect(res, http.StatusOK, "")
if got := decode[user.Response](t, res); got != alice.Response {
t.Fatalf("me = %+v, want %+v", got, alice.Response)
}
}
func TestChatCreationRules(t *testing.T) {
ts := newTester(t)
alice, bob := ts.user("alice", "A"), ts.user("bob", "B")
created := ts.chat(alice.token, "Проект по ВНП", 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.token, 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.token, "Контрактный тест", alice.ID, bob.ID)
path := "/api/v1/chats/" + created.ID
res := ts.do(http.MethodGet, path, bob.token, 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.token, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/33333333-3333-4333-8333-333333333333", alice.token, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/not-a-uuid", alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, path, "", nil, nil), http.StatusUnauthorized, "unauthorized")
listed := ts.chats(bob.token, "?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.token, 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.token, fmt.Sprintf("chat %d", i), alice.ID).ID)
}
var walked []string
var cursor *string
for pages := 0; pages < 10; pages++ {
page := ts.chats(alice.token, 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.token, "?limit=1").NextCursor
ts.expect(ts.do(http.MethodGet, "/api/v1/chats"+cursorQuery(50, foreign), bob.token, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?cursor=", alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?limit=abc", alice.token, 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.token, "Контрактный тест", alice.ID, bob.ID)
path := "/api/v1/chats/" + room.ID + "/messages"
first := ts.message(alice.token, room.ID, "Привет, мир 👋")
second := ts.message(bob.token, 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.token, 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.token, 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.token, map[string]string{"text": ""}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": " "}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": strings.Repeat("я", 4001)}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": "x", "sender_id": bob.ID}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, `{"text":`), http.StatusBadRequest, "invalid_request")
ts.expect(post(eve.token, map[string]string{"text": "чужое"}), http.StatusNotFound, "not_found")
ts.expect(post(eve.token, map[string]string{"text": ""}), http.StatusNotFound, "not_found")
ts.expect(post("", map[string]string{"text": "x"}), http.StatusUnauthorized, "unauthorized")
ts.expect(post(alice.token, 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.token, ""), http.StatusNotFound, "not_found")
ts.expect(get(alice.token, "?limit=0"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.token, "?limit=101"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.token, "?cursor=garbage"), http.StatusBadRequest, "invalid_request")
other := ts.chat(alice.token, "другой", alice.ID)
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/"+other.ID+"/messages"+cursorQuery(50, page1.NextCursor), alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
}
func TestMessageHistoryWalkAcrossPages(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "t", alice.ID)
var expected []string
for i := 0; i < 23; i++ {
expected = append(expected, ts.message(alice.token, room.ID, fmt.Sprintf("m%d", i)).ID)
}
var walked []string
var cursor *string
for {
page := ts.history(alice.token, 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
clientsList := make([]account, 0, clients)
members := make([]string, 0, clients)
for i := 0; i < clients; i++ {
c := ts.user(fmt.Sprintf("client_%d", i), "C")
clientsList = append(clientsList, c)
members = append(members, c.ID)
}
room := ts.chat(clientsList[0].token, "нагрузка", members...)
var wg sync.WaitGroup
for n, c := range clientsList {
wg.Go(func() {
for i := 0; i < perClient; i++ {
res := ts.do(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", c.token, 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)
}
}
})
}
wg.Wait()
page := ts.history(clientsList[0].token, 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")
}