package http import ( "fmt" "net/http" "net/url" "testing" ) func TestPagination_MultiPageWalk(t *testing.T) { r := newTestRig(t) alice, bob, _, chat := bootstrap(r) const total = 7 var sentIDs []string for i := 0; i < total; i++ { actor := alice if i%2 == 1 { actor = bob } _, msg := r.sendMessage(actor, chat.ID, fmt.Sprintf("page-%02d", i)) if msg.ID == "" { t.Fatalf("send message %d failed", i) } sentIDs = append(sentIDs, msg.ID) } history, pages := r.listMessages(alice, chat.ID, 3) if pages != 3 { t.Fatalf("ожидалось 3 страницы (3+3+1), получено %d", pages) } if len(history) != total { t.Fatalf("собрано %d сообщений, ожидалось %d", len(history), total) } for i, m := range history { if m.ID != sentIDs[i] { t.Fatalf("позиция %d: ожидался %s, получен %s (повтор, пропуск или нарушен порядок)", i, sentIDs[i], m.ID) } } } func TestPagination_ExactPageAndEmptyChat(t *testing.T) { r := newTestRig(t) alice, _, _, chat := bootstrap(r) history, pages := r.listMessages(alice, chat.ID, 5) if len(history) != 0 || pages != 1 { t.Fatalf("пустой чат: items=%d pages=%d", len(history), pages) } for i := 0; i < 4; i++ { r.send(alice, chat.ID, fmt.Sprintf("m%d", i)) } if _, pages := r.listMessages(alice, chat.ID, 4); pages != 1 { t.Fatalf("4 сообщения при limit=4: ожидалась 1 страница, получено %d", pages) } if _, pages := r.listMessages(alice, chat.ID, 2); pages != 2 { t.Fatalf("4 сообщения при limit=2: ожидалось 2 страницы, получено %d", pages) } } func TestPagination_CursorBoundToChat(t *testing.T) { r := newTestRig(t) alice, bob, _, chat := bootstrap(r) other := r.createChat(alice, "Другой", alice.ID, bob.ID) for i := 0; i < 3; i++ { r.send(alice, chat.ID, fmt.Sprintf("m%d", i)) } resp := r.do(http.MethodGet, "/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil) expectStatus(t, resp, http.StatusOK) var page struct { NextCursor *string `json:"next_cursor"` } readJSON(t, resp, &page) if page.NextCursor == nil { t.Fatal("ожидался next_cursor") } for _, path := range []string{ "/api/v1/chats/" + other.ID + "/messages?cursor=" + url.QueryEscape(*page.NextCursor), "/api/v1/chats?cursor=" + url.QueryEscape(*page.NextCursor), "/api/v1/chats/" + chat.ID + "/messages?cursor=not-a-cursor", } { resp := r.do(http.MethodGet, path, alice.ID, nil, nil) expectStatus(t, resp, http.StatusBadRequest) resp.Body.Close() } }