package studenttests import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "os" "strings" "sync" "testing" "time" "mtusi2026lab1/internal/api" "mtusi2026lab1/internal/store" ) func testAPI(t *testing.T) *httptest.Server { t.Helper() _ = os.Setenv("APP_ACCESS_LOG", "0") return httptest.NewServer(api.New(store.New()).Routes()) } func post(t *testing.T, c *http.Client, url string, body any, hdr map[string]string) (int, map[string]any, http.Header) { t.Helper() var raw []byte if body != nil { var err error raw, err = json.Marshal(body) if err != nil { t.Fatal(err) } } req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(raw)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") for k, v := range hdr { req.Header.Set(k, v) } resp, err := c.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) var out map[string]any _ = json.Unmarshal(data, &out) return resp.StatusCode, out, resp.Header } func get(t *testing.T, c *http.Client, url string, hdr map[string]string) (int, map[string]any, http.Header) { t.Helper() req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { t.Fatal(err) } for k, v := range hdr { req.Header.Set(k, v) } resp, err := c.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) var out map[string]any _ = json.Unmarshal(data, &out) return resp.StatusCode, out, resp.Header } func register(t *testing.T, c *http.Client, base, username string) map[string]any { t.Helper() st, body, _ := post(t, c, base+"/api/v1/users", map[string]any{ "username": username, "display_name": "User " + username, }, nil) if st != 201 { t.Fatalf("register %q: %d %#v", username, st, body) } return body } func TestMalformedJSON(t *testing.T) { srv := testAPI(t) defer srv.Close() req, _ := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/users", strings.NewReader("{broken")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.StatusCode != 400 { t.Fatalf("want 400, got %d", resp.StatusCode) } if resp.Header.Get("X-Request-Id") == "" { t.Fatal("missing X-Request-Id") } } func TestDuplicateUsername(t *testing.T) { srv := testAPI(t) defer srv.Close() c := srv.Client() register(t, c, srv.URL, "dup_u01") st, _, _ := post(t, c, srv.URL+"/api/v1/users", map[string]any{ "username": "dup_u01", "display_name": "again", }, nil) if st != 409 { t.Fatalf("want 409, got %d", st) } } func TestEmptyMessage(t *testing.T) { srv := testAPI(t) defer srv.Close() c := srv.Client() u := register(t, c, srv.URL, "empty_u") uid := u["id"].(string) st, chat, _ := post(t, c, srv.URL+"/api/v1/chats", map[string]any{ "title": "solo", "member_ids": []string{uid}, }, map[string]string{"X-User-Id": uid}) if st != 201 { t.Fatalf("chat: %d", st) } chatID := chat["id"].(string) st, _, _ = post(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages", map[string]any{"text": " "}, map[string]string{"X-User-Id": uid}) if st != 400 { t.Fatalf("want 400, got %d", st) } } func TestForeignChat(t *testing.T) { srv := testAPI(t) defer srv.Close() c := srv.Client() a := register(t, c, srv.URL, "alice_f") e := register(t, c, srv.URL, "eve_f") aid := a["id"].(string) eid := e["id"].(string) st, chat, _ := post(t, c, srv.URL+"/api/v1/chats", map[string]any{ "title": "secret", "member_ids": []string{aid}, }, map[string]string{"X-User-Id": aid}) if st != 201 { t.Fatal(st) } st, _, _ = get(t, c, srv.URL+"/api/v1/chats/"+chat["id"].(string), map[string]string{"X-User-Id": eid}) if st != 404 { t.Fatalf("want 404, got %d", st) } } func TestPaginationPages(t *testing.T) { srv := testAPI(t) defer srv.Close() c := srv.Client() u := register(t, c, srv.URL, "page_u") uid := u["id"].(string) st, chat, _ := post(t, c, srv.URL+"/api/v1/chats", map[string]any{ "title": "p", "member_ids": []string{uid}, }, map[string]string{"X-User-Id": uid}) if st != 201 { t.Fatal(st) } chatID := chat["id"].(string) for i := 0; i < 3; i++ { st, _, _ = post(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages", map[string]any{"text": fmt.Sprintf("msg-%d", i)}, map[string]string{"X-User-Id": uid}) if st != 201 { t.Fatalf("msg %d: %d", i, st) } } st, page1, _ := get(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages?limit=2", map[string]string{"X-User-Id": uid}) if st != 200 { t.Fatal(st) } items1 := page1["items"].([]any) if len(items1) != 2 || page1["next_cursor"] == nil { t.Fatalf("page1: %#v", page1) } cursor := page1["next_cursor"].(string) st, page2, _ := get(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages?limit=2&cursor="+cursor, map[string]string{"X-User-Id": uid}) if st != 200 { t.Fatal(st) } items2 := page2["items"].([]any) if len(items2) != 1 || page2["next_cursor"] != nil { t.Fatalf("page2: %#v", page2) } seen := map[string]struct{}{} for _, page := range [][]any{items1, items2} { for _, it := range page { id := it.(map[string]any)["id"].(string) if _, dup := seen[id]; dup { t.Fatalf("duplicate %s", id) } seen[id] = struct{}{} } } if len(seen) != 3 { t.Fatalf("want 3 ids, got %d", len(seen)) } } func TestConcurrentHundredMessages(t *testing.T) { srv := testAPI(t) defer srv.Close() c := srv.Client() users := make([]map[string]any, 10) ids := make([]string, 10) for i := 0; i < 10; i++ { users[i] = register(t, c, srv.URL, fmt.Sprintf("race_%02d", i)) ids[i] = users[i]["id"].(string) } st, chat, _ := post(t, c, srv.URL+"/api/v1/chats", map[string]any{ "title": "race", "member_ids": ids, }, map[string]string{"X-User-Id": ids[0]}) if st != 201 { t.Fatal(st) } chatID := chat["id"].(string) var wg sync.WaitGroup msgIDs := make(chan string, 100) errs := make(chan error, 100) start := time.Now() for i := 0; i < 10; i++ { uid := ids[i] for j := 0; j < 10; j++ { wg.Add(1) go func(user string, n int) { defer wg.Done() st, body, _ := post(t, c, srv.URL+"/api/v1/chats/"+chatID+"/messages", map[string]any{"text": fmt.Sprintf("c-%s-%d", user[:8], n)}, map[string]string{"X-User-Id": user}) if st != 201 { errs <- fmt.Errorf("status=%d", st) return } msgIDs <- body["id"].(string) }(uid, j) } } wg.Wait() close(msgIDs) close(errs) for err := range errs { t.Fatal(err) } uniq := map[string]struct{}{} for id := range msgIDs { uniq[id] = struct{}{} } t.Logf("elapsed=%s unique=%d", time.Since(start), len(uniq)) if len(uniq) != 100 { t.Fatalf("want 100 unique messages, got %d", len(uniq)) } }