This commit is contained in:
Vladislav Kunetskiy
2026-10-15 20:45:29 +03:00
parent 1fdaf6299a
commit f4bd361f12
140 changed files with 12784 additions and 2198 deletions
+216 -533
View File
@@ -1,100 +1,87 @@
package rest
package rest_test
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/stretchr/testify/suite"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/logger"
"mtusi-messenger/internal/service/chat"
"mtusi-messenger/internal/service/message"
"mtusi-messenger/internal/service/user"
"mtusi-messenger/internal/storage/memory"
"mtusi-messenger/internal/transport/rest"
"mtusi-messenger/internal/transport/rest/mocks"
)
const userIDHeader = "X-User-Id"
const requestIDHeader = "X-Request-ID"
type response struct {
func basic(username, password string) string {
return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
}
func assertError(message string) error {
return errors.New(message)
}
type httpResult struct {
status int
header http.Header
body []byte
}
type RouterSuite struct {
suite.Suite
type routerFixture struct {
users *mocks.MockUserService
chats *mocks.MockChatService
messages *mocks.MockMessageService
health *mocks.MockHealthChecker
sessions *mocks.MockSessionActions
sink *strings.Builder
log *slog.Logger
server *httptest.Server
}
func TestRouterSuite(t *testing.T) {
t.Parallel()
suite.Run(t, new(RouterSuite))
}
func newRouterFixture(t *testing.T) *routerFixture {
t.Helper()
func (s *RouterSuite) SetupTest() {
s.sink = &strings.Builder{}
s.log = logger.New(logger.WithWriter(s.sink), logger.WithLevel(slog.LevelDebug))
store := memory.NewStore()
userService := user.NewService(store.Users())
router, err := NewRouter(
NewHandler(
userService,
chat.NewService(store.Chats()),
message.NewService(store.Messages()),
),
NewSecurityHandler(userService),
s.log,
)
s.Require().NoError(err)
s.server = httptest.NewServer(router)
}
func (s *RouterSuite) TearDownTest() {
s.server.Close()
}
func (s *RouterSuite) do(method, path string, headers map[string]string) response {
s.T().Helper()
return s.send(method, path, nil, headers)
}
func (s *RouterSuite) send(method, path string, body any, headers map[string]string) response {
s.T().Helper()
if body == nil {
return s.sendRaw(method, path, nil, headers)
fixture := &routerFixture{
users: mocks.NewMockUserService(t),
chats: mocks.NewMockChatService(t),
messages: mocks.NewMockMessageService(t),
health: mocks.NewMockHealthChecker(t),
sessions: mocks.NewMockSessionActions(t),
}
raw, err := json.Marshal(body)
s.Require().NoError(err)
router, err := rest.NewRouter(
rest.NewHandler(fixture.users, fixture.chats, fixture.messages, fixture.health, fixture.sessions),
rest.NewSecurityHandler(fixture.sessions),
logger.New(logger.WithLevel(slog.LevelError)),
)
require.NoError(t, err)
return s.sendRaw(method, path, raw, headers)
fixture.server = httptest.NewServer(router)
t.Cleanup(fixture.server.Close)
return fixture
}
func (s *RouterSuite) sendRaw(method, path string, body []byte, headers map[string]string) response {
s.T().Helper()
func (f *routerFixture) do(t *testing.T, method, path string, body []byte, headers map[string]string) httpResult {
t.Helper()
var reader io.Reader
if body != nil {
reader = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(s.T().Context(), method, s.server.URL+path, reader)
s.Require().NoError(err)
req, err := http.NewRequestWithContext(t.Context(), method, f.server.URL+path, reader)
require.NoError(t, err)
if body != nil {
req.Header.Set("Content-Type", "application/json")
@@ -104,540 +91,236 @@ func (s *RouterSuite) sendRaw(method, path string, body []byte, headers map[stri
req.Header.Set(key, value)
}
resp, err := s.server.Client().Do(req)
s.Require().NoError(err)
resp, err := f.server.Client().Do(req)
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
payload, err := io.ReadAll(resp.Body)
s.Require().NoError(err)
require.NoError(t, err)
return response{status: resp.StatusCode, header: resp.Header, body: payload}
return httpResult{status: resp.StatusCode, header: resp.Header, body: payload}
}
func (s *RouterSuite) records() []map[string]any {
s.T().Helper()
func TestHealthEndpoints(t *testing.T) {
fixture := newRouterFixture(t)
fixture.health.EXPECT().Ping(mock.Anything).Return(nil).Maybe()
var out []map[string]any
result := fixture.do(t, http.MethodGet, "/health/live", nil, nil)
require.Equal(t, http.StatusOK, result.status)
require.NotEmpty(t, result.header.Get(requestIDHeader))
require.JSONEq(t, `{"status":"ok"}`, string(result.body))
for line := range strings.SplitSeq(strings.TrimSpace(s.sink.String()), "\n") {
if line == "" {
continue
}
var record map[string]any
s.Require().NoError(json.Unmarshal([]byte(line), &record))
out = append(out, record)
}
return out
result = fixture.do(t, http.MethodGet, "/health/ready", nil, nil)
require.Equal(t, http.StatusOK, result.status)
}
func (s *RouterSuite) lastRecord() map[string]any {
s.T().Helper()
func TestReadinessReturns503WhenDependencyDown(t *testing.T) {
fixture := newRouterFixture(t)
fixture.health.EXPECT().Ping(mock.Anything).Return(assertError("down")).Maybe()
records := s.records()
s.Require().NotEmpty(records)
return records[len(records)-1]
}
func (s *RouterSuite) decodeError(resp response) map[string]any {
s.T().Helper()
result := fixture.do(t, http.MethodGet, "/health/ready", nil, nil)
require.Equal(t, http.StatusServiceUnavailable, result.status)
var body struct {
Error map[string]any `json:"error"`
Error struct {
Code string `json:"code"`
} `json:"error"`
}
s.Require().NoError(json.Unmarshal(resp.body, &body))
s.Require().NotEmpty(body.Error)
return body.Error
require.NoError(t, json.Unmarshal(result.body, &body))
require.Equal(t, "unavailable", body.Error.Code)
}
func (s *RouterSuite) decode(resp response) map[string]any {
s.T().Helper()
func TestRequestIDEchoedFromClient(t *testing.T) {
fixture := newRouterFixture(t)
result := fixture.do(t, http.MethodGet, "/health/live", nil, map[string]string{requestIDHeader: "from-client"})
require.Equal(t, "from-client", result.header.Get(requestIDHeader))
}
func TestProtectedEndpointRequiresBearer(t *testing.T) {
tests := map[string]map[string]string{
"без заголовка": nil,
"только X-User-Id": {"X-User-Id": uuid.NewString()},
"basic вместо bearer": {"Authorization": "Basic dXNlcjpwYXNz"},
}
for name, headers := range tests {
t.Run(name, func(t *testing.T) {
fixture := newRouterFixture(t)
result := fixture.do(t, http.MethodGet, "/api/v1/users/me", nil, headers)
require.Equal(t, http.StatusUnauthorized, result.status)
require.Contains(t, result.header.Get("WWW-Authenticate"), "Bearer")
})
}
}
func TestBearerSessionIsResolvedToCaller(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Once()
fixture.users.EXPECT().GetByID(mock.Anything, user.ID).Return(user, nil).Once()
result := fixture.do(t, http.MethodGet, "/api/v1/users/me", nil, map[string]string{"Authorization": "Bearer opaque-token"})
require.Equal(t, http.StatusOK, result.status)
var body map[string]any
s.Require().NoError(json.Unmarshal(resp.body, &body))
return body
require.NoError(t, json.Unmarshal(result.body, &body))
require.Equal(t, user.ID.String(), body["id"])
}
func (s *RouterSuite) register(username string) map[string]any {
s.T().Helper()
func TestUnknownBearerIsRejected(t *testing.T) {
fixture := newRouterFixture(t)
fixture.sessions.EXPECT().Resolve(mock.Anything, "unknown").Return(domain.User{}, domain.ErrUnauthenticated).Once()
resp := s.send(http.MethodPost, "/api/v1/users", map[string]string{
"username": username,
"display_name": "Пользователь " + username,
}, nil)
s.Require().Equal(http.StatusCreated, resp.status, string(resp.body))
return s.decode(resp)
result := fixture.do(t, http.MethodGet, "/api/v1/chats", nil, map[string]string{"Authorization": "Bearer unknown"})
require.Equal(t, http.StatusUnauthorized, result.status)
require.Contains(t, result.header.Get("WWW-Authenticate"), "Bearer")
}
func (s *RouterSuite) actor(user map[string]any) map[string]string {
s.T().Helper()
func TestRegisterUserReturnsContractShape(t *testing.T) {
fixture := newRouterFixture(t)
id, ok := user["id"].(string)
s.Require().True(ok)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
fixture.users.EXPECT().Register(mock.Anything, draft).Return(user, nil).Once()
return map[string]string{userIDHeader: id}
body, err := json.Marshal(map[string]string{"username": "alice", "display_name": "Алиса", "password": draft.Password})
require.NoError(t, err)
result := fixture.do(t, http.MethodPost, "/api/v1/users", body, nil)
require.Equal(t, http.StatusCreated, result.status)
require.NotContains(t, string(result.body), "password")
var decoded map[string]any
require.NoError(t, json.Unmarshal(result.body, &decoded))
require.Equal(t, user.ID.String(), decoded["id"])
require.Len(t, decoded, 4)
}
func (s *RouterSuite) createChat(owner map[string]any, members ...string) map[string]any {
s.T().Helper()
func TestRegisterDuplicateUsernameConflicts(t *testing.T) {
fixture := newRouterFixture(t)
fixture.users.EXPECT().Register(mock.Anything, mock.Anything).Return(domain.User{}, domain.ErrUsernameTaken).Once()
resp := s.send(http.MethodPost, "/api/v1/chats", map[string]any{
"title": "Контрактный чат",
"member_ids": members,
}, s.actor(owner))
s.Require().Equal(http.StatusCreated, resp.status, string(resp.body))
body, err := json.Marshal(map[string]string{"username": "alice", "display_name": "Алиса", "password": "very-secret-password"})
require.NoError(t, err)
return s.decode(resp)
result := fixture.do(t, http.MethodPost, "/api/v1/users", body, nil)
require.Equal(t, http.StatusConflict, result.status)
}
func (s *RouterSuite) id(object map[string]any) string {
s.T().Helper()
func TestCreateSessionFromBasicAuth(t *testing.T) {
fixture := newRouterFixture(t)
value, ok := object["id"].(string)
s.Require().True(ok)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
session := domain.Session{Token: "opaque-token", ExpiresAt: time.Now().UTC().Add(time.Hour), User: user}
return value
}
fixture.sessions.EXPECT().Authenticate(mock.Anything, "alice", "very-secret-password").Return(user, nil).Once()
fixture.sessions.EXPECT().Create(mock.Anything, user).Return(session, nil).Once()
func (s *RouterSuite) TestHealthLive() {
resp := s.do(http.MethodGet, "/health/live", nil)
s.Equal(http.StatusOK, resp.status)
s.NotEmpty(resp.header.Get(requestIDHeader))
s.JSONEq(`{"status":"ok"}`, string(resp.body))
}
func (s *RouterSuite) TestHealthReady() {
resp := s.do(http.MethodGet, "/health/ready", nil)
s.Equal(http.StatusOK, resp.status)
s.NotEmpty(resp.header.Get(requestIDHeader))
s.JSONEq(`{"status":"ok"}`, string(resp.body))
}
func (s *RouterSuite) TestRequestIDEchoedFromClient() {
resp := s.do(http.MethodGet, "/health/live", map[string]string{
requestIDHeader: "from-client",
result := fixture.do(t, http.MethodPost, "/api/v1/auth/sessions", nil, map[string]string{
"Authorization": "Basic " + basic("alice", "very-secret-password"),
})
require.Equal(t, http.StatusCreated, result.status)
s.Equal("from-client", resp.header.Get(requestIDHeader))
var body struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
}
require.NoError(t, json.Unmarshal(result.body, &body))
require.Equal(t, "opaque-token", body.Token)
require.Equal(t, "Bearer", body.TokenType)
}
func (s *RouterSuite) TestUnauthorizedIsLoggedWithoutStacktrace() {
resp := s.do(http.MethodGet, "/api/v1/chats", nil)
func TestCreateSessionRejectsBadCredentials(t *testing.T) {
fixture := newRouterFixture(t)
fixture.sessions.EXPECT().Authenticate(mock.Anything, mock.Anything, mock.Anything).Return(domain.User{}, domain.ErrUnauthenticated).Once()
s.Equal(http.StatusUnauthorized, resp.status)
body := s.decodeError(resp)
s.Equal("unauthorized", body["code"])
s.Equal(resp.header.Get(requestIDHeader), body["request_id"])
s.NotEmpty(body["message"])
record := s.lastRecord()
s.Equal("request rejected", record["msg"])
s.Equal("warn", record["level"])
s.InEpsilon(float64(http.StatusUnauthorized), record["status"], 0.0001)
s.NotEmpty(record["request_id"])
s.NotContains(record, "stacktrace", "ожидаемый отказ не должен печатать стек")
}
func (s *RouterSuite) TestNotFoundReturnsContractError() {
resp := s.do(http.MethodGet, "/nope", nil)
s.Equal(http.StatusNotFound, resp.status)
s.Equal("application/json; charset=utf-8", resp.header.Get("Content-Type"))
body := s.decodeError(resp)
s.Equal("not_found", body["code"])
s.Equal(resp.header.Get(requestIDHeader), body["request_id"])
record := s.lastRecord()
s.Equal("request rejected", record["msg"])
s.Equal("warn", record["level"])
s.InEpsilon(float64(http.StatusNotFound), record["status"], 0.0001)
}
func (s *RouterSuite) TestMethodNotAllowedReturnsContractError() {
resp := s.do(http.MethodDelete, "/health/live", nil)
s.Equal(http.StatusMethodNotAllowed, resp.status)
s.Equal(http.MethodGet, resp.header.Get("Allow"))
body := s.decodeError(resp)
s.Equal("invalid_request", body["code"])
record := s.lastRecord()
s.Equal("request rejected", record["msg"])
s.InEpsilon(float64(http.StatusMethodNotAllowed), record["status"], 0.0001)
}
func (s *RouterSuite) TestMalformedUserIDIsRejected() {
resp := s.do(http.MethodGet, "/api/v1/chats", map[string]string{
userIDHeader: "not-a-uuid",
result := fixture.do(t, http.MethodPost, "/api/v1/auth/sessions", nil, map[string]string{
"Authorization": "Basic " + basic("alice", "wrong-password-value"),
})
s.Equal(http.StatusUnauthorized, resp.status)
s.Equal("unauthorized", s.decodeError(resp)["code"])
require.Equal(t, http.StatusUnauthorized, result.status)
require.Contains(t, result.header.Get("WWW-Authenticate"), "Basic")
}
func (s *RouterSuite) TestUnknownUserIDIsRejected() {
resp := s.do(http.MethodGet, "/api/v1/chats", map[string]string{
userIDHeader: "11111111-1111-4111-8111-111111111111",
})
func TestRevokeSession(t *testing.T) {
fixture := newRouterFixture(t)
s.Equal(http.StatusUnauthorized, resp.status,
"неизвестный пользователь не проходит идентификацию lab1")
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Once()
fixture.sessions.EXPECT().Revoke(mock.Anything, user.ID, "opaque-token").Return(nil).Once()
result := fixture.do(t, http.MethodDelete, "/api/v1/auth/sessions/current", nil, map[string]string{"Authorization": "Bearer opaque-token"})
require.Equal(t, http.StatusNoContent, result.status)
require.Empty(t, result.body)
}
func (s *RouterSuite) TestRegisterUserReturnsContractShape() {
resp := s.send(http.MethodPost, "/api/v1/users", map[string]string{
"username": "alice",
"display_name": "Алиса",
}, nil)
func TestCursorRoundTrip(t *testing.T) {
fixture := newRouterFixture(t)
s.Require().Equal(http.StatusCreated, resp.status)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
chatID := uuid.New()
message := domain.Message{ID: uuid.New(), ChatID: chatID, SenderID: user.ID, Text: "первое", CreatedAt: time.Now().UTC()}
body := s.decode(resp)
s.Equal("alice", body["username"])
s.Equal("Алиса", body["display_name"])
s.NotEmpty(body["id"])
s.NotEmpty(body["created_at"])
s.Len(body, 4, "User не содержит лишних полей")
}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
fixture.messages.EXPECT().
History(mock.Anything, user.ID, chatID, (*domain.Cursor)(nil), 1).
Return(domain.Page[domain.Message]{
Items: []domain.Message{message},
Next: &domain.Cursor{Scope: chatID, CreatedAt: message.CreatedAt, ID: message.ID},
}, nil).
Once()
func (s *RouterSuite) TestDuplicateUsernameConflicts() {
s.register("alice")
result := fixture.do(t, http.MethodGet, "/api/v1/chats/"+chatID.String()+"/messages?limit=1", nil, map[string]string{"Authorization": "Bearer opaque-token"})
require.Equal(t, http.StatusOK, result.status)
resp := s.send(http.MethodPost, "/api/v1/users", map[string]string{
"username": "alice",
"display_name": "Другая Алиса",
}, nil)
s.Equal(http.StatusConflict, resp.status)
s.Equal("conflict", s.decodeError(resp)["code"])
}
func (s *RouterSuite) TestRegisterRejectsInvalidPayload() {
tests := map[string]map[string]string{
"username в верхнем регистре": {"username": "Alice", "display_name": "Алиса"},
"слишком короткий username": {"username": "ab", "display_name": "Алиса"},
"пробельный display_name": {"username": "alice", "display_name": " "},
var body struct {
Items []json.RawMessage `json:"items"`
NextCursor *string `json:"next_cursor"`
}
require.NoError(t, json.Unmarshal(result.body, &body))
require.Len(t, body.Items, 1)
require.NotNil(t, body.NextCursor)
for name, payload := range tests {
s.Run(name, func() {
resp := s.send(http.MethodPost, "/api/v1/users", payload, nil)
fixture.messages.EXPECT().
History(mock.Anything, user.ID, chatID, mock.Anything, 1).
Return(domain.Page[domain.Message]{Items: []domain.Message{}}, nil).
Once()
s.Equal(http.StatusBadRequest, resp.status)
s.Equal("invalid_request", s.decodeError(resp)["code"])
})
}
}
// Контракт: "JSON с лишними полями или неверными типами — 400; malformed JSON также 400".
// Проверку выполняет сгенерированный слой, поэтому тест фиксирует границу, а не домен.
func (s *RouterSuite) TestRegisterRejectsMalformedBody() {
tests := map[string]string{
"лишнее поле": `{"username":"alice","display_name":"Алиса","is_admin":true}`,
"неверный тип": `{"username":"alice","display_name":42}`,
"битый json": `{"username":"alice",`,
"не объект": `"alice"`,
"пропущено поле": `{"username":"alice"}`,
}
for name, body := range tests {
s.Run(name, func() {
resp := s.sendRaw(http.MethodPost, "/api/v1/users", []byte(body), nil)
s.Equal(http.StatusBadRequest, resp.status)
s.Equal("invalid_request", s.decodeError(resp)["code"])
})
}
}
func (s *RouterSuite) TestCurrentUser() {
alice := s.register("alice")
resp := s.do(http.MethodGet, "/api/v1/users/me", s.actor(alice))
s.Require().Equal(http.StatusOK, resp.status)
s.Equal(alice, s.decode(resp))
}
func (s *RouterSuite) TestCreateChatRequiresCallerAsMember() {
alice := s.register("alice")
bob := s.register("bob")
resp := s.send(http.MethodPost, "/api/v1/chats", map[string]any{
"title": "Без создателя",
"member_ids": []string{s.id(bob)},
}, s.actor(alice))
s.Equal(http.StatusBadRequest, resp.status)
s.Equal("invalid_request", s.decodeError(resp)["code"])
}
func (s *RouterSuite) TestCreateChatRejectsUnknownMember() {
alice := s.register("alice")
resp := s.send(http.MethodPost, "/api/v1/chats", map[string]any{
"title": "Неизвестный участник",
"member_ids": []string{s.id(alice), "11111111-1111-4111-8111-111111111111"},
}, s.actor(alice))
s.Equal(http.StatusBadRequest, resp.status)
}
func (s *RouterSuite) TestCreateChatRejectsDuplicateMembers() {
alice := s.register("alice")
resp := s.send(http.MethodPost, "/api/v1/chats", map[string]any{
"title": "Дубликаты",
"member_ids": []string{s.id(alice), s.id(alice)},
}, s.actor(alice))
s.Equal(http.StatusBadRequest, resp.status)
}
func (s *RouterSuite) TestChatIsHiddenFromOutsider() {
alice := s.register("alice")
bob := s.register("bob")
eve := s.register("eve")
chat := s.createChat(alice, s.id(alice), s.id(bob))
resp := s.do(http.MethodGet, "/api/v1/chats/"+s.id(chat), s.actor(eve))
s.Equal(http.StatusNotFound, resp.status, "посторонний получает 404, а не 403")
resp = s.do(http.MethodGet, "/api/v1/chats/"+s.id(chat), s.actor(bob))
s.Equal(http.StatusOK, resp.status, "участник читает чат")
}
func (s *RouterSuite) TestListChatsShowsOnlyVisibleChats() {
alice := s.register("alice")
bob := s.register("bob")
eve := s.register("eve")
chat := s.createChat(alice, s.id(alice), s.id(bob))
resp := s.do(http.MethodGet, "/api/v1/chats", s.actor(bob))
s.Require().Equal(http.StatusOK, resp.status)
body := s.decode(resp)
items, ok := body["items"].([]any)
s.Require().True(ok)
s.Require().Len(items, 1)
s.Nil(body["next_cursor"])
first, ok := items[0].(map[string]any)
s.Require().True(ok)
s.Equal(s.id(chat), first["id"])
resp = s.do(http.MethodGet, "/api/v1/chats", s.actor(eve))
s.Require().Equal(http.StatusOK, resp.status)
body = s.decode(resp)
items, ok = body["items"].([]any)
s.Require().True(ok)
s.Empty(items, "чужой чат не попадает в список")
}
func (s *RouterSuite) TestSenderIsDerivedFromIdentity() {
alice := s.register("alice")
bob := s.register("bob")
chat := s.createChat(alice, s.id(alice), s.id(bob))
resp := s.send(http.MethodPost, "/api/v1/chats/"+s.id(chat)+"/messages", map[string]any{
"text": "Привет, мир 👋",
"sender_id": s.id(bob),
}, s.actor(alice))
s.Equal(http.StatusBadRequest, resp.status, "sender_id в запросе не принимается")
resp = s.send(http.MethodPost, "/api/v1/chats/"+s.id(chat)+"/messages", map[string]any{
"text": "Привет, мир 👋",
}, s.actor(alice))
s.Require().Equal(http.StatusCreated, resp.status)
body := s.decode(resp)
s.Equal(s.id(alice), body["sender_id"])
s.Equal(s.id(chat), body["chat_id"])
s.Equal("Привет, мир 👋", body["text"])
}
func (s *RouterSuite) TestMessageTextValidation() {
alice := s.register("alice")
chat := s.createChat(alice, s.id(alice))
path := "/api/v1/chats/" + s.id(chat) + "/messages"
tests := map[string]string{
"пустой текст": "",
"пробельный текст": " ",
"слишком длинный": strings.Repeat("я", 4001),
}
for name, text := range tests {
s.Run(name, func() {
resp := s.send(http.MethodPost, path, map[string]any{"text": text}, s.actor(alice))
s.Equal(http.StatusBadRequest, resp.status)
s.Equal("invalid_request", s.decodeError(resp)["code"])
})
}
}
func (s *RouterSuite) TestOutsiderCannotUseChat() {
alice := s.register("alice")
eve := s.register("eve")
chat := s.createChat(alice, s.id(alice))
path := "/api/v1/chats/" + s.id(chat) + "/messages"
resp := s.send(http.MethodPost, path, map[string]any{"text": "чужое"}, s.actor(eve))
s.Equal(http.StatusNotFound, resp.status)
resp = s.do(http.MethodGet, path, s.actor(eve))
s.Equal(http.StatusNotFound, resp.status)
}
func (s *RouterSuite) TestHistoryPaginationDoesNotRepeatItems() {
alice := s.register("alice")
chat := s.createChat(alice, s.id(alice))
path := "/api/v1/chats/" + s.id(chat) + "/messages"
const total = 5
for range total {
resp := s.send(http.MethodPost, path, map[string]any{"text": "сообщение"}, s.actor(alice))
s.Require().Equal(http.StatusCreated, resp.status)
}
seen := make(map[string]struct{}, total)
cursor := ""
for {
query := path + "?limit=2"
if cursor != "" {
query += "&cursor=" + url.QueryEscape(cursor)
}
resp := s.do(http.MethodGet, query, s.actor(alice))
s.Require().Equal(http.StatusOK, resp.status)
body := s.decode(resp)
items, ok := body["items"].([]any)
s.Require().True(ok)
for _, item := range items {
message, ok := item.(map[string]any)
s.Require().True(ok)
id, ok := message["id"].(string)
s.Require().True(ok)
_, duplicate := seen[id]
s.Require().False(duplicate, "страницы не повторяют сообщения")
seen[id] = struct{}{}
}
next, ok := body["next_cursor"].(string)
if !ok {
s.Nil(body["next_cursor"])
break
}
cursor = next
}
s.Len(seen, total)
}
func (s *RouterSuite) TestCursorFromAnotherChatIsRejected() {
alice := s.register("alice")
first := s.createChat(alice, s.id(alice))
second := s.createChat(alice, s.id(alice))
firstPath := "/api/v1/chats/" + s.id(first) + "/messages"
for range 2 {
resp := s.send(http.MethodPost, firstPath, map[string]any{"text": "сообщение"}, s.actor(alice))
s.Require().Equal(http.StatusCreated, resp.status)
}
resp := s.do(http.MethodGet, firstPath+"?limit=1", s.actor(alice))
s.Require().Equal(http.StatusOK, resp.status)
cursor, ok := s.decode(resp)["next_cursor"].(string)
s.Require().True(ok)
resp = s.do(
result = fixture.do(
t,
http.MethodGet,
"/api/v1/chats/"+s.id(second)+"/messages?cursor="+url.QueryEscape(cursor),
s.actor(alice),
"/api/v1/chats/"+chatID.String()+"/messages?limit=1&cursor="+*body.NextCursor,
nil,
map[string]string{"Authorization": "Bearer opaque-token"},
)
s.Equal(http.StatusBadRequest, resp.status, "cursor привязан к чату")
s.Equal("invalid_request", s.decodeError(resp)["code"])
require.Equal(t, http.StatusOK, result.status)
}
func (s *RouterSuite) TestInvalidCursorIsRejected() {
alice := s.register("alice")
chat := s.createChat(alice, s.id(alice))
func TestInvalidCursorIsRejected(t *testing.T) {
fixture := newRouterFixture(t)
resp := s.do(
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, mock.Anything).Return(user, nil).Maybe()
result := fixture.do(
t,
http.MethodGet,
"/api/v1/chats/"+s.id(chat)+"/messages?cursor=not-a-cursor",
s.actor(alice),
"/api/v1/chats/"+uuid.NewString()+"/messages?cursor=not-a-cursor",
nil,
map[string]string{"Authorization": "Bearer opaque-token"},
)
s.Equal(http.StatusBadRequest, resp.status)
require.Equal(t, http.StatusBadRequest, result.status)
}
func (s *RouterSuite) TestLimitOutOfRangeIsRejected() {
alice := s.register("alice")
chat := s.createChat(alice, s.id(alice))
func TestNotFoundAndMethodNotAllowed(t *testing.T) {
fixture := newRouterFixture(t)
for _, limit := range []string{"0", "101"} {
resp := s.do(
http.MethodGet,
"/api/v1/chats/"+s.id(chat)+"/messages?limit="+limit,
s.actor(alice),
)
result := fixture.do(t, http.MethodGet, "/nope", nil, nil)
require.Equal(t, http.StatusNotFound, result.status)
s.Equal(http.StatusBadRequest, resp.status)
}
}
func (s *RouterSuite) TestEmptyHistoryReturnsEmptyItems() {
alice := s.register("alice")
chat := s.createChat(alice, s.id(alice))
resp := s.do(http.MethodGet, "/api/v1/chats/"+s.id(chat)+"/messages", s.actor(alice))
s.Require().Equal(http.StatusOK, resp.status)
s.JSONEq(`{"items":[],"next_cursor":null}`, string(resp.body))
}
func (s *RouterSuite) TestSuccessfulRequestIsLogged() {
alice := s.register("alice")
s.sink.Reset()
resp := s.do(http.MethodGet, "/api/v1/users/me", s.actor(alice))
s.Require().Equal(http.StatusOK, resp.status)
records := s.records()
s.Require().Len(records, 2)
s.Equal("request accepted", records[0]["msg"])
s.Equal("request handled", records[1]["msg"])
s.NotEmpty(records[1]["duration"])
result = fixture.do(t, http.MethodDelete, "/health/live", nil, nil)
require.Equal(t, http.StatusMethodNotAllowed, result.status)
}