package rest import ( "bytes" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "strings" "testing" "github.com/stretchr/testify/suite" "mtusi-messenger/internal/logger" "mtusi-messenger/internal/service/chat" "mtusi-messenger/internal/service/message" "mtusi-messenger/internal/service/user" "mtusi-messenger/internal/storage/memory" ) const userIDHeader = "X-User-Id" type response struct { status int header http.Header body []byte } type RouterSuite struct { suite.Suite sink *strings.Builder log *slog.Logger server *httptest.Server } func TestRouterSuite(t *testing.T) { t.Parallel() suite.Run(t, new(RouterSuite)) } 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) } raw, err := json.Marshal(body) s.Require().NoError(err) return s.sendRaw(method, path, raw, headers) } func (s *RouterSuite) sendRaw(method, path string, body []byte, headers map[string]string) response { s.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) if body != nil { req.Header.Set("Content-Type", "application/json") } for key, value := range headers { req.Header.Set(key, value) } resp, err := s.server.Client().Do(req) s.Require().NoError(err) defer func() { _ = resp.Body.Close() }() payload, err := io.ReadAll(resp.Body) s.Require().NoError(err) return response{status: resp.StatusCode, header: resp.Header, body: payload} } func (s *RouterSuite) records() []map[string]any { s.T().Helper() var out []map[string]any 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 } func (s *RouterSuite) lastRecord() map[string]any { s.T().Helper() records := s.records() s.Require().NotEmpty(records) return records[len(records)-1] } func (s *RouterSuite) decodeError(resp response) map[string]any { s.T().Helper() var body struct { Error map[string]any `json:"error"` } s.Require().NoError(json.Unmarshal(resp.body, &body)) s.Require().NotEmpty(body.Error) return body.Error } func (s *RouterSuite) decode(resp response) map[string]any { s.T().Helper() var body map[string]any s.Require().NoError(json.Unmarshal(resp.body, &body)) return body } func (s *RouterSuite) register(username string) map[string]any { s.T().Helper() 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) } func (s *RouterSuite) actor(user map[string]any) map[string]string { s.T().Helper() id, ok := user["id"].(string) s.Require().True(ok) return map[string]string{userIDHeader: id} } func (s *RouterSuite) createChat(owner map[string]any, members ...string) map[string]any { s.T().Helper() 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)) return s.decode(resp) } func (s *RouterSuite) id(object map[string]any) string { s.T().Helper() value, ok := object["id"].(string) s.Require().True(ok) return value } 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", }) s.Equal("from-client", resp.header.Get(requestIDHeader)) } func (s *RouterSuite) TestUnauthorizedIsLoggedWithoutStacktrace() { resp := s.do(http.MethodGet, "/api/v1/chats", nil) 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", }) s.Equal(http.StatusUnauthorized, resp.status) s.Equal("unauthorized", s.decodeError(resp)["code"]) } func (s *RouterSuite) TestUnknownUserIDIsRejected() { resp := s.do(http.MethodGet, "/api/v1/chats", map[string]string{ userIDHeader: "11111111-1111-4111-8111-111111111111", }) s.Equal(http.StatusUnauthorized, resp.status, "неизвестный пользователь не проходит идентификацию lab1") } func (s *RouterSuite) TestRegisterUserReturnsContractShape() { resp := s.send(http.MethodPost, "/api/v1/users", map[string]string{ "username": "alice", "display_name": "Алиса", }, nil) s.Require().Equal(http.StatusCreated, resp.status) 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 не содержит лишних полей") } func (s *RouterSuite) TestDuplicateUsernameConflicts() { s.register("alice") 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": " "}, } for name, payload := range tests { s.Run(name, func() { resp := s.send(http.MethodPost, "/api/v1/users", payload, nil) 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( http.MethodGet, "/api/v1/chats/"+s.id(second)+"/messages?cursor="+url.QueryEscape(cursor), s.actor(alice), ) s.Equal(http.StatusBadRequest, resp.status, "cursor привязан к чату") s.Equal("invalid_request", s.decodeError(resp)["code"]) } func (s *RouterSuite) TestInvalidCursorIsRejected() { alice := s.register("alice") chat := s.createChat(alice, s.id(alice)) resp := s.do( http.MethodGet, "/api/v1/chats/"+s.id(chat)+"/messages?cursor=not-a-cursor", s.actor(alice), ) s.Equal(http.StatusBadRequest, resp.status) } func (s *RouterSuite) TestLimitOutOfRangeIsRejected() { alice := s.register("alice") chat := s.createChat(alice, s.id(alice)) for _, limit := range []string{"0", "101"} { resp := s.do( http.MethodGet, "/api/v1/chats/"+s.id(chat)+"/messages?limit="+limit, s.actor(alice), ) 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"]) }