forked from mtusi2026/mtusi2026lab7
60 lines
2.1 KiB
Go
60 lines
2.1 KiB
Go
package tests
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func TestListPageByChatUsesCursorAndLimit(t *testing.T) {
|
|
f := newTestFixture(t)
|
|
user, _ := createTestUser(t, f.users, "alice", "Алиса")
|
|
chat := createTestChat(t, f.chats, "Пагинация", []string{user.ID})
|
|
other := createTestChat(t, f.chats, "Другой чат", []string{user.ID})
|
|
createTestMessage(t, f.messages, other.ID, user.ID, "Не должно попасть в страницу")
|
|
createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC)
|
|
ids := []string{
|
|
"00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000002",
|
|
"00000000-0000-4000-8000-000000000003", "00000000-0000-4000-8000-000000000004",
|
|
}
|
|
// Insert in reverse order to exercise SQL ordering, including equal timestamps.
|
|
for i := len(ids) - 1; i >= 0; i-- {
|
|
at := createdAt
|
|
if i > 1 {
|
|
at = at.Add(time.Duration(i-1) * time.Second)
|
|
}
|
|
_, err := f.db.Exec(context.Background(), "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", ids[i], chat.ID, user.ID, "message", at)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
first, more, err := f.messages.ListPageByChat(context.Background(), chat.ID, nil, 2)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !more || len(first) != 2 || first[0].ID != ids[0] || first[1].ID != ids[1] {
|
|
t.Fatalf("unexpected first page: %v, more=%v", first, more)
|
|
}
|
|
cursor := &messageCursor{ChatID: chat.ID, CreatedAt: first[1].CreatedAt, MessageID: first[1].ID}
|
|
second, more, err := f.messages.ListPageByChat(context.Background(), chat.ID, cursor, 2)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if more || len(second) != 2 || second[0].ID != ids[2] || second[1].ID != ids[3] {
|
|
t.Fatalf("unexpected second page: %v, more=%v", second, more)
|
|
}
|
|
}
|
|
|
|
func TestListPageByChatReturnsNonNilEmptyPage(t *testing.T) {
|
|
f := newTestFixture(t)
|
|
page, more, err := f.messages.ListPageByChat(context.Background(), uuid.NewString(), nil, 100)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if page == nil || len(page) != 0 || more {
|
|
t.Fatalf("unexpected empty page: %v, more=%v", page, more)
|
|
}
|
|
}
|