Files
mtusi2026lab6/app/internal/api/http/helpers_test.go
T

359 lines
9.6 KiB
Go

package http
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
)
type testRig struct {
t *testing.T
server *httptest.Server
srv *Server
memory *store.Memory
objects *objectstore.Memory
sessions session.Store
client *http.Client
mu sync.Mutex
tokens map[string]string
}
func newTestRig(t *testing.T) *testRig {
return newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: 1 << 20,
MaxInFlight: 256,
MaxMessagesGlobal: 100000,
MaxHeapBytes: 1 << 40,
})
}
func newTestRigWithLimits(t *testing.T, limits config.Limits) *testRig {
t.Helper()
return newRig(t, limits, session.NewMemory(), time.Hour)
}
const testInstanceID = "test-instance"
var defaultTestLimits = config.Limits{
MaxBodyBytes: 1 << 20,
MaxInFlight: 256,
MaxMessagesGlobal: 100000,
MaxHeapBytes: 1 << 40,
}
func newRig(t *testing.T, limits config.Limits, sessions session.Store, ttl time.Duration) *testRig {
t.Helper()
cfg := &config.Config{
Env: "test",
Version: "test",
InstanceID: testInstanceID,
HTTP: config.HTTP{
Addr: "127.0.0.1:0",
ReadTimeoutMs: 10000,
WriteTimeoutMs: 10000,
IdleTimeoutMs: 60000,
ShutdownTimeoutMs: 1000,
},
Limits: limits,
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
memory := store.NewWithLimit(limits.MaxMessagesGlobal)
hasher := password.NewHasher(testHashParams, 8)
auth, err := service.NewAuth(memory, sessions, hasher, ttl)
if err != nil {
t.Fatal(err)
}
objects := objectstore.NewMemory()
srv := NewServer(Deps{
Config: cfg,
Logger: logger,
Store: memory,
Auth: auth,
Users: service.NewUsers(memory, hasher),
Chats: service.NewChats(memory),
Messages: service.NewMessages(memory),
Attachments: service.NewAttachments(memory, objects, service.AttachmentLimits{
MaxUploadBytes: testMaxUploadBytes,
MaxImagePixels: testMaxImagePixels,
MaxConcurrentUploads: testMaxConcurrentUploads,
}, logger),
})
ts := httptest.NewServer(srv.e)
t.Cleanup(ts.Close)
return &testRig{
t: t,
server: ts,
srv: srv,
memory: memory,
objects: objects,
sessions: sessions,
client: &http.Client{Timeout: 10 * time.Second},
tokens: make(map[string]string),
}
}
type testUser struct {
ID string
Username string
DisplayName string
}
type errorResp struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
func (r *testRig) do(method, path string, actorID string, headers map[string]string, body io.Reader) *http.Response {
r.t.Helper()
req, err := http.NewRequest(method, r.server.URL+path, body)
if err != nil {
r.t.Fatalf("new request %s %s: %v", method, path, err)
}
req.Header.Set("Accept", "application/json")
r.setAuth(req, actorID)
if method == http.MethodPost && strings.HasSuffix(path, "/messages") {
req.Header.Set("Idempotency-Key", uuid.NewString())
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := r.client.Do(req)
if err != nil {
r.t.Fatalf("do %s %s: %v", method, path, err)
}
return resp
}
func (r *testRig) doJSON(method, path string, actorID string, payload any) *http.Response {
r.t.Helper()
var body io.Reader
if payload != nil {
body = bytes.NewReader(mustJSON(payload))
}
return r.do(method, path, actorID, map[string]string{"Content-Type": "application/json"}, body)
}
func readJSON(t *testing.T, resp *http.Response, dst any) {
t.Helper()
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if len(data) == 0 {
return
}
if err := json.Unmarshal(data, dst); err != nil {
t.Fatalf("decode body (%s): %v", string(data), err)
}
}
func readError(t *testing.T, resp *http.Response) errorResp {
t.Helper()
var e errorResp
readJSON(t, resp, &e)
return e
}
func expectStatus(t *testing.T, resp *http.Response, want int) {
t.Helper()
if resp.StatusCode != want {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("expected status %d, got %d; body=%s", want, resp.StatusCode, string(data))
}
}
const testPassword = "test-password-123"
var testHashParams = password.Params{MemoryKiB: 64, Iterations: 1, Parallelism: 1, SaltLen: 16, KeyLen: 32}
func (r *testRig) createUser(username, displayName string) testUser {
r.t.Helper()
resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
Username: username,
DisplayName: displayName,
Password: testPassword,
})
expectStatus(r.t, resp, http.StatusCreated)
var u dto.UserResponse
readJSON(r.t, resp, &u)
s := r.login(username, testPassword)
r.mu.Lock()
r.tokens[u.ID] = s.Token
r.mu.Unlock()
return testUser{ID: u.ID, Username: u.Username, DisplayName: u.DisplayName}
}
// login входит по Basic и возвращает сессию; ожидает 201.
func (r *testRig) login(username, pw string) dto.SessionResponse {
r.t.Helper()
resp := r.basicLogin(username, pw)
expectStatus(r.t, resp, http.StatusCreated)
var s dto.SessionResponse
readJSON(r.t, resp, &s)
return s
}
func (r *testRig) basicLogin(username, pw string) *http.Response {
r.t.Helper()
req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions", nil)
req.SetBasicAuth(username, pw)
resp, err := r.client.Do(req)
if err != nil {
r.t.Fatalf("login: %v", err)
}
return resp
}
func (r *testRig) setAuth(req *http.Request, actorID string) {
if actorID == "" {
return
}
r.mu.Lock()
tok, ok := r.tokens[strings.ToLower(actorID)]
r.mu.Unlock()
if !ok {
tok = "unknown-" + actorID
}
req.Header.Set("Authorization", "Bearer "+tok)
}
func (r *testRig) createChat(owner testUser, title string, members ...string) dto.ChatResponse {
r.t.Helper()
resp := r.doJSON(http.MethodPost, "/api/v1/chats", owner.ID, dto.CreateChatRequest{
Title: title,
MemberIDs: members,
})
expectStatus(r.t, resp, http.StatusCreated)
var ch dto.ChatResponse
readJSON(r.t, resp, &ch)
return ch
}
func (r *testRig) sendMessage(actor testUser, chatID, text string) (*http.Response, dto.MessageResponse) {
r.t.Helper()
resp := r.doJSON(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID, textMessage(text))
if resp.StatusCode != http.StatusCreated {
return resp, dto.MessageResponse{}
}
var m dto.MessageResponse
readJSON(r.t, resp, &m)
return resp, m
}
func (r *testRig) sendRaw(actor testUser, chatID string, body []byte) (int, dto.MessageResponse, []byte) {
r.t.Helper()
resp := r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID,
map[string]string{"Content-Type": "application/json"}, bytes.NewReader(body))
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusCreated {
return resp.StatusCode, dto.MessageResponse{}, data
}
var m dto.MessageResponse
if err := json.Unmarshal(data, &m); err != nil {
r.t.Fatalf("decode message: %v", err)
}
return resp.StatusCode, m, data
}
func (r *testRig) send(actor testUser, chatID, text string) (int, dto.MessageResponse) {
r.t.Helper()
status, msg, _ := r.sendRaw(actor, chatID, mustJSON(textMessage(text)))
return status, msg
}
func (r *testRig) listMessages(actor testUser, chatID string, pageSize int) ([]dto.MessageResponse, int) {
r.t.Helper()
collected := []dto.MessageResponse{}
cursor := ""
for pages := 1; ; pages++ {
q := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chatID, pageSize)
if cursor != "" {
q += "&cursor=" + url.QueryEscape(cursor)
}
resp := r.do(http.MethodGet, q, actor.ID, nil, nil)
expectStatus(r.t, resp, http.StatusOK)
var page dto.MessagesPageResponse
readJSON(r.t, resp, &page)
collected = append(collected, page.Items...)
if page.NextCursor == nil {
return collected, pages
}
cursor = *page.NextCursor
if pages > 100_000 {
r.t.Fatalf("пагинация не сходится: next_cursor не исчезает")
}
}
}
func bootstrap(r *testRig) (alice, bob, eve testUser, chat dto.ChatResponse) {
alice = r.createUser("own_alice_"+randomSuffix(), "Алиса")
bob = r.createUser("own_bob_"+randomSuffix(), "Боб")
eve = r.createUser("own_eve_"+randomSuffix(), "Ева")
chat = r.createChat(alice, "Контрактный тест", alice.ID, bob.ID)
return
}
var suffixMu sync.Mutex
var suffixSeq int
func randomSuffix() string {
suffixMu.Lock()
defer suffixMu.Unlock()
suffixSeq++
return fmt.Sprintf("%09d_%d", time.Now().UnixNano()%1_000_000_000, suffixSeq)
}
func mustJSON(v any) []byte {
data, err := json.Marshal(v)
if err != nil {
panic(err)
}
return data
}
func extractErrorCode(t *testing.T, data []byte) string {
t.Helper()
var e errorResp
if err := json.Unmarshal(data, &e); err != nil {
t.Fatalf("decode error body: %v; raw=%s", err, string(data))
}
return e.Error.Code
}
const (
testMaxUploadBytes = 2 << 20
testMaxImagePixels = 10_000
testMaxConcurrentUploads = 4
)
// textMessage — тело POST сообщения без вложений.
func textMessage(text string) map[string]string {
return map[string]string{"text": text}
}