forked from mtusi2026/mtusi2026lab3
Горизонтальное масштабирование за LB с общими сессиями Redis, X-Instance-Id, обязательным Idempotency-Key в PostgreSQL, сценариями failover/persistence и измерением цены масштабирования при фиксированном CPU/RAM бюджете.
654 lines
24 KiB
Go
654 lines
24 KiB
Go
// Собственные проверки lab3 (плюс регрессия lab2). Им нужен уже поднятый
|
||
// PostgreSQL и Redis (docker compose up / scripts/up.sh): контракт требует
|
||
// настоящую БД, а не sqlmock. HTTP бьём в httptest.Server поверх того же Store,
|
||
// что и реплики — идемпотентность и гонки видны без обхода LB.
|
||
//
|
||
// Каждый тест пишет в лог, что именно проверяет и какой статус получил.
|
||
package studenttests
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"encoding/base64"
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"os"
|
||
"strings"
|
||
"sync"
|
||
"testing"
|
||
"time"
|
||
|
||
"github.com/google/uuid"
|
||
|
||
"mtusi2026lab3/internal/api"
|
||
"mtusi2026lab3/internal/auth"
|
||
"mtusi2026lab3/internal/session"
|
||
"mtusi2026lab3/internal/store"
|
||
)
|
||
|
||
var (
|
||
sharedStore *store.Store
|
||
sharedSessions *session.Store
|
||
sharedRedisURL string
|
||
)
|
||
|
||
func TestMain(m *testing.M) {
|
||
ctx := context.Background()
|
||
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||
sharedRedisURL = getenv("REDIS_URL", "redis://127.0.0.1:6379/0")
|
||
hasher, err := auth.NewHasher()
|
||
if err != nil {
|
||
fmt.Fprintln(os.Stderr, "hasher:", err)
|
||
os.Exit(1)
|
||
}
|
||
sharedStore, err = store.Open(ctx, dsn, hasher, 5)
|
||
if err != nil {
|
||
fmt.Fprintln(os.Stderr, "postgres:", err)
|
||
fmt.Fprintln(os.Stderr, "подсказка: docker compose --env-file .env up -d --build")
|
||
os.Exit(1)
|
||
}
|
||
defer sharedStore.Close()
|
||
if err := sharedStore.Migrate(ctx); err != nil {
|
||
fmt.Fprintln(os.Stderr, "migrate:", err)
|
||
os.Exit(1)
|
||
}
|
||
// Повтор миграции не должен падать и не должен дублировать данные.
|
||
if err := sharedStore.Migrate(ctx); err != nil {
|
||
fmt.Fprintln(os.Stderr, "migrate second:", err)
|
||
os.Exit(1)
|
||
}
|
||
sharedSessions, err = session.Open(sharedRedisURL, time.Hour)
|
||
if err != nil {
|
||
fmt.Fprintln(os.Stderr, "redis:", err)
|
||
os.Exit(1)
|
||
}
|
||
defer sharedSessions.Close()
|
||
os.Exit(m.Run())
|
||
}
|
||
|
||
func TestMalformedJSONAndValidation(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
logStep(t, "битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат")
|
||
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, "{")
|
||
logResult(t, status, body)
|
||
if status != http.StatusBadRequest || !strings.Contains(body, "invalid_request") {
|
||
t.Fatalf("malformed json: status=%d body=%s", status, body)
|
||
}
|
||
|
||
status, body = do(t, srv, http.MethodPost, "/api/v1/users", nil,
|
||
`{"username":"abc","display_name":"Имя","password":"correct-horse-1","extra":1}`)
|
||
logResult(t, status, body)
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("extra field: status=%d", status)
|
||
}
|
||
|
||
user := register(t, srv, "ok_user")
|
||
token := login(t, srv, user.username, user.password)
|
||
chat := createChat(t, srv, token, user.id, "Чат проверки")
|
||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||
|
||
// Decoder.More() это не ловит: один объект декодируется, лишняя скобка остаётся.
|
||
for _, raw := range []string{`{"text":"valid"}}`, `{"text":"valid"}]`} {
|
||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, raw)
|
||
logResult(t, status, body)
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("trailing garbage %q: status=%d body=%s", raw, status, body)
|
||
}
|
||
}
|
||
|
||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":" "}`)
|
||
logResult(t, status, body)
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("blank message: status=%d", status)
|
||
}
|
||
|
||
outsider := register(t, srv, "outsider")
|
||
outTok := login(t, srv, outsider.username, outsider.password)
|
||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{"Authorization": "Bearer " + outTok}, `{"text":"чужое"}`)
|
||
logResult(t, status, body)
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("foreign chat: status=%d body=%s", status, body)
|
||
}
|
||
logOK(t, "валидация JSON, хвоста, пустого текста и чужого чата")
|
||
}
|
||
|
||
func TestMessageTextPreservedAndLengthOnOriginal(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
logStep(t, "пробелы по краям сохраняются; длина считается по исходному тексту")
|
||
user := register(t, srv, "text_user")
|
||
token := login(t, srv, user.username, user.password)
|
||
chat := createChat(t, srv, token, user.id, "Текст")
|
||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||
|
||
original := " строка\nс пробелами "
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||
fmt.Sprintf(`{"text":%q}`, original))
|
||
logResult(t, status, body)
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("preserve spaces: status=%d", status)
|
||
}
|
||
got := decode(t, body)
|
||
if got["text"] != original {
|
||
t.Fatalf("text mutated: got %q want %q", got["text"], original)
|
||
}
|
||
|
||
tooLong := " " + strings.Repeat("a", 4000) // 4001 code points
|
||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||
fmt.Sprintf(`{"text":%q}`, tooLong))
|
||
logResult(t, status, body)
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("length after trim bypass: status=%d body=%s", status, body)
|
||
}
|
||
logOK(t, "текст сохранён целиком, обход лимита через TrimSpace закрыт")
|
||
}
|
||
|
||
func TestSessionRejectsJSONBody(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
logStep(t, "POST /auth/sessions с телом должен быть 400 даже при верном Basic")
|
||
user := register(t, srv, "body_user")
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||
"Authorization": "Basic " + basic(user.username, user.password),
|
||
}, `{"extra":1}`)
|
||
logResult(t, status, body)
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("session with body: status=%d body=%s", status, body)
|
||
}
|
||
logOK(t, "вход без JSON body")
|
||
}
|
||
|
||
func TestWrongPasswordLogoutAndIgnoredUserHeader(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
logStep(t, "неверный пароль, Basic на бизнес-методе, X-User-Id, logout")
|
||
user := register(t, srv, "auth_user")
|
||
other := register(t, srv, "auth_other")
|
||
|
||
status, body, hdr := doRaw(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||
"Authorization": "Basic " + basic(user.username, "wrong-password-1"),
|
||
}, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Basic") {
|
||
t.Fatalf("wrong password: status=%d www=%q", status, hdr.Get("WWW-Authenticate"))
|
||
}
|
||
|
||
token := login(t, srv, user.username, user.password)
|
||
status, body, hdr = doRaw(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||
"Authorization": "Basic " + basic(user.username, user.password),
|
||
}, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Bearer") {
|
||
t.Fatalf("basic on business endpoint: status=%d www=%q", status, hdr.Get("WWW-Authenticate"))
|
||
}
|
||
|
||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"X-User-Id": user.id}, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusUnauthorized {
|
||
t.Fatalf("X-User-Id alone: status=%d", status)
|
||
}
|
||
|
||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||
"Authorization": "Bearer " + token,
|
||
"X-User-Id": other.id,
|
||
}, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusOK || !strings.Contains(body, user.id) || strings.Contains(body, other.id) {
|
||
t.Fatalf("X-User-Id overrode bearer: status=%d body=%s", status, body)
|
||
}
|
||
|
||
status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "")
|
||
t.Logf("logout status=%d", status)
|
||
if status != http.StatusNoContent {
|
||
t.Fatalf("logout status=%d", status)
|
||
}
|
||
status, _ = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "")
|
||
if status != http.StatusUnauthorized {
|
||
t.Fatalf("token still valid after logout: %d", status)
|
||
}
|
||
status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "")
|
||
if status != http.StatusUnauthorized {
|
||
t.Fatalf("second logout status=%d", status)
|
||
}
|
||
logOK(t, "пароль, заголовки и отзыв сессии")
|
||
}
|
||
|
||
func TestSessionExpiry(t *testing.T) {
|
||
srv := newAPI(t, 2*time.Second)
|
||
defer srv.Close()
|
||
logStep(t, "SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается")
|
||
user := register(t, srv, "ttl_user")
|
||
token := login(t, srv, user.username, user.password)
|
||
time.Sleep(2500 * time.Millisecond)
|
||
status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusUnauthorized {
|
||
t.Fatalf("expired token status=%d body=%s", status, body)
|
||
}
|
||
logOK(t, "истёкшая сессия отклонена")
|
||
}
|
||
|
||
func TestDuplicateUsernameRace(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
name := "race_" + uuid.NewString()[:8]
|
||
logStep(t, "8 параллельных регистраций username="+name)
|
||
const n = 8
|
||
codes := make([]int, n)
|
||
var wg sync.WaitGroup
|
||
body := fmt.Sprintf(`{"username":%q,"display_name":"Гонка","password":"correct-horse-1"}`, name)
|
||
for i := 0; i < n; i++ {
|
||
wg.Add(1)
|
||
go func(i int) {
|
||
defer wg.Done()
|
||
status, _ := do(t, srv, http.MethodPost, "/api/v1/users", nil, body)
|
||
codes[i] = status
|
||
}(i)
|
||
}
|
||
wg.Wait()
|
||
ok, conflict := 0, 0
|
||
for _, c := range codes {
|
||
switch c {
|
||
case http.StatusCreated:
|
||
ok++
|
||
case http.StatusConflict:
|
||
conflict++
|
||
default:
|
||
t.Errorf("unexpected status %d", c)
|
||
}
|
||
}
|
||
t.Logf("created=%d conflict=%d", ok, conflict)
|
||
if ok != 1 || conflict != n-1 {
|
||
t.Fatalf("race result created=%d conflict=%d", ok, conflict)
|
||
}
|
||
logOK(t, "UNIQUE username выдержал гонку")
|
||
}
|
||
|
||
func TestChatCreateRollsBack(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
user := register(t, srv, "roll_user")
|
||
token := login(t, srv, user.username, user.password)
|
||
title := "rollback-" + uuid.NewString()
|
||
missing := uuid.NewString()
|
||
logStep(t, "создание чата с несуществующим участником должно откатиться, title="+title)
|
||
raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q,%q]}`, title, user.id, missing)
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw)
|
||
logResult(t, status, body)
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("status=%d", status)
|
||
}
|
||
n, err := sharedStore.CountChatsByTitle(context.Background(), title)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
t.Logf("строк chats с этим title после ошибки: %d", n)
|
||
if n != 0 {
|
||
t.Fatalf("chat row survived rollback: %d", n)
|
||
}
|
||
logOK(t, "транзакция создания чата откатилась")
|
||
}
|
||
|
||
func TestPaginationPages(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
logStep(t, "три сообщения, две страницы limit=2, затем последняя")
|
||
user := register(t, srv, "page_user")
|
||
token := login(t, srv, user.username, user.password)
|
||
chat := createChat(t, srv, token, user.id, "Страницы")
|
||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||
for _, text := range []string{"раз", "два", "три"} {
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, fmt.Sprintf(`{"text":%q}`, text))
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("post message %s: %d %s", text, status, body)
|
||
}
|
||
}
|
||
status, body := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2", auth, "")
|
||
logResult(t, status, body)
|
||
page := decode(t, body)
|
||
items, _ := page["items"].([]any)
|
||
if status != http.StatusOK || len(items) != 2 || page["next_cursor"] == nil {
|
||
t.Fatalf("page1: %+v", page)
|
||
}
|
||
cursor, _ := page["next_cursor"].(string)
|
||
status, body = do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2&cursor="+cursor, auth, "")
|
||
logResult(t, status, body)
|
||
page = decode(t, body)
|
||
items, _ = page["items"].([]any)
|
||
if len(items) != 1 || page["next_cursor"] != nil {
|
||
t.Fatalf("page2: %+v", page)
|
||
}
|
||
logOK(t, "keyset обошёл историю без зависания cursor")
|
||
}
|
||
|
||
func TestRedisDownIsNotAnonymous(t *testing.T) {
|
||
logStep(t, "закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима")
|
||
closed, err := session.Open(sharedRedisURL, time.Hour)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := closed.Close(); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
srv := httptest.NewServer(api.New(sharedStore, closed, "test-closed-redis").Handler())
|
||
defer srv.Close()
|
||
regSrv := newAPI(t, time.Hour)
|
||
defer regSrv.Close()
|
||
user := register(t, regSrv, "redis_down")
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||
"Authorization": "Basic " + basic(user.username, user.password),
|
||
}, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusServiceUnavailable {
|
||
t.Fatalf("login with dead redis: status=%d body=%s", status, body)
|
||
}
|
||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||
"Authorization": "Bearer " + strings.Repeat("ab", 32),
|
||
}, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusServiceUnavailable {
|
||
t.Fatalf("bearer with dead redis: status=%d body=%s", status, body)
|
||
}
|
||
logOK(t, "сбой Redis не стал анонимным доступом")
|
||
}
|
||
|
||
func TestPostgresDownIsNotAnonymous(t *testing.T) {
|
||
logStep(t, "закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя")
|
||
regSrv := newAPI(t, time.Hour)
|
||
defer regSrv.Close()
|
||
user := register(t, regSrv, "pg_down")
|
||
token := login(t, regSrv, user.username, user.password)
|
||
|
||
hasher, err := auth.NewHasher()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||
broken, err := store.Open(context.Background(), dsn, hasher, 5)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
broken.Close()
|
||
sessions, err := session.Open(sharedRedisURL, time.Hour)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
t.Cleanup(func() { _ = sessions.Close() })
|
||
srv := httptest.NewServer(api.New(broken, sessions, "test-broken-pg").Handler())
|
||
defer srv.Close()
|
||
|
||
status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusServiceUnavailable {
|
||
t.Fatalf("ready with dead postgres: %d", status)
|
||
}
|
||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||
"Authorization": "Bearer " + token,
|
||
}, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusServiceUnavailable || strings.Contains(body, `"username"`) {
|
||
t.Fatalf("me with dead postgres: status=%d body=%s", status, body)
|
||
}
|
||
status, body = do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||
"Authorization": "Basic " + basic(user.username, user.password),
|
||
}, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusServiceUnavailable {
|
||
t.Fatalf("login with dead postgres: status=%d body=%s", status, body)
|
||
}
|
||
logOK(t, "сбой PostgreSQL не стал анонимным доступом")
|
||
}
|
||
|
||
|
||
func TestIdempotencyReplayAndConflict(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
logStep(t, "повтор того же Idempotency-Key возвращает то же сообщение; другой body — 409")
|
||
user := register(t, srv, "idem_user")
|
||
token := login(t, srv, user.username, user.password)
|
||
chat := createChat(t, srv, token, user.id, "Идемпотентность")
|
||
key := "key-" + uuid.NewString()
|
||
auth := map[string]string{
|
||
"Authorization": "Bearer " + token,
|
||
"Idempotency-Key": key,
|
||
}
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"один раз"}`)
|
||
logResult(t, status, body)
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("first: %d %s", status, body)
|
||
}
|
||
first := decode(t, body)
|
||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"один раз"}`)
|
||
logResult(t, status, body)
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("replay: %d %s", status, body)
|
||
}
|
||
second := decode(t, body)
|
||
if first["id"] != second["id"] || first["text"] != second["text"] {
|
||
t.Fatalf("replay differs: first=%v second=%v", first, second)
|
||
}
|
||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"другой body"}`)
|
||
logResult(t, status, body)
|
||
if status != http.StatusConflict {
|
||
t.Fatalf("conflict: %d %s", status, body)
|
||
}
|
||
logOK(t, "replay и conflict по Idempotency-Key")
|
||
}
|
||
|
||
func TestIdempotencyKeyRequiredAndConcurrent(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
logStep(t, "нет ключа → 400; 8 параллельных POST с одним ключом → ровно одно сообщение")
|
||
user := register(t, srv, "idem_race")
|
||
token := login(t, srv, user.username, user.password)
|
||
chat := createChat(t, srv, token, user.id, "Гонка ключа")
|
||
|
||
// Явно без ключа: хелпер doRaw подставляет ключ только если заголовок пуст —
|
||
// поэтому бьём в doRaw с пустым Idempotency-Key, переопределив после...
|
||
// Проще: отдельный raw-запрос.
|
||
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/chats/"+chat+"/messages", strings.NewReader(`{"text":"без ключа"}`))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
req.Header.Set("Authorization", "Bearer "+token)
|
||
req.Header.Set("Content-Type", "application/json")
|
||
resp, err := http.DefaultClient.Do(req)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
b, _ := io.ReadAll(resp.Body)
|
||
resp.Body.Close()
|
||
logResult(t, resp.StatusCode, string(b))
|
||
if resp.StatusCode != http.StatusBadRequest {
|
||
t.Fatalf("missing key: %d", resp.StatusCode)
|
||
}
|
||
|
||
key := "race-" + uuid.NewString()
|
||
const n = 8
|
||
ids := make([]string, n)
|
||
var wg sync.WaitGroup
|
||
for i := 0; i < n; i++ {
|
||
wg.Add(1)
|
||
go func(i int) {
|
||
defer wg.Done()
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{
|
||
"Authorization": "Bearer " + token,
|
||
"Idempotency-Key": key,
|
||
}, `{"text":"параллельно"}`)
|
||
if status != http.StatusCreated {
|
||
t.Errorf("worker %d status=%d body=%s", i, status, body)
|
||
return
|
||
}
|
||
ids[i] = decode(t, body)["id"].(string)
|
||
}(i)
|
||
}
|
||
wg.Wait()
|
||
uniq := map[string]struct{}{}
|
||
for _, id := range ids {
|
||
if id == "" {
|
||
t.Fatalf("empty id in race")
|
||
}
|
||
uniq[id] = struct{}{}
|
||
}
|
||
t.Logf("unique message ids=%d", len(uniq))
|
||
if len(uniq) != 1 {
|
||
t.Fatalf("expected 1 message, got %d ids=%v", len(uniq), ids)
|
||
}
|
||
logOK(t, "ключ обязателен; конкурентный повтор не плодит дубли")
|
||
}
|
||
|
||
func TestInstanceIDHeaderPresent(t *testing.T) {
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
logStep(t, "каждый ответ содержит непустой X-Instance-Id")
|
||
status, body, hdr := doRaw(t, srv, http.MethodGet, "/health/live", nil, "")
|
||
logResult(t, status, body)
|
||
if status != http.StatusOK || hdr.Get("X-Instance-Id") == "" {
|
||
t.Fatalf("live instance header missing: %q status=%d", hdr.Get("X-Instance-Id"), status)
|
||
}
|
||
logOK(t, "X-Instance-Id="+hdr.Get("X-Instance-Id"))
|
||
}
|
||
|
||
type account struct {
|
||
id string
|
||
username string
|
||
password string
|
||
}
|
||
|
||
func newAPI(t *testing.T, ttl time.Duration) *httptest.Server {
|
||
t.Helper()
|
||
sessions, err := session.Open(sharedRedisURL, ttl)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
t.Cleanup(func() { _ = sessions.Close() })
|
||
return httptest.NewServer(api.New(sharedStore, sessions, "test-instance").Handler())
|
||
}
|
||
|
||
func register(t *testing.T, srv *httptest.Server, prefix string) account {
|
||
t.Helper()
|
||
username := prefix + "_" + uuid.NewString()[:8]
|
||
password := "correct-horse-1"
|
||
raw := fmt.Sprintf(`{"username":%q,"display_name":"Студент","password":%q}`, username, password)
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, raw)
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("register %s: %d %s", username, status, body)
|
||
}
|
||
var u struct {
|
||
ID string `json:"id"`
|
||
}
|
||
if err := json.Unmarshal([]byte(body), &u); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
t.Logf("создан %s id=%s", username, u.ID)
|
||
return account{id: u.ID, username: username, password: password}
|
||
}
|
||
|
||
func login(t *testing.T, srv *httptest.Server, username, password string) string {
|
||
t.Helper()
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||
"Authorization": "Basic " + basic(username, password),
|
||
}, "")
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("login %s: %d %s", username, status, body)
|
||
}
|
||
var s struct {
|
||
Token string `json:"token"`
|
||
}
|
||
if err := json.Unmarshal([]byte(body), &s); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if len(s.Token) < 32 {
|
||
t.Fatalf("token too short: %d", len(s.Token))
|
||
}
|
||
t.Logf("сессия выпущена, длина токена=%d (значение не печатаем)", len(s.Token))
|
||
return s.Token
|
||
}
|
||
|
||
func createChat(t *testing.T, srv *httptest.Server, token, userID, title string) string {
|
||
t.Helper()
|
||
raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q]}`, title, userID)
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw)
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("chat: %d %s", status, body)
|
||
}
|
||
var c struct {
|
||
ID string `json:"id"`
|
||
}
|
||
if err := json.Unmarshal([]byte(body), &c); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
return c.ID
|
||
}
|
||
|
||
func do(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string) {
|
||
t.Helper()
|
||
status, body, _ := doRaw(t, srv, method, path, headers, raw)
|
||
return status, body
|
||
}
|
||
|
||
func doRaw(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string, http.Header) {
|
||
t.Helper()
|
||
var rdr io.Reader
|
||
if raw != "" {
|
||
rdr = bytes.NewBufferString(raw)
|
||
}
|
||
req, err := http.NewRequest(method, srv.URL+path, rdr)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if raw != "" && method != http.MethodGet {
|
||
req.Header.Set("Content-Type", "application/json")
|
||
}
|
||
for k, v := range headers {
|
||
req.Header.Set(k, v)
|
||
}
|
||
// Lab3: POST сообщений без ключа — 400. В хелперах подставляем уникальный ключ,
|
||
// если тест сам его не задал (негативные проверки ключа делают это явно).
|
||
if method == http.MethodPost && strings.Contains(path, "/messages") && req.Header.Get("Idempotency-Key") == "" {
|
||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||
}
|
||
resp, err := http.DefaultClient.Do(req)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer resp.Body.Close()
|
||
b, _ := io.ReadAll(resp.Body)
|
||
return resp.StatusCode, string(b), resp.Header
|
||
}
|
||
|
||
func decode(t *testing.T, body string) map[string]any {
|
||
t.Helper()
|
||
var m map[string]any
|
||
if err := json.Unmarshal([]byte(body), &m); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
return m
|
||
}
|
||
|
||
func basic(user, pass string) string {
|
||
return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
|
||
}
|
||
|
||
func logStep(t *testing.T, msg string) { t.Helper(); t.Logf("→ %s", msg) }
|
||
func logOK(t *testing.T, msg string) { t.Helper(); t.Logf("✓ %s", msg) }
|
||
func logResult(t *testing.T, status int, body string) {
|
||
t.Helper()
|
||
if len(body) > 400 {
|
||
body = body[:400] + "..."
|
||
}
|
||
t.Logf("status=%d body=%s", status, body)
|
||
}
|
||
|
||
func getenv(k, def string) string {
|
||
if v := os.Getenv(k); v != "" {
|
||
return v
|
||
}
|
||
return def
|
||
}
|