package paginate import ( "errors" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestPaginationFromQuery(t *testing.T) { req, err := http.NewRequest("GET", "/?page=2&pageSize=10", http.NoBody) assert.NoError(t, err) pagination := PaginationFromQuery("page", "pageSize")(req, &Pagination{}) assert.Equal(t, &Pagination{Page: 2, PageSize: 10}, pagination) } func TestValidPagination(t *testing.T) { opts := []Option{ SetPaginationDefaults(1, 10), } handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { pagination := PaginationFromContext(r.Context()) assert.NotNil(t, pagination) assert.Equal(t, 2, pagination.Page) assert.Equal(t, 10, pagination.PageSize) }) middleware := Middleware(opts...)(handler) w := httptest.NewRecorder() req := httptest.NewRequest("GET", "/?page=2&pageSize=10", http.NoBody) middleware.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) } func TestInvalidPagination(t *testing.T) { opts := []Option{ SetPaginationDefaults(1, 10), SetValidatePaginationFn(func(p *Pagination) error { if p.Page < 1 || p.PageSize < 1 { return errors.New("invalid pagination") } return nil }), } handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { pagination := PaginationFromContext(r.Context()) assert.NotNil(t, pagination) assert.Equal(t, -1, pagination.Page) assert.Equal(t, 10, pagination.PageSize) }) middleware := Middleware(opts...)(handler) w := httptest.NewRecorder() req := httptest.NewRequest("GET", "/?page=-1&pageSize=10", http.NoBody) middleware.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) }