72 lines
1.9 KiB
Go
72 lines
1.9 KiB
Go
package pagination_test
|
|
|
|
import (
|
|
"errors"
|
|
"strings"
|
|
"testing"
|
|
|
|
"messenger/internal/platform/ident"
|
|
"messenger/internal/platform/pagination"
|
|
)
|
|
|
|
func TestCursorRoundTrip(t *testing.T) {
|
|
scope, last := ident.New(), ident.New()
|
|
encoded := pagination.EncodeCursor(scope, last)
|
|
if encoded == "" || strings.ContainsAny(encoded, "+/=") {
|
|
t.Fatalf("cursor must be non-empty URL-safe base64 without padding, got %q", encoded)
|
|
}
|
|
got, err := pagination.DecodeCursor(encoded, scope)
|
|
if err != nil {
|
|
t.Fatalf("DecodeCursor error: %v", err)
|
|
}
|
|
if got != last {
|
|
t.Fatalf("decoded %s, want %s", got, last)
|
|
}
|
|
}
|
|
|
|
func TestDecodeCursorRejectsForeignScope(t *testing.T) {
|
|
encoded := pagination.EncodeCursor(ident.New(), ident.New())
|
|
_, err := pagination.DecodeCursor(encoded, ident.New())
|
|
if !errors.Is(err, pagination.ErrInvalidCursor) {
|
|
t.Fatalf("err = %v, want ErrInvalidCursor", err)
|
|
}
|
|
}
|
|
|
|
func TestDecodeCursorRejectsGarbage(t *testing.T) {
|
|
scope := ident.New()
|
|
valid := pagination.EncodeCursor(scope, ident.New())
|
|
for _, raw := range []string{"", "***", "abc", valid[:len(valid)-2], valid + "AA", strings.ToUpper(valid)} {
|
|
if _, err := pagination.DecodeCursor(raw, scope); !errors.Is(err, pagination.ErrInvalidCursor) {
|
|
t.Errorf("DecodeCursor(%q) err = %v, want ErrInvalidCursor", raw, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestParseLimit(t *testing.T) {
|
|
cases := []struct {
|
|
raw string
|
|
want int
|
|
ok bool
|
|
}{
|
|
{"", 50, true},
|
|
{"1", 1, true},
|
|
{"100", 100, true},
|
|
{"0", 0, false},
|
|
{"101", 0, false},
|
|
{"-1", 0, false},
|
|
{"+5", 0, false},
|
|
{"5.0", 0, false},
|
|
{"abc", 0, false},
|
|
{" 5", 0, false},
|
|
}
|
|
for _, tc := range cases {
|
|
got, err := pagination.ParseLimit(tc.raw)
|
|
if tc.ok && (err != nil || got != tc.want) {
|
|
t.Errorf("ParseLimit(%q) = %d, %v; want %d", tc.raw, got, err, tc.want)
|
|
}
|
|
if !tc.ok && !errors.Is(err, pagination.ErrInvalidLimit) {
|
|
t.Errorf("ParseLimit(%q) err = %v, want ErrInvalidLimit", tc.raw, err)
|
|
}
|
|
}
|
|
}
|