123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- package depager_test
- import (
- "fmt"
- "testing"
- dp "idio.link/go/depager/v2"
- )
- type NoopClient[T any] struct {
- err error
- pages []dp.Page[T]
- m int
- cnt uint64
- }
- func (c *NoopClient[T]) NextPage(
- _offset uint64,
- ) (page dp.Page[T], cnt uint64, err error) {
- if len(c.pages) == 0 {
- return
- }
- if c.m >= len(c.pages) {
- err = fmt.Errorf("client: next page: exceeded max pages")
- return
- }
- page = c.pages[c.m]
- cnt = c.cnt
- err = c.err
- c.m++
- return
- }
- func NewNoopClient[T any](
- cnt int,
- err error,
- pages []dp.Page[T],
- ) dp.Client[T] {
- return &NoopClient[T]{
- cnt: uint64(cnt),
- err: err,
- pages: pages,
- }
- }
- type Aggr[T any] []T
- func (a Aggr[T]) Elems() []T {
- return []T(a)
- }
- func TestUsingNoopClient(t *testing.T) {
- client := NewNoopClient[any](0, nil,
- []dp.Page[any]{
- Aggr[any]{},
- },
- )
- pager := dp.NewPager(client, 0)
- for range pager.Iter() {
- }
- if err := pager.LastErr(); err != nil {
- t.Errorf("unexpected error in pager with noop client: %v", err)
- }
- }
- func TestNoopClientReturnsError(t *testing.T) {
- client := NewNoopClient[any](0, fmt.Errorf("whomp"),
- []dp.Page[any]{
- Aggr[any]{},
- },
- )
- pager := dp.NewPager(client, 0)
- for range pager.Iter() {
- }
- if err := pager.LastErr(); err == nil {
- t.Errorf("unexpected success: %v", err)
- }
- }
- func TestClientReturnsNonemptyPage(t *testing.T) {
- pageSize := 2
- itemCount := 3
- client := NewNoopClient[any](itemCount, nil,
- []dp.Page[any]{
- Aggr[any]{1, 2},
- Aggr[any]{3},
- },
- )
- pager := dp.NewPager(client, uint64(pageSize))
- var elem int
- for e := range pager.Iter() {
- elem = e.(int)
- }
- if err := pager.LastErr(); err != nil {
- t.Errorf("unexpected error in pager: %v", err)
- }
- if elem != 3 {
- t.Errorf("unexpected value: '%v'", elem)
- }
- }
- func TestClientReturnsFewerPagesThanExpected(t *testing.T) {
- pageSize := 1
- itemCount := pageSize + 1
- client := NewNoopClient[any](itemCount, nil,
- []dp.Page[any]{
- Aggr[any]{0},
- },
- )
- pager := dp.NewPager(client, uint64(pageSize))
- for range pager.Iter() {
- }
- if err := pager.LastErr(); err == nil {
- t.Errorf("unexpected success in pager: %v", err)
- }
- }
|