package api import ( "context" "encoding/json" "errors" "io" "net/http" "net/http/httptest" "sync/atomic" "testing" ) // stubPreZero implements MLClient (through the embedded stubML) and // PreZeroClient, so New's optional type assertion picks it up. type stubPreZero struct { *stubML calls atomic.Int32 summaryFn func(context.Context) (int, []byte, error) priorityFn func(context.Context, string, int, int) (int, []byte, error) containerFn func(context.Context, string) (int, []byte, error) gotPriority string gotLimit int gotOffset int gotLocation string } func newStubPreZero() *stubPreZero { return &stubPreZero{stubML: &stubML{}} } func (s *stubPreZero) PreZeroSummary(ctx context.Context) (int, []byte, error) { s.calls.Add(1) if s.summaryFn == nil { return 0, nil, errors.New("ml unavailable") } return s.summaryFn(ctx) } func (s *stubPreZero) PreZeroPriority(ctx context.Context, priority string, limit, offset int) (int, []byte, error) { s.calls.Add(1) s.gotPriority, s.gotLimit, s.gotOffset = priority, limit, offset if s.priorityFn == nil { return 0, nil, errors.New("ml unavailable") } return s.priorityFn(ctx, priority, limit, offset) } func (s *stubPreZero) PreZeroContainer(ctx context.Context, locationID string) (int, []byte, error) { s.calls.Add(1) s.gotLocation = locationID if s.containerFn == nil { return 0, nil, errors.New("ml unavailable") } return s.containerFn(ctx, locationID) } func newPreZeroServer(t *testing.T, client MLClient) *httptest.Server { t.Helper() _, ts := newTestServer(t, client, nil) return ts } // getRaw is getJSON's byte-preserving sibling: the PreZero tests assert that // the upstream body passes through unchanged. func getRaw(t *testing.T, url string) (*http.Response, []byte) { t.Helper() resp, err := http.Get(url) if err != nil { t.Fatalf("GET %s: %v", url, err) } defer resp.Body.Close() raw, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("read GET %s: %v", url, err) } return resp, raw } func TestPreZeroSummaryPassthrough(t *testing.T) { const body = `{"meta":{"rows":11701,"containers":449},"summary":{"priority_counts":{"high":88,"medium":248,"low":113}}}` stub := newStubPreZero() stub.summaryFn = func(context.Context) (int, []byte, error) { return http.StatusOK, []byte(body), nil } ts := newPreZeroServer(t, stub) resp, raw := getRaw(t, ts.URL+"/api/prezero/summary") if resp.StatusCode != http.StatusOK { t.Fatalf("summary status=%d body=%s, want 200", resp.StatusCode, raw) } if got := resp.Header.Get("Content-Type"); got != "application/json; charset=utf-8" { t.Errorf("summary Content-Type=%q, want JSON", got) } if string(raw) != body { t.Fatalf("summary body=%s, want exact passthrough", raw) } var decoded struct { Summary struct { PriorityCounts map[string]int `json:"priority_counts"` } `json:"summary"` } if err := json.Unmarshal(raw, &decoded); err != nil { t.Fatalf("decode summary: %v", err) } if decoded.Summary.PriorityCounts["high"] != 88 || decoded.Summary.PriorityCounts["medium"] != 248 || decoded.Summary.PriorityCounts["low"] != 113 { t.Fatalf("priority counts=%v", decoded.Summary.PriorityCounts) } if got := stub.calls.Load(); got != 1 { t.Fatalf("client calls=%d, want 1", got) } } func TestPreZeroPriorityForwardsQuery(t *testing.T) { stub := newStubPreZero() stub.priorityFn = func(context.Context, string, int, int) (int, []byte, error) { return http.StatusOK, []byte(`{"total":88,"count":3,"offset":10,"limit":3,"containers":[{"location_id":"a"},{"location_id":"b"},{"location_id":"c"}]}`), nil } ts := newPreZeroServer(t, stub) resp, raw := getRaw(t, ts.URL+"/api/prezero/priority?priority=high&limit=3&offset=10") if resp.StatusCode != http.StatusOK { t.Fatalf("priority status=%d body=%s, want 200", resp.StatusCode, raw) } if stub.gotPriority != "high" || stub.gotLimit != 3 || stub.gotOffset != 10 { t.Fatalf("forwarded priority=%q limit=%d offset=%d, want high/3/10", stub.gotPriority, stub.gotLimit, stub.gotOffset) } var body struct { Total int `json:"total"` Count int `json:"count"` Containers []struct { LocationID string `json:"location_id"` } `json:"containers"` } if err := json.Unmarshal(raw, &body); err != nil { t.Fatalf("decode priority: %v", err) } if body.Total != 88 || body.Count != 3 || len(body.Containers) != 3 { t.Fatalf("priority body=%+v", body) } // Omitted query parameters use the contract defaults. getRaw(t, ts.URL+"/api/prezero/priority") if stub.gotPriority != "" || stub.gotLimit != 50 || stub.gotOffset != 0 { t.Fatalf("defaults forwarded priority=%q limit=%d offset=%d, want empty/50/0", stub.gotPriority, stub.gotLimit, stub.gotOffset) } } func TestPreZeroPriorityValidationSkipsClient(t *testing.T) { stub := newStubPreZero() stub.priorityFn = func(context.Context, string, int, int) (int, []byte, error) { return http.StatusOK, []byte(`{"containers":[]}`), nil } ts := newPreZeroServer(t, stub) for _, query := range []string{ "priority=urgent", "priority=HIGH", "limit=0", "limit=501", "limit=-1", "limit=abc", "limit=1.5", "offset=-1", "offset=abc", } { resp, raw := getRaw(t, ts.URL+"/api/prezero/priority?"+query) if resp.StatusCode != http.StatusBadRequest { t.Errorf("%s: status=%d body=%s, want 400", query, resp.StatusCode, raw) continue } var envelope struct { Error struct { Code string `json:"code"` Message string `json:"message"` } `json:"error"` } if err := json.Unmarshal(raw, &envelope); err != nil { t.Errorf("%s: decode error envelope: %v", query, err) continue } if envelope.Error.Code != "bad_request" || envelope.Error.Message == "" { t.Errorf("%s: error envelope=%+v", query, envelope.Error) } } if got := stub.calls.Load(); got != 0 { t.Fatalf("client calls=%d for invalid queries, want 0", got) } } func TestPreZeroContainerPassthrough(t *testing.T) { const locationID = "eecbf6fa-decf-46da-b110-bf014e7c181d" stub := newStubPreZero() stub.containerFn = func(_ context.Context, locationID string) (int, []byte, error) { if locationID == "eecbf6fa-decf-46da-b110-bf014e7c181d" { return http.StatusOK, []byte(`{"container":{"location_id":"eecbf6fa-decf-46da-b110-bf014e7c181d","priority":"high"},"readings":[{"date":"2026-09-29"}]}`), nil } return http.StatusNotFound, []byte(`{"error":{"code":"not_found","message":"container not found"}}`), nil } ts := newPreZeroServer(t, stub) resp, raw := getRaw(t, ts.URL+"/api/prezero/containers/"+locationID) if resp.StatusCode != http.StatusOK { t.Fatalf("container status=%d body=%s, want 200", resp.StatusCode, raw) } if stub.gotLocation != locationID { t.Errorf("forwarded location=%q, want %q", stub.gotLocation, locationID) } var body struct { Container struct { LocationID string `json:"location_id"` Priority string `json:"priority"` } `json:"container"` } if err := json.Unmarshal(raw, &body); err != nil { t.Fatalf("decode container: %v", err) } if body.Container.LocationID != locationID || body.Container.Priority != "high" { t.Fatalf("container=%+v", body.Container) } resp, raw = getRaw(t, ts.URL+"/api/prezero/containers/unknown-id") if resp.StatusCode != http.StatusNotFound { t.Fatalf("unknown container status=%d body=%s, want 404", resp.StatusCode, raw) } if !json.Valid(raw) { t.Fatalf("unknown container body is not JSON: %s", raw) } } func TestPreZeroUnavailableReturns502(t *testing.T) { failing := newStubPreZero() failing.summaryFn = func(context.Context) (int, []byte, error) { return 0, nil, errors.New("connection refused") } failing.priorityFn = func(context.Context, string, int, int) (int, []byte, error) { return 0, nil, errors.New("connection refused") } failing.containerFn = func(context.Context, string) (int, []byte, error) { return 0, nil, errors.New("connection refused") } ts := newPreZeroServer(t, failing) for _, path := range []string{ "/api/prezero/summary", "/api/prezero/priority?priority=high", "/api/prezero/containers/abc", } { resp, raw := getRaw(t, ts.URL+path) if resp.StatusCode != http.StatusBadGateway { t.Errorf("%s: status=%d body=%s, want 502", path, resp.StatusCode, raw) continue } var envelope struct { Error struct { Code string `json:"code"` } `json:"error"` } if err := json.Unmarshal(raw, &envelope); err != nil || envelope.Error.Code != "ml_unavailable" { t.Errorf("%s: error=%+v err=%v, want ml_unavailable", path, envelope.Error, err) } } // Prediction-only stubs do not implement PreZeroClient; that is also 502. unconfigured := newPreZeroServer(t, &stubML{}) for _, path := range []string{ "/api/prezero/summary", "/api/prezero/priority", "/api/prezero/containers/abc", } { resp, raw := getRaw(t, unconfigured.URL+path) if resp.StatusCode != http.StatusBadGateway { t.Errorf("unconfigured %s: status=%d body=%s, want 502", path, resp.StatusCode, raw) } } } func TestPreZeroRouting(t *testing.T) { stub := newStubPreZero() stub.summaryFn = func(context.Context) (int, []byte, error) { return http.StatusOK, []byte(`{}`), nil } stub.priorityFn = func(context.Context, string, int, int) (int, []byte, error) { return http.StatusOK, []byte(`{}`), nil } stub.containerFn = func(context.Context, string) (int, []byte, error) { return http.StatusOK, []byte(`{}`), nil } ts := newPreZeroServer(t, stub) for _, path := range []string{ "/api/prezero/summary", "/api/prezero/priority", "/api/prezero/containers/abc", } { req, err := http.NewRequest(http.MethodPost, ts.URL+path, nil) if err != nil { t.Fatal(err) } resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("POST %s: %v", path, err) } resp.Body.Close() if resp.StatusCode != http.StatusMethodNotAllowed { t.Errorf("POST %s status=%d, want 405", path, resp.StatusCode) } if allow := resp.Header.Get("Allow"); allow != "GET" { t.Errorf("POST %s Allow=%q, want GET", path, allow) } } for _, path := range []string{ "/api/prezero", "/api/prezero/unknown", "/api/prezero/containers/", "/api/prezero/containers/a/b", } { resp, raw := getRaw(t, ts.URL+path) if resp.StatusCode != http.StatusNotFound { t.Errorf("GET %s status=%d body=%s, want 404", path, resp.StatusCode, raw) } if !json.Valid(raw) { t.Errorf("GET %s body is not JSON: %s", path, raw) } } if got := stub.calls.Load(); got != 0 { t.Fatalf("client calls=%d for unroutable requests, want 0", got) } }