Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
86 lines
2.2 KiB
Go
86 lines
2.2 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestHealthz(t *testing.T) {
|
|
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
|
rec := httptest.NewRecorder()
|
|
|
|
New(nil, nil).Router().ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)
|
|
}
|
|
|
|
var body map[string]string
|
|
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
|
|
t.Fatalf("failed to decode body: %v", err)
|
|
}
|
|
if body["status"] != "ok" {
|
|
t.Fatalf("expected status ok, got %q", body["status"])
|
|
}
|
|
}
|
|
|
|
func TestPageParams(t *testing.T) {
|
|
cases := []struct {
|
|
query string
|
|
wantPage, wantSz int
|
|
}{
|
|
{"", 1, defaultPageSize},
|
|
{"page=3&size=10", 3, 10},
|
|
{"page=0&size=-5", 1, defaultPageSize},
|
|
{"size=1000", 1, maxPageSize},
|
|
{"page=abc", 1, defaultPageSize},
|
|
}
|
|
for _, c := range cases {
|
|
req := httptest.NewRequest(http.MethodGet, "/?"+c.query, nil)
|
|
page, size := pageParams(req)
|
|
if page != c.wantPage || size != c.wantSz {
|
|
t.Errorf("query %q: got page=%d size=%d, want page=%d size=%d",
|
|
c.query, page, size, c.wantPage, c.wantSz)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestPageTooDeep(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
page, size int
|
|
want bool
|
|
}{
|
|
{name: "boundary", page: 100, size: 100, want: false},
|
|
{name: "over boundary", page: 101, size: 100, want: true},
|
|
{name: "small page", page: 1, size: 20, want: false},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := pageTooDeep(tt.page, tt.size); got != tt.want {
|
|
t.Fatalf("pageTooDeep(%d, %d) = %v, want %v",
|
|
tt.page, tt.size, got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestDeepPaginationReturns400BeforeStoreAccess(t *testing.T) {
|
|
h := New(nil, nil)
|
|
for _, path := range []string{
|
|
"/api/" + APIVersion + "/products/search?page=101&size=100",
|
|
"/api/" + APIVersion + "/brands?page=101&size=100",
|
|
} {
|
|
rec := doGET(t, h, path)
|
|
if rec.Code != http.StatusBadRequest {
|
|
t.Fatalf("%s: status = %d, want %d", path, rec.Code, http.StatusBadRequest)
|
|
}
|
|
if !strings.Contains(rec.Body.String(), "page_too_deep") {
|
|
t.Fatalf("%s: response missing page_too_deep: %s", path, rec.Body.String())
|
|
}
|
|
}
|
|
}
|