61 lines
1.8 KiB
Go
61 lines
1.8 KiB
Go
package pagination_test
|
|
|
|
import (
|
|
"encoding/json"
|
|
"testing"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"messenger/internal/platform/ident"
|
|
"messenger/internal/platform/pagination"
|
|
)
|
|
|
|
func self(id uuid.UUID) uuid.UUID { return id }
|
|
|
|
func TestCutTrimsOverfetchAndDerivesNext(t *testing.T) {
|
|
ids := []uuid.UUID{ident.New(), ident.New(), ident.New()}
|
|
|
|
fewer := pagination.Cut(ids[:2], 5, self)
|
|
if len(fewer.Items) != 2 || fewer.Next != nil {
|
|
t.Fatalf("fewer than limit: %+v", fewer)
|
|
}
|
|
exact := pagination.Cut(ids[:2], 2, self)
|
|
if len(exact.Items) != 2 || exact.Next != nil {
|
|
t.Fatalf("exactly limit must not continue: %+v", exact)
|
|
}
|
|
over := pagination.Cut(ids, 2, self)
|
|
if len(over.Items) != 2 || over.Next == nil || *over.Next != ids[1] {
|
|
t.Fatalf("over-fetched page must trim and continue from the last kept id: %+v", over)
|
|
}
|
|
if over.Items[0] != ids[0] || over.Items[1] != ids[1] {
|
|
t.Fatalf("order changed: %v", over.Items)
|
|
}
|
|
}
|
|
|
|
func TestToResponseEncodesCursorWithinScope(t *testing.T) {
|
|
scope, last := ident.New(), ident.New()
|
|
page := pagination.Page[uuid.UUID]{Items: []uuid.UUID{last}, Next: &last}
|
|
res := pagination.ToResponse(page, scope, func(id uuid.UUID) string { return id.String() })
|
|
if len(res.Items) != 1 || res.Items[0] != last.String() {
|
|
t.Fatalf("items = %v", res.Items)
|
|
}
|
|
if res.NextCursor == nil {
|
|
t.Fatal("next cursor missing")
|
|
}
|
|
got, err := pagination.DecodeCursor(*res.NextCursor, scope)
|
|
if err != nil || got != last {
|
|
t.Fatalf("cursor decodes to %s, %v; want %s", got, err, last)
|
|
}
|
|
}
|
|
|
|
func TestToResponseSerializesEmptyPageAsContractRequires(t *testing.T) {
|
|
res := pagination.ToResponse(pagination.Page[uuid.UUID]{}, ident.New(), func(id uuid.UUID) string { return id.String() })
|
|
raw, err := json.Marshal(res)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if string(raw) != `{"items":[],"next_cursor":null}` {
|
|
t.Fatalf("empty page = %s", raw)
|
|
}
|
|
}
|