package main import ( "bytes" "context" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "net/url" "os" "runtime" "strings" "sync" "testing" "time" "github.com/jackc/pgx/v5/pgxpool" "github.com/redis/go-redis/v9" ) // --------------------------------------------------------------------------- // TestMain: один раз поднимает соединение к ТЕСТОВОЙ PostgreSQL (TEST_DATABASE_URL // или локальный дефолт) и прогоняет миграции. Каждый newTestEnv(t) затем // усекает все таблицы — тесты запускаются последовательно (без t.Parallel), // так что усечение в начале теста даёт чистый лист без гонок между тестами. // --------------------------------------------------------------------------- var sharedDB *pgxpool.Pool func TestMain(m *testing.M) { dsn := os.Getenv("TEST_DATABASE_URL") if dsn == "" { dsn = "postgres://messenger:messenger@localhost:5432/messenger?sslmode=disable" } if err := runMigrations(dsn); err != nil { fmt.Fprintln(os.Stderr, "миграции для тестовой БД:", err) os.Exit(1) } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) db, err := openPool(ctx, dsn) cancel() if err != nil { fmt.Fprintln(os.Stderr, "нужен запущенный Postgres для тестов (TEST_DATABASE_URL):", err) os.Exit(1) } sharedDB = db code := m.Run() db.Close() os.Exit(code) } func truncateAll(t *testing.T) { t.Helper() if _, err := sharedDB.Exec(context.Background(), `TRUNCATE sessions, messages, chat_members, chats, users CASCADE`); err != nil { t.Fatalf("truncate: %v", err) } } // --------------------------------------------------------------------------- // testEnv: тесты ходят в настоящий HTTP-сервер (httptest) с тем же роутером, // что и в проде, поэтому проверяется весь путь запроса. // --------------------------------------------------------------------------- type testEnv struct { t *testing.T url string } func newTestEnv(t *testing.T) *testEnv { return newTestEnvTTL(t, time.Hour) } func newTestEnvTTL(t *testing.T, ttl time.Duration) *testEnv { t.Helper() truncateAll(t) srv := httptest.NewServer((&api{store: NewStore(sharedDB, nil, ttl)}).routes()) t.Cleanup(srv.Close) return &testEnv{t: t, url: srv.URL} } // newTestEnvWithCache поднимает тот же роутер, но с реальным Redis-кэшем // сессий поверх той же PostgreSQL — для тестов, специфичных для кэша // (попадание в кэш, инвалидация при logout, деградация при отказе Redis). func newTestEnvWithCache(t *testing.T) *testEnv { t.Helper() truncateAll(t) addr := os.Getenv("TEST_CACHE_URL") if addr == "" { addr = "redis://localhost:6379/0" } cache, err := newSessionCache(addr) if err != nil { t.Fatalf("нужен запущенный Redis для теста (TEST_CACHE_URL): %v", err) } if err := cache.rdb.FlushDB(context.Background()).Err(); err != nil { t.Fatalf("flushdb: %v", err) } t.Cleanup(func() { cache.Close() }) srv := httptest.NewServer((&api{store: NewStore(sharedDB, cache, time.Hour)}).routes()) t.Cleanup(srv.Close) return &testEnv{t: t, url: srv.URL} } type page[T any] struct { Items []T `json:"items"` NextCursor *string `json:"next_cursor"` } // send безопасен для вызова из горутин (не трогает *testing.T). // token: "" — без Bearer-авторизации. extra — дополнительные/замещающие // заголовки (например Authorization: Basic для входа). // body: nil — без тела; []byte/string — «как есть» (для битого JSON); остальное — JSON. func (e *testEnv) send(method, path, token string, body any, extra http.Header) (int, http.Header, []byte, error) { var rd io.Reader switch b := body.(type) { case nil: case []byte: rd = bytes.NewReader(b) case string: rd = strings.NewReader(b) default: raw, err := json.Marshal(b) if err != nil { return 0, nil, nil, err } rd = bytes.NewReader(raw) } req, err := http.NewRequest(method, e.url+path, rd) if err != nil { return 0, nil, nil, err } if rd != nil { req.Header.Set("Content-Type", "application/json") } for k, vs := range extra { req.Header.Del(k) // extra заменяет дефолт (например, свой Content-Type), а не дублирует for _, v := range vs { req.Header.Add(k, v) } } if token != "" { req.Header.Set("Authorization", "Bearer "+token) } resp, err := http.DefaultClient.Do(req) if err != nil { return 0, nil, nil, err } defer resp.Body.Close() data, err := io.ReadAll(resp.Body) return resp.StatusCode, resp.Header, data, err } func (e *testEnv) do(method, path, token string, body any) (int, http.Header, []byte) { e.t.Helper() status, hdr, data, err := e.send(method, path, token, body, nil) if err != nil { e.t.Fatalf("%s %s: %v", method, path, err) } return status, hdr, data } func basicAuthHeader(username, password string) http.Header { cred := base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) return http.Header{"Authorization": []string{"Basic " + cred}} } // expectJSON проверяет код ответа и разбирает тело в dst. func (e *testEnv) expectJSON(status int, dst any, method, path, token string, body any) { e.t.Helper() got, _, data := e.do(method, path, token, body) if got != status { e.t.Fatalf("%s %s: статус %d, ожидали %d; тело: %s", method, path, got, status, data) } if dst != nil { if err := json.Unmarshal(data, dst); err != nil { e.t.Fatalf("%s %s: некорректный JSON в ответе: %v", method, path, err) } } } // expectErr проверяет код, машинный код ошибки и что request_id в теле == X-Request-Id. func (e *testEnv) expectErr(status int, code, method, path, token string, body any) { e.t.Helper() got, hdr, data := e.do(method, path, token, body) if got != status { e.t.Fatalf("%s %s: статус %d, ожидали %d; тело: %s", method, path, got, status, data) } var env struct { Error struct { Code string `json:"code"` Message string `json:"message"` RequestID string `json:"request_id"` } `json:"error"` } if err := json.Unmarshal(data, &env); err != nil { e.t.Fatalf("%s %s: тело ошибки не JSON: %s", method, path, data) } rid := hdr.Get("X-Request-Id") if rid == "" || env.Error.RequestID != rid { e.t.Fatalf("%s %s: request_id в теле (%q) не совпадает с заголовком (%q)", method, path, env.Error.RequestID, rid) } if env.Error.Code != code || env.Error.Message == "" { e.t.Fatalf("%s %s: код ошибки %q, ожидали %q", method, path, env.Error.Code, code) } } // actor — зарегистрированный и вошедший пользователь: и сам User, и // Bearer-токен его сессии, и исходный пароль (для повторного логина в тестах). type actor struct { user User password string token string } func (e *testEnv) mustRegister(username string) User { e.t.Helper() var u User e.expectJSON(http.StatusCreated, &u, "POST", "/api/v1/users", "", map[string]string{"username": username, "display_name": "Тест " + username, "password": "Correct-horse-battery-staple"}) return u } // mustActor регистрирует и один раз логинится — основной способ получить // рабочего "актёра" для теста. func (e *testEnv) mustActor(username string) actor { e.t.Helper() const password = "Correct-horse-battery-staple" u := e.mustRegister(username) return e.loginActor(u, password) } func (e *testEnv) loginActor(u User, password string) actor { e.t.Helper() status, _, data, err := e.send("POST", "/api/v1/auth/sessions", "", nil, basicAuthHeader(u.Username, password)) if err != nil { e.t.Fatalf("login: %v", err) } if status != http.StatusCreated { e.t.Fatalf("login %s: статус %d, тело: %s", u.Username, status, data) } var s Session if err := json.Unmarshal(data, &s); err != nil { e.t.Fatalf("login %s: некорректный JSON: %v", u.Username, err) } return actor{user: u, password: password, token: s.Token} } func (e *testEnv) mustChat(owner actor, title string, members ...actor) Chat { e.t.Helper() ids := []string{owner.user.ID} for _, m := range members { ids = append(ids, m.user.ID) } var c Chat e.expectJSON(http.StatusCreated, &c, "POST", "/api/v1/chats", owner.token, map[string]any{"title": title, "member_ids": ids}) return c } func (e *testEnv) mustMessage(a actor, chatID, text string) Message { e.t.Helper() var m Message e.expectJSON(http.StatusCreated, &m, "POST", "/api/v1/chats/"+chatID+"/messages", a.token, map[string]string{"text": text}) return m } // listMessages обходит всю историю страницами по limit и возвращает все элементы и число страниц. func (e *testEnv) listMessages(a actor, chatID string, limit int) ([]Message, int) { e.t.Helper() var all []Message cursor, pages := "", 0 for { if pages++; pages > 1000 { e.t.Fatal("пагинация не завершается") } path := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chatID, limit) if cursor != "" { path += "&cursor=" + url.QueryEscape(cursor) } var p page[Message] e.expectJSON(http.StatusOK, &p, "GET", path, a.token, nil) if len(p.Items) > limit { e.t.Fatalf("на странице %d элементов при limit=%d", len(p.Items), limit) } all = append(all, p.Items...) if p.NextCursor == nil { return all, pages } cursor = *p.NextCursor } } // --------------------------------------------------------------------------- // Тесты // --------------------------------------------------------------------------- func TestRegisterUserInvalidInput(t *testing.T) { e := newTestEnv(t) validPW := "Correct-horse-battery-staple" cases := map[string]any{ "битый JSON": `{"username":`, "мусор после объекта": `{"username":"abc","display_name":"x","password":"` + validPW + `"} {}`, "null вместо объекта": `null`, "лишнее поле": map[string]any{"username": "abc", "display_name": "x", "password": validPW, "admin": true}, "неверный тип": `{"username":"abc","display_name":5,"password":"` + validPW + `"}`, "нет password": map[string]string{"username": "abc", "display_name": "x"}, "username верхний регистр": map[string]string{"username": "Alice", "display_name": "x", "password": validPW}, "username короче 3": map[string]string{"username": "ab", "display_name": "x", "password": validPW}, "username длиннее 32": map[string]string{"username": strings.Repeat("a", 33), "display_name": "x", "password": validPW}, "username с дефисом": map[string]string{"username": "al-ice", "display_name": "x", "password": validPW}, "display_name пробелы": map[string]string{"username": "abc", "display_name": " ", "password": validPW}, "display_name 101": map[string]string{"username": "abc", "display_name": strings.Repeat("я", 101), "password": validPW}, "password короче 12": map[string]string{"username": "abc", "display_name": "x", "password": "short-pass"}, "password длиннее 128": map[string]string{"username": "abc", "display_name": "x", "password": strings.Repeat("a", 129)}, "password из пробелов": map[string]string{"username": "abc", "display_name": "x", "password": strings.Repeat(" ", 20)}, } for name, body := range cases { t.Run(name, func(t *testing.T) { e.expectErr(http.StatusBadRequest, "invalid_request", "POST", "/api/v1/users", "", body) }) } } func TestRegisterUserWrongContentType(t *testing.T) { e := newTestEnv(t) got, _, data, err := e.send("POST", "/api/v1/users", "", []byte(`not json`), http.Header{"Content-Type": {"text/plain"}}) if err != nil { t.Fatal(err) } if got != http.StatusUnsupportedMediaType { t.Fatalf("статус %d, тело %s", got, data) } } func TestDuplicateUsername(t *testing.T) { e := newTestEnv(t) e.mustRegister("alice") e.expectErr(http.StatusConflict, "conflict", "POST", "/api/v1/users", "", map[string]string{"username": "alice", "display_name": "Другая Алиса", "password": "Correct-horse-battery-staple"}) } // Гонка двух параллельных регистраций ОДНОГО username: ровно один 201, // ровно один 409 — защита идёт через UNIQUE INDEX в PostgreSQL, не через // check-then-insert в Go (который был бы подвержен той же гонке). func TestConcurrentRegistrationSameUsernameOnlyOneSucceeds(t *testing.T) { e := newTestEnv(t) const n = 10 var wg sync.WaitGroup statuses := make([]int, n) for i := 0; i < n; i++ { wg.Add(1) go func(i int) { defer wg.Done() status, _, _ := e.do("POST", "/api/v1/users", "", map[string]string{"username": "racer", "display_name": "Racer", "password": "Correct-horse-battery-staple"}) statuses[i] = status }(i) } wg.Wait() created, conflicted := 0, 0 for _, s := range statuses { switch s { case http.StatusCreated: created++ case http.StatusConflict: conflicted++ default: t.Fatalf("неожиданный статус %d", s) } } if created != 1 || conflicted != n-1 { t.Fatalf("created=%d conflicted=%d, ожидали 1 и %d", created, conflicted, n-1) } } func TestLoginWrongCredentials(t *testing.T) { e := newTestEnv(t) u := e.mustRegister("alice") status, hdr, _, err := e.send("POST", "/api/v1/auth/sessions", "", nil, basicAuthHeader(u.Username, "wrong-password-but-long-enough")) if err != nil { t.Fatal(err) } if status != http.StatusUnauthorized { t.Fatalf("статус %d, ожидали 401", status) } if !strings.HasPrefix(strings.ToLower(hdr.Get("WWW-Authenticate")), "basic") { t.Fatalf("WWW-Authenticate=%q, ожидали Basic", hdr.Get("WWW-Authenticate")) } status2, _, _, _ := e.send("POST", "/api/v1/auth/sessions", "", nil, basicAuthHeader("no-such-user", "whatever-long-enough")) if status2 != http.StatusUnauthorized { t.Fatalf("неизвестный username: статус %d, ожидали 401", status2) } } func TestUnauthorized(t *testing.T) { e := newTestEnv(t) e.expectErr(http.StatusUnauthorized, "unauthorized", "GET", "/api/v1/users/me", "", nil) e.expectErr(http.StatusUnauthorized, "unauthorized", "GET", "/api/v1/users/me", "not-a-real-token", nil) } // Basic на бизнес-endpoint — 401 (там нужен именно Bearer). func TestBasicOnBusinessEndpointRejected(t *testing.T) { e := newTestEnv(t) u := e.mustRegister("alice") status, _, _, err := e.send("GET", "/api/v1/users/me", "", nil, basicAuthHeader(u.Username, "Correct-horse-battery-staple")) if err != nil { t.Fatal(err) } if status != http.StatusUnauthorized { t.Fatalf("статус %d, ожидали 401", status) } } // X-User-Id с lab2 ничего не даёт сам по себе и не переопределяет личность // из Bearer-токена. func TestXUserIdHeaderIgnored(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") eve := e.mustActor("eve") status, _, _, err := e.send("GET", "/api/v1/users/me", "", nil, http.Header{"X-User-Id": {eve.user.ID}}) if err != nil { t.Fatal(err) } if status != http.StatusUnauthorized { t.Fatalf("X-User-Id без Bearer: статус %d, ожидали 401", status) } status2, _, data2, err := e.send("GET", "/api/v1/users/me", "", nil, http.Header{ "Authorization": {"Bearer " + alice.token}, "X-User-Id": {eve.user.ID}, }) if err != nil { t.Fatal(err) } if status2 != http.StatusOK { t.Fatalf("статус %d", status2) } var me2 User if err := json.Unmarshal(data2, &me2); err != nil { t.Fatal(err) } if me2.ID != alice.user.ID { t.Fatalf("X-User-Id переопределил личность из Bearer: получили %s, ожидали %s", me2.ID, alice.user.ID) } } // Logout отзывает токен; повторный logout тем же токеном — 401 (он уже недействителен). func TestSessionLogout(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") status, _, _ := e.do("DELETE", "/api/v1/auth/sessions/current", alice.token, nil) if status != http.StatusNoContent { t.Fatalf("logout: статус %d, ожидали 204", status) } e.expectErr(http.StatusUnauthorized, "unauthorized", "GET", "/api/v1/users/me", alice.token, nil) e.expectErr(http.StatusUnauthorized, "unauthorized", "DELETE", "/api/v1/auth/sessions/current", alice.token, nil) } // Короткий TTL — явная автоматическая проверка истечения сессии. func TestSessionExpiry(t *testing.T) { e := newTestEnvTTL(t, 1*time.Second) alice := e.mustActor("alice") var me User e.expectJSON(http.StatusOK, &me, "GET", "/api/v1/users/me", alice.token, nil) time.Sleep(1200 * time.Millisecond) e.expectErr(http.StatusUnauthorized, "unauthorized", "GET", "/api/v1/users/me", alice.token, nil) } func TestOutsiderCannotAccessChat(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") bob := e.mustActor("bob") eve := e.mustActor("eve") chat := e.mustChat(alice, "чат", bob) e.expectErr(http.StatusNotFound, "not_found", "GET", "/api/v1/chats/"+chat.ID, eve.token, nil) e.expectErr(http.StatusNotFound, "not_found", "POST", "/api/v1/chats/"+chat.ID+"/messages", eve.token, map[string]string{"text": "чужое"}) e.expectErr(http.StatusNotFound, "not_found", "GET", "/api/v1/chats/"+chat.ID+"/messages", eve.token, nil) var listed page[Chat] e.expectJSON(http.StatusOK, &listed, "GET", "/api/v1/chats?limit=100", eve.token, nil) for _, c := range listed.Items { if c.ID == chat.ID { t.Fatal("чужой чат утёк в список чатов постороннего") } } } func TestCreateChatValidation(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") bob := e.mustActor("bob") cases := map[string]map[string]any{ "пустой title": {"title": "", "member_ids": []string{alice.user.ID}}, "пустой список": {"title": "x", "member_ids": []string{}}, "не UUID в member_ids": {"title": "x", "member_ids": []string{"not-a-uuid"}}, "дубликаты участников": {"title": "x", "member_ids": []string{alice.user.ID, alice.user.ID}}, "вызывающий не в списке": {"title": "x", "member_ids": []string{bob.user.ID}}, "неизвестный участник": {"title": "x", "member_ids": []string{alice.user.ID, newUUID()}}, } for name, body := range cases { t.Run(name, func(t *testing.T) { e.expectErr(http.StatusBadRequest, "invalid_request", "POST", "/api/v1/chats", alice.token, body) }) } } // Составная операция создания чата атомарна: неизвестный участник не // должен оставить после себя ни чат, ни частичный список участников. func TestCreateChatRollsBackOnUnknownMember(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") const title = "Чат с несуществующим участником" status, _, data := e.do("POST", "/api/v1/chats", alice.token, map[string]any{"title": title, "member_ids": []string{alice.user.ID, newUUID()}}) if status != http.StatusBadRequest { t.Fatalf("статус %d, тело %s", status, data) } var listed page[Chat] e.expectJSON(http.StatusOK, &listed, "GET", "/api/v1/chats?limit=100", alice.token, nil) for _, c := range listed.Items { if c.Title == title { t.Fatalf("откат не сработал: чат %q всё равно появился в списке", title) } } var count int if err := sharedDB.QueryRow(context.Background(), `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&count); err != nil { t.Fatal(err) } if count != 0 { t.Fatalf("в БД осталась %d строк(а) чата, который должен был откатиться", count) } } func TestMessageValidation(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") chat := e.mustChat(alice, "чат") cases := map[string]any{ "пустой текст": map[string]string{"text": ""}, "только пробелы": map[string]string{"text": " "}, "нет поля text": map[string]string{}, "text не строка": `{"text":5}`, "4001 code point": map[string]string{"text": strings.Repeat("я", 4001)}, "sender_id в теле": map[string]any{"text": "привет", "sender_id": newUUID()}, "лишнее поле": map[string]any{"text": "привет", "extra": true}, "битый JSON": `{"text":`, "два объекта подряд": `{"text":"a"} {}`, } for name, body := range cases { t.Run(name, func(t *testing.T) { e.expectErr(http.StatusBadRequest, "invalid_request", "POST", "/api/v1/chats/"+chat.ID+"/messages", alice.token, body) }) } } func TestPaginationWalksAllPages(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") chat := e.mustChat(alice, "чат") const total = 53 for i := 0; i < total; i++ { e.mustMessage(alice, chat.ID, fmt.Sprint(i)) } for _, limit := range []int{1, 7, 24, 25, 100} { t.Run(fmt.Sprintf("limit=%d", limit), func(t *testing.T) { items, _ := e.listMessages(alice, chat.ID, limit) if len(items) != total { t.Fatalf("получили %d сообщений, ожидали %d", len(items), total) } for i, m := range items { if m.Text != fmt.Sprint(i) { t.Fatalf("сообщение %d: текст %q, ожидали %q (порядок нарушен)", i, m.Text, fmt.Sprint(i)) } } }) } } func TestPaginationBadParameters(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") chat := e.mustChat(alice, "чат") other := e.mustActor("bob") otherChat := e.mustChat(other, "другой чат") e.mustMessage(alice, chat.ID, "привет") cases := map[string]string{ "limit=0": "?limit=0", "limit=101": "?limit=101", "limit=-1": "?limit=-1", "limit=abc": "?limit=abc", "cursor мусор": "?cursor=not-a-valid-cursor", } for name, q := range cases { t.Run(name, func(t *testing.T) { e.expectErr(http.StatusBadRequest, "invalid_request", "GET", "/api/v1/chats/"+chat.ID+"/messages"+q, alice.token, nil) }) } // Курсор чужого (другого) scope — тоже 400. var p page[Message] e.expectJSON(http.StatusOK, &p, "GET", "/api/v1/chats/"+otherChat.ID+"/messages?limit=1", other.token, nil) foreignCursor := encodeCursor("m:"+chat.ID, "2024-01-01T00:00:00.000000Z", newUUID()) e.expectErr(http.StatusBadRequest, "invalid_request", "GET", "/api/v1/chats/"+otherChat.ID+"/messages?cursor="+url.QueryEscape(foreignCursor), other.token, nil) } func TestChatListPagination(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") const total = 12 seen := map[string]bool{} for i := 0; i < total; i++ { e.mustChat(alice, fmt.Sprintf("чат %d", i)) } cursor := "" for { path := "/api/v1/chats?limit=5" if cursor != "" { path += "&cursor=" + url.QueryEscape(cursor) } var p page[Chat] e.expectJSON(http.StatusOK, &p, "GET", path, alice.token, nil) for _, c := range p.Items { if seen[c.ID] { t.Fatalf("чат %s отдан дважды", c.ID) } seen[c.ID] = true } if p.NextCursor == nil { break } cursor = *p.NextCursor } if len(seen) != total { t.Fatalf("получили %d чатов, ожидали %d", len(seen), total) } } func TestEveryResponseHasRequestID(t *testing.T) { e := newTestEnv(t) _, hdr, _ := e.do("GET", "/health/live", "", nil) if hdr.Get("X-Request-Id") == "" { t.Fatal("health/live без X-Request-Id") } _, hdr2, _ := e.do("GET", "/api/v1/users/me", "", nil) if hdr2.Get("X-Request-Id") == "" { t.Fatal("ошибка 401 без X-Request-Id") } } // 100 сообщений от 10 параллельных клиентов -> ровно 100 уникальных сообщений. func TestConcurrentSendKeepsEveryMessage(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") chat := e.mustChat(alice, "чат") const writers, perWriter = 10, 10 var wg sync.WaitGroup for w := 0; w < writers; w++ { wg.Add(1) go func(w int) { defer wg.Done() for i := 0; i < perWriter; i++ { status, _, data := e.do("POST", "/api/v1/chats/"+chat.ID+"/messages", alice.token, map[string]string{"text": fmt.Sprintf("w%d-m%d", w, i)}) if status != http.StatusCreated { e.t.Errorf("писатель %d сообщение %d: статус %d, тело %s", w, i, status, data) } runtime.Gosched() } }(w) } wg.Wait() items, _ := e.listMessages(alice, chat.ID, 100) if len(items) != writers*perWriter { t.Fatalf("сообщений %d, ожидали %d", len(items), writers*perWriter) } seen := make(map[string]bool, len(items)) for _, m := range items { if seen[m.ID] { t.Fatalf("сообщение %s отдано дважды", m.ID) } seen[m.ID] = true } } // Дубликат ключа, отличающегося только регистром, не должен тихо // перезаписывать значение правильно написанного поля. func TestDuplicateKeyDifferingOnlyInCaseIsRejected(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") chat := e.mustChat(alice, "чат") e.expectErr(http.StatusBadRequest, "invalid_request", "POST", "/api/v1/chats/"+chat.ID+"/messages", alice.token, []byte(`{"text":"valid","TEXT":"overwritten"}`)) e.expectErr(http.StatusBadRequest, "invalid_request", "POST", "/api/v1/users", "", []byte(`{"username":"bob1","display_name":"Боб","DISPLAY_NAME":"Подмена","password":"Correct-horse-battery-staple"}`)) } // Невалидные байты UTF-8 должны отклоняться 400, а не тихо приниматься. func TestInvalidUTF8IsRejected(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") chat := e.mustChat(alice, "чат") e.expectErr(http.StatusBadRequest, "invalid_request", "POST", "/api/v1/chats/"+chat.ID+"/messages", alice.token, []byte("{\"text\":\"\xff\"}")) e.expectErr(http.StatusBadRequest, "invalid_request", "POST", "/api/v1/users", "", []byte("{\"username\":\"bob2\",\"display_name\":\"\xff\",\"password\":\"Correct-horse-battery-staple\"}")) } // Структурно правильный, но семантически мусорный cursor — 400, не пустая страница. func TestGarbageCursorIsRejected(t *testing.T) { e := newTestEnv(t) alice := e.mustActor("alice") chat := e.mustChat(alice, "чат") e.mustMessage(alice, chat.ID, "привет") garbage := base64.RawURLEncoding.EncodeToString([]byte("m:" + chat.ID + "|not-a-time|not-a-uuid")) e.expectErr(http.StatusBadRequest, "invalid_request", "GET", "/api/v1/chats/"+chat.ID+"/messages?cursor="+url.QueryEscape(garbage), alice.token, nil) badTime := base64.RawURLEncoding.EncodeToString([]byte("c:" + alice.user.ID + "|not-a-time|" + newUUID())) e.expectErr(http.StatusBadRequest, "invalid_request", "GET", "/api/v1/chats?cursor="+url.QueryEscape(badTime), alice.token, nil) badUUID := base64.RawURLEncoding.EncodeToString([]byte("c:" + alice.user.ID + "|2024-01-01T00:00:00.000000Z|not-a-uuid")) e.expectErr(http.StatusBadRequest, "invalid_request", "GET", "/api/v1/chats?cursor="+url.QueryEscape(badUUID), alice.token, nil) } // --- кэш сессий (уровень 4) ------------------------------------------------ // Попадание в кэш отдаёт того же пользователя, что и прямой поход в Postgres. func TestSessionCacheHitMatchesDatabase(t *testing.T) { e := newTestEnvWithCache(t) alice := e.mustActor("alice") var fromMiss User e.expectJSON(http.StatusOK, &fromMiss, "GET", "/api/v1/users/me", alice.token, nil) // первый — промах, заполняет кэш var fromHit User e.expectJSON(http.StatusOK, &fromHit, "GET", "/api/v1/users/me", alice.token, nil) // второй — попадание в кэш if fromHit != fromMiss || fromHit.ID != alice.user.ID { t.Fatalf("данные из кэша расходятся с БД: %+v vs %+v", fromMiss, fromHit) } } // Logout инвалидирует кэш: повторная проверка того же токена видит отзыв, // а не устаревшую "валидную" запись. func TestSessionCacheInvalidatedOnLogout(t *testing.T) { e := newTestEnvWithCache(t) alice := e.mustActor("alice") var me User e.expectJSON(http.StatusOK, &me, "GET", "/api/v1/users/me", alice.token, nil) // прогреваем кэш status, _, _ := e.do("DELETE", "/api/v1/auth/sessions/current", alice.token, nil) if status != http.StatusNoContent { t.Fatalf("logout: статус %d", status) } e.expectErr(http.StatusUnauthorized, "unauthorized", "GET", "/api/v1/users/me", alice.token, nil) } // Недоступность Redis не делает анонимный запрос доверенным и не роняет // авторизацию — она просто идёт мимо кэша прямо в Postgres. func TestSessionValidationSurvivesRedisOutage(t *testing.T) { e := newTestEnv(t) // без кэша в HTTP-слое — Store.ValidateSession проверяем напрямую alice := e.mustActor("alice") downCache := &sessionCache{rdb: redis.NewClient(&redis.Options{ Addr: "127.0.0.1:1", // ничего не слушает DialTimeout: 200 * time.Millisecond, })} t.Cleanup(func() { downCache.Close() }) store := NewStore(sharedDB, downCache, time.Hour) u, ok, err := store.ValidateSession(context.Background(), alice.token) if err != nil { t.Fatalf("ValidateSession вернул ошибку при недоступном Redis (должен был обойти кэш и дойти до Postgres): %v", err) } if !ok || u.ID != alice.user.ID { t.Fatalf("валидная сессия не подтвердилась при недоступном Redis: ok=%v u=%+v", ok, u) } // Заведомо неверный токен при недоступном Redis — всё равно 401, не "доверяем". _, ok2, err2 := store.ValidateSession(context.Background(), "совершенно-неверный-токен") if err2 != nil { t.Fatalf("неожиданная ошибка: %v", err2) } if ok2 { t.Fatal("недоступность Redis не должна превращать неверный токен в валидный") } } // Недоступность PostgreSQL отражается в /health/ready как 503, а не как // "всё хорошо" — и ValidateSession явно возвращает error, а не "валидно". func TestReadyAndAuthReturnUnavailableWhenPostgresDown(t *testing.T) { badDSN := "postgres://messenger:messenger@127.0.0.1:1/messenger?sslmode=disable&connect_timeout=1" badDB, err := pgxpool.New(context.Background(), badDSN) if err != nil { t.Fatal(err) } defer badDB.Close() store := NewStore(badDB, nil, time.Hour) if err := store.Ready(context.Background()); err == nil { t.Fatal("Ready() должен вернуть ошибку при недоступном Postgres") } _, ok, err := store.ValidateSession(context.Background(), "любой-токен") if err == nil { t.Fatal("ValidateSession должен вернуть ошибку (не false без ошибки) при недоступном Postgres") } if ok { t.Fatal("недоступный Postgres не должен трактоваться как «сессия валидна»") } srv := httptest.NewServer((&api{store: store}).routes()) defer srv.Close() resp, err := http.Get(srv.URL + "/health/ready") if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusServiceUnavailable { t.Fatalf("статус %d, ожидали 503", resp.StatusCode) } } // TestEmptyListsAreJSONArraysNotNull — регрессия на баг, который поймал // внешний публичный smoke-тест, но не свои: "items":null вместо // "items":[] при пустой истории/списке. encoding/json маршалит nil-слайс // как null, а не []; Go-декодирование в структуру эту разницу прощает // (null в []T остаётся nil-слайсом без ошибки), поэтому проверка делается // по СЫРЫМ байтам ответа, а не через json.Unmarshal в типизированный dst. func TestEmptyListsAreJSONArraysNotNull(t *testing.T) { e := newTestEnv(t) a := e.mustActor("emptylists") // Свежий пользователь без единого чата. _, _, data := e.do("GET", "/api/v1/chats", a.token, nil) if !bytes.Contains(data, []byte(`"items":[]`)) { t.Fatalf(`GET /chats без чатов: ожидали "items":[] в сыром JSON, получили: %s`, data) } // Чат без единого сообщения. c := e.mustChat(a, "Пустой чат") _, _, data = e.do("GET", "/api/v1/chats/"+c.ID+"/messages", a.token, nil) if !bytes.Contains(data, []byte(`"items":[]`)) { t.Fatalf(`GET /messages без сообщений: ожидали "items":[] в сыром JSON, получили: %s`, data) } }