forked from mtusi2026/mtusi2026lab2
238 lines
6.9 KiB
Go
238 lines
6.9 KiB
Go
package handler_test
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"messenger/internal/handler"
|
|
"messenger/internal/repository/memory"
|
|
"messenger/internal/router"
|
|
"messenger/internal/service"
|
|
)
|
|
|
|
func newServer(t *testing.T) *httptest.Server {
|
|
t.Helper()
|
|
store := memory.New()
|
|
users := service.NewUserService(store)
|
|
chats := service.NewChatService(store)
|
|
messages := service.NewMessageService(chats, store)
|
|
srv := httptest.NewServer(router.New(handler.New(users, chats, messages, slog.New(slog.DiscardHandler))))
|
|
t.Cleanup(srv.Close)
|
|
return srv
|
|
}
|
|
|
|
func do(t *testing.T, srv *httptest.Server, method, path, userID, body string) (int, map[string]any) {
|
|
t.Helper()
|
|
req, err := http.NewRequest(method, srv.URL+path, strings.NewReader(body))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if body != "" {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if userID != "" {
|
|
req.Header.Set("X-User-Id", userID)
|
|
}
|
|
resp, err := srv.Client().Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
var out map[string]any
|
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
|
t.Fatalf("%s %s: invalid JSON response: %v", method, path, err)
|
|
}
|
|
return resp.StatusCode, out
|
|
}
|
|
|
|
func errorCode(body map[string]any) string {
|
|
e, _ := body["error"].(map[string]any)
|
|
code, _ := e["code"].(string)
|
|
return code
|
|
}
|
|
|
|
func createUser(t *testing.T, srv *httptest.Server, username string) string {
|
|
t.Helper()
|
|
status, body := do(t, srv, http.MethodPost, "/api/v1/users", "",
|
|
fmt.Sprintf(`{"username":%q,"display_name":"Test"}`, username))
|
|
if status != http.StatusCreated {
|
|
t.Fatalf("create user %s: status %d", username, status)
|
|
}
|
|
return body["id"].(string)
|
|
}
|
|
|
|
func createChat(t *testing.T, srv *httptest.Server, owner string, members ...string) string {
|
|
t.Helper()
|
|
ids, _ := json.Marshal(members)
|
|
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner,
|
|
fmt.Sprintf(`{"title":"Test","member_ids":%s}`, ids))
|
|
if status != http.StatusCreated {
|
|
t.Fatalf("create chat: status %d", status)
|
|
}
|
|
return body["id"].(string)
|
|
}
|
|
|
|
func TestInvalidJSON(t *testing.T) {
|
|
srv := newServer(t)
|
|
for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x"}`} {
|
|
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", body)
|
|
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
|
|
t.Errorf("body %q: got %d %q, want 400 invalid_request", body, status, errorCode(resp))
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestForeignChat(t *testing.T) {
|
|
srv := newServer(t)
|
|
alice := createUser(t, srv, "alice")
|
|
bob := createUser(t, srv, "bob")
|
|
eve := createUser(t, srv, "eve")
|
|
chat := createChat(t, srv, alice, alice, bob)
|
|
|
|
cases := []struct{ method, path, body string }{
|
|
{http.MethodGet, "/api/v1/chats/" + chat, ""},
|
|
{http.MethodGet, "/api/v1/chats/" + chat + "/messages", ""},
|
|
{http.MethodPost, "/api/v1/chats/" + chat + "/messages", `{"text":"hi"}`},
|
|
}
|
|
for _, c := range cases {
|
|
status, resp := do(t, srv, c.method, c.path, eve, c.body)
|
|
if status != http.StatusNotFound || errorCode(resp) != "not_found" {
|
|
t.Errorf("%s %s by outsider: got %d, want 404", c.method, c.path, status)
|
|
}
|
|
}
|
|
|
|
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve, "")
|
|
if status != http.StatusOK || len(resp["items"].([]any)) != 0 {
|
|
t.Errorf("outsider chat list: got %d %v, want 200 with no items", status, resp["items"])
|
|
}
|
|
}
|
|
|
|
func TestEmptyMessage(t *testing.T) {
|
|
srv := newServer(t)
|
|
alice := createUser(t, srv, "alice")
|
|
chat := createChat(t, srv, alice, alice)
|
|
|
|
for _, text := range []string{"", " ", "\n\t"} {
|
|
body, _ := json.Marshal(map[string]string{"text": text})
|
|
status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, string(body))
|
|
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
|
|
t.Errorf("text %q: got %d, want 400", text, status)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestDuplicateUsername(t *testing.T) {
|
|
srv := newServer(t)
|
|
createUser(t, srv, "alice")
|
|
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Other"}`)
|
|
if status != http.StatusConflict || errorCode(resp) != "conflict" {
|
|
t.Errorf("got %d %q, want 409 conflict", status, errorCode(resp))
|
|
}
|
|
}
|
|
|
|
func TestPaginationMultiplePages(t *testing.T) {
|
|
srv := newServer(t)
|
|
alice := createUser(t, srv, "alice")
|
|
chat := createChat(t, srv, alice, alice)
|
|
|
|
const total, limit = 7, 3
|
|
for i := range total {
|
|
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, fmt.Sprintf(`{"text":"msg %d"}`, i))
|
|
if status != http.StatusCreated {
|
|
t.Fatalf("send message %d: status %d", i, status)
|
|
}
|
|
}
|
|
|
|
seen := map[string]bool{}
|
|
pages := 0
|
|
prevCreatedAt := ""
|
|
cursor := ""
|
|
for {
|
|
path := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chat, limit)
|
|
if cursor != "" {
|
|
path += "&cursor=" + cursor
|
|
}
|
|
status, resp := do(t, srv, http.MethodGet, path, alice, "")
|
|
if status != http.StatusOK {
|
|
t.Fatalf("page %d: status %d", pages+1, status)
|
|
}
|
|
pages++
|
|
for _, it := range resp["items"].([]any) {
|
|
m := it.(map[string]any)
|
|
id, createdAt := m["id"].(string), m["created_at"].(string)
|
|
if seen[id] {
|
|
t.Errorf("message %s returned twice", id)
|
|
}
|
|
if createdAt < prevCreatedAt {
|
|
t.Errorf("messages out of order: %s after %s", createdAt, prevCreatedAt)
|
|
}
|
|
seen[id] = true
|
|
prevCreatedAt = createdAt
|
|
}
|
|
next, ok := resp["next_cursor"].(string)
|
|
if !ok {
|
|
break
|
|
}
|
|
cursor = next
|
|
}
|
|
|
|
if len(seen) != total {
|
|
t.Errorf("got %d messages, want %d", len(seen), total)
|
|
}
|
|
if want := (total + limit - 1) / limit; pages != want {
|
|
t.Errorf("got %d pages, want %d", pages, want)
|
|
}
|
|
}
|
|
|
|
func TestConcurrentMessages(t *testing.T) {
|
|
srv := newServer(t)
|
|
const clients, perClient = 10, 10
|
|
|
|
users := make([]string, clients)
|
|
for i := range users {
|
|
users[i] = createUser(t, srv, fmt.Sprintf("client_%d", i))
|
|
}
|
|
chat := createChat(t, srv, users[0], users...)
|
|
|
|
var wg sync.WaitGroup
|
|
errs := make(chan error, clients*perClient)
|
|
for c, user := range users {
|
|
wg.Go(func() {
|
|
for i := range perClient {
|
|
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user,
|
|
fmt.Sprintf(`{"text":"client %d msg %d"}`, c, i))
|
|
if status != http.StatusCreated {
|
|
errs <- fmt.Errorf("client %d msg %d: status %d", c, i, status)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
wg.Wait()
|
|
close(errs)
|
|
for err := range errs {
|
|
t.Error(err)
|
|
}
|
|
|
|
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0], "")
|
|
if status != http.StatusOK {
|
|
t.Fatalf("read history: status %d", status)
|
|
}
|
|
items := resp["items"].([]any)
|
|
ids := map[string]bool{}
|
|
for _, it := range items {
|
|
ids[it.(map[string]any)["id"].(string)] = true
|
|
}
|
|
if len(items) != clients*perClient || len(ids) != clients*perClient {
|
|
t.Errorf("got %d messages (%d unique), want %d", len(items), len(ids), clients*perClient)
|
|
}
|
|
if resp["next_cursor"] != nil {
|
|
t.Errorf("next_cursor = %v, want null", resp["next_cursor"])
|
|
}
|
|
}
|