Files
mtusi2026lab2/internal/api/server_test.go
T

410 lines
13 KiB
Go

package api
import (
"bytes"
"encoding/base64"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"messenger/internal/store"
)
func newServer(t *testing.T) (*httptest.Server, *API, *bytes.Buffer) {
t.Helper()
var logs bytes.Buffer
st := store.New()
application := New(st, slog.New(slog.NewJSONHandler(&logs, nil)))
srv := httptest.NewServer(application)
t.Cleanup(srv.Close)
return srv, application, &logs
}
func do(t *testing.T, method, url, user string, body any, raw []byte, contentType string) (int, http.Header, []byte) {
t.Helper()
var rdr io.Reader
if raw != nil {
rdr = bytes.NewReader(raw)
} else if body != nil {
b, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
rdr = bytes.NewReader(b)
}
req, err := http.NewRequest(method, url, rdr)
if err != nil {
t.Fatal(err)
}
if body != nil || raw != nil {
if contentType == "" {
contentType = "application/json"
}
req.Header.Set("Content-Type", contentType)
}
if user != "" {
req.Header.Set("X-User-Id", user)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if resp.Header.Get("X-Request-Id") == "" {
t.Fatalf("%s %s: missing X-Request-Id", method, url)
}
if resp.StatusCode >= 400 {
var env errorEnvelope
if err := json.Unmarshal(data, &env); err != nil {
t.Fatalf("error json: %v body %s", err, data)
}
if env.Error.RequestID != resp.Header.Get("X-Request-Id") || env.Error.Code == "" || env.Error.Message == "" {
t.Fatalf("bad error envelope: %+v", env)
}
}
return resp.StatusCode, resp.Header, data
}
func createUser(t *testing.T, base, username, display string) userJSON {
t.Helper()
status, _, body := do(t, http.MethodPost, base+"/api/v1/users", "", map[string]string{
"username": username, "display_name": display,
}, nil, "")
if status != http.StatusCreated {
t.Fatalf("create user %s: %d %s", username, status, body)
}
var u userJSON
if err := json.Unmarshal(body, &u); err != nil {
t.Fatal(err)
}
return u
}
func createChat(t *testing.T, base, caller, title string, members ...string) chatJSON {
t.Helper()
status, _, body := do(t, http.MethodPost, base+"/api/v1/chats", caller, map[string]any{
"title": title, "member_ids": members,
}, nil, "")
if status != http.StatusCreated {
t.Fatalf("create chat: %d %s", status, body)
}
var c chatJSON
if err := json.Unmarshal(body, &c); err != nil {
t.Fatal(err)
}
return c
}
func TestInvalidJSONExtraFieldAndTypes(t *testing.T) {
srv, _, _ := newServer(t)
cases := [][]byte{
[]byte(`{`),
[]byte(`{"username":"abc","display_name":"Алиса","extra":1}`),
[]byte(`{"username":1,"display_name":"Алиса"}`),
[]byte(`null`),
}
for _, raw := range cases {
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, raw, "application/json")
if status != http.StatusBadRequest || !bytes.Contains(body, []byte(`"invalid_request"`)) {
t.Fatalf("body %s: %d %s", raw, status, body)
}
}
status, _, _ := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, []byte(`{"username":"abc","display_name":"Алиса"}`), "text/plain")
if status != http.StatusUnsupportedMediaType {
t.Fatalf("content type: %d", status)
}
}
func TestStrictJSONNamesUTF8AndCursorTail(t *testing.T) {
srv, _, _ := newServer(t)
bad := [][]byte{
[]byte(`{"username":"bad_json","display_name":"Я"}]`),
[]byte(`{"username":"bad_json","display_name":"Я"}}`),
[]byte(`{"Username":"bad_case","display_name":"Я"}`),
append([]byte(`{"username":"bad_utf","display_name":"`), 0xff, '"', '}'),
}
for _, raw := range bad {
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, raw, "application/json")
if status != http.StatusBadRequest {
t.Fatalf("user body %q: %d %s", raw, status, body)
}
}
alice := createUser(t, srv.URL, "alice", "Алиса")
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats", alice.ID, nil, []byte(`{"Title":"чат","member_ids":["`+alice.ID+`"]}`), "application/json")
if status != http.StatusBadRequest {
t.Fatalf("Title: %d %s", status, body)
}
chat := createChat(t, srv.URL, alice.ID, "чат", alice.ID)
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, []byte(`{"TEXT":"hi"}`), "application/json")
if status != http.StatusBadRequest {
t.Fatalf("TEXT: %d %s", status, body)
}
rawText := append([]byte(`{"text":"`), 0xff, '"', '}')
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, rawText, "application/json")
if status != http.StatusBadRequest {
t.Fatalf("message utf-8: %d %s", status, body)
}
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "one"}, nil, "")
if status != http.StatusCreated {
t.Fatalf("seed: %d %s", status, body)
}
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "two"}, nil, "")
if status != http.StatusCreated {
t.Fatalf("seed2: %d %s", status, body)
}
status, _, body = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil, "")
if status != http.StatusOK {
t.Fatalf("page: %d %s", status, body)
}
var page messagePage
if err := json.Unmarshal(body, &page); err != nil || page.NextCursor == nil {
t.Fatalf("cursor: %v %s", err, body)
}
decoded, err := base64.RawURLEncoding.DecodeString(*page.NextCursor)
if err != nil {
t.Fatal(err)
}
tampered := base64.RawURLEncoding.EncodeToString(append(decoded, []byte("garbage")...))
status, _, body = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(tampered), alice.ID, nil, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("tampered cursor: %d %s", status, body)
}
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(*page.NextCursor), alice.ID, nil, nil, "")
if status != http.StatusOK {
t.Fatalf("valid cursor: %d", status)
}
}
func TestDuplicateUsername(t *testing.T) {
srv, _, _ := newServer(t)
createUser(t, srv.URL, "alice", "Алиса")
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", map[string]string{
"username": "alice", "display_name": "Другая",
}, nil, "")
if status != http.StatusConflict || !bytes.Contains(body, []byte(`"conflict"`)) {
t.Fatalf("duplicate: %d %s", status, body)
}
}
func TestEmptyMessageForeignChatAndAuth(t *testing.T) {
srv, _, _ := newServer(t)
alice := createUser(t, srv.URL, "alice", "Алиса")
bob := createUser(t, srv.URL, "bob", "Боб")
eve := createUser(t, srv.URL, "eve", "Ева")
chat := createChat(t, srv.URL, alice.ID, "Контрактный тест", alice.ID, bob.ID)
status, _, _ := do(t, http.MethodGet, srv.URL+"/api/v1/users/me", "", nil, nil, "")
if status != http.StatusUnauthorized {
t.Fatalf("missing header: %d", status)
}
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/users/me", "11111111-1111-4111-8111-111111111111", nil, nil, "")
if status != http.StatusUnauthorized {
t.Fatalf("unknown user: %d", status)
}
meStatus, _, meBody := do(t, http.MethodGet, srv.URL+"/api/v1/users/me", alice.ID, nil, nil, "")
if meStatus != http.StatusOK || !bytes.Contains(meBody, []byte(alice.ID)) {
t.Fatalf("me: %d %s", meStatus, meBody)
}
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID, eve.ID, nil, nil, "")
if status != http.StatusNotFound {
t.Fatalf("foreign chat: %d", status)
}
status, _, _ = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", eve.ID, map[string]string{"text": "чужое"}, nil, "")
if status != http.StatusNotFound {
t.Fatalf("foreign post: %d", status)
}
for _, text := range []string{"", " ", "\n\t"} {
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("empty %q: %d %s", text, status, body)
}
}
status, _, _ = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "привет", "sender_id": eve.ID}, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("sender_id must be rejected: %d", status)
}
text := "Привет, мир 👋"
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
if status != http.StatusCreated {
t.Fatalf("unicode: %d %s", status, body)
}
var msg messageJSON
if err := json.Unmarshal(body, &msg); err != nil {
t.Fatal(err)
}
if msg.Text != text || msg.SenderID != alice.ID || msg.ChatID != chat.ID {
t.Fatalf("message mutated: %+v", msg)
}
if !strings.HasSuffix(msg.CreatedAt, "Z") {
t.Fatalf("timestamp: %s", msg.CreatedAt)
}
}
func TestPaginationSeveralPages(t *testing.T) {
srv, _, _ := newServer(t)
alice := createUser(t, srv.URL, "alice", "Алиса")
bob := createUser(t, srv.URL, "bob", "Боб")
chat := createChat(t, srv.URL, alice.ID, "страницы", alice.ID, bob.ID)
other := createChat(t, srv.URL, alice.ID, "другой", alice.ID)
const n = 25
ids := make([]string, 0, n)
for i := 0; i < n; i++ {
sender := alice.ID
if i%2 == 1 {
sender = bob.ID
}
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", sender, map[string]string{
"text": "сообщение " + strings.Repeat("я", i%3) + string(rune('a'+i%26)),
}, nil, "")
if status != http.StatusCreated {
t.Fatalf("post %d: %d %s", i, status, body)
}
var msg messageJSON
if err := json.Unmarshal(body, &msg); err != nil {
t.Fatal(err)
}
ids = append(ids, msg.ID)
}
var got []string
cursor := ""
pages := 0
for {
pages++
if pages > 10 {
t.Fatal("pagination did not finish")
}
url := srv.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=10"
if cursor != "" {
url += "&cursor=" + cursor
}
status, _, body := do(t, http.MethodGet, url, bob.ID, nil, nil, "")
if status != http.StatusOK {
t.Fatalf("page: %d %s", status, body)
}
var page messagePage
if err := json.Unmarshal(body, &page); err != nil {
t.Fatal(err)
}
if len(page.Items) == 0 || len(page.Items) > 10 {
t.Fatalf("page size %d", len(page.Items))
}
for _, item := range page.Items {
got = append(got, item.ID)
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
}
if pages < 3 {
t.Fatalf("expected several pages, got %d", pages)
}
if strings.Join(got, ",") != strings.Join(ids, ",") {
t.Fatalf("order/duplication mismatch\nwant %v\ngot %v", ids, got)
}
status, _, _ := do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+other.ID+"/messages?limit=10&cursor="+cursor, alice.ID, nil, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("foreign cursor: %d", status)
}
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=0", alice.ID, nil, nil, "")
if status != http.StatusBadRequest {
t.Fatalf("limit 0: %d", status)
}
}
func TestConcurrentHundredMessages(t *testing.T) {
srv, _, _ := newServer(t)
users := make([]userJSON, 10)
ids := make([]string, 10)
for i := 0; i < 10; i++ {
users[i] = createUser(t, srv.URL, "u"+string(rune('a'+i))+"x", "Участник")
ids[i] = users[i].ID
}
chat := createChat(t, srv.URL, ids[0], "гонка", ids...)
var wg sync.WaitGroup
errCh := make(chan error, 100)
for i := 0; i < 10; i++ {
wg.Add(1)
go func(user string) {
defer wg.Done()
for j := 0; j < 10; j++ {
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", strings.NewReader(`{"text":"n"}`))
if err != nil {
errCh <- err
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User-Id", user)
resp, err := http.DefaultClient.Do(req)
if err != nil {
errCh <- err
return
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
errCh <- &statusErr{resp.StatusCode, body}
}
}
}(ids[i])
}
wg.Wait()
close(errCh)
for err := range errCh {
t.Fatal(err)
}
seen := map[string]struct{}{}
cursor := ""
for {
url := srv.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=17"
if cursor != "" {
url += "&cursor=" + cursor
}
status, _, body := do(t, http.MethodGet, url, ids[3], nil, nil, "")
if status != http.StatusOK {
t.Fatalf("list: %d %s", status, body)
}
var page messagePage
if err := json.Unmarshal(body, &page); err != nil {
t.Fatal(err)
}
for _, item := range page.Items {
if _, ok := seen[item.ID]; ok {
t.Fatalf("duplicate %s", item.ID)
}
seen[item.ID] = struct{}{}
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
}
if len(seen) != 100 {
t.Fatalf("unique messages = %d, want 100", len(seen))
}
}
type statusErr struct {
code int
body []byte
}
func (e *statusErr) Error() string {
return http.StatusText(e.code) + " " + string(e.body)
}