This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
package forecastapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/itworx/pulse/internal/auth"
|
||||
"github.com/itworx/pulse/internal/forecast"
|
||||
)
|
||||
|
||||
type providerFunc func(context.Context) (forecast.Snapshot, error)
|
||||
|
||||
func (f providerFunc) Snapshot(ctx context.Context) (forecast.Snapshot, error) { return f(ctx) }
|
||||
|
||||
func authenticatedRequest(method, path string) *http.Request {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
return r.WithContext(auth.WithPrincipal(r.Context(), auth.Principal{Subject: "test", Role: auth.RoleViewer}))
|
||||
}
|
||||
|
||||
func TestHandlerRequiresAuthenticationAndGET(t *testing.T) {
|
||||
h := Handler{}
|
||||
unauthenticated := httptest.NewRecorder()
|
||||
h.ServeHTTP(unauthenticated, httptest.NewRequest(http.MethodGet, "/api/v1/forecasts", nil))
|
||||
if unauthenticated.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status=%d", unauthenticated.Code)
|
||||
}
|
||||
method := httptest.NewRecorder()
|
||||
h.ServeHTTP(method, authenticatedRequest(http.MethodPost, "/api/v1/forecasts"))
|
||||
if method.Code != http.StatusNotFound {
|
||||
t.Fatalf("status=%d", method.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerReturnsBoundedSnapshotAndMapsProviderErrors(t *testing.T) {
|
||||
now := time.Date(2026, 8, 1, 12, 0, 0, 0, time.UTC)
|
||||
snapshot := forecast.Snapshot{ContractVersion: forecast.ContractVersion, GeneratedAt: now, QualifiedCount: 0, Items: []forecast.Forecast{{EntityID: "share", Method: forecast.MethodInsufficient, Confidence: forecast.ConfidenceNone, Reason: "insufficient_points"}}}
|
||||
h := Handler{Provider: providerFunc(func(context.Context) (forecast.Snapshot, error) { return snapshot, nil })}
|
||||
recorder := httptest.NewRecorder()
|
||||
h.ServeHTTP(recorder, authenticatedRequest(http.MethodGet, "/api/v1/forecasts"))
|
||||
if recorder.Code != http.StatusOK || recorder.Header().Get("Cache-Control") != "private, max-age=15" {
|
||||
t.Fatalf("status=%d headers=%v", recorder.Code, recorder.Header())
|
||||
}
|
||||
var got forecast.Snapshot
|
||||
if err := json.NewDecoder(recorder.Body).Decode(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.QualifiedCount != 0 || len(got.Items) != 1 || got.Items[0].Reason != "insufficient_points" {
|
||||
t.Fatalf("snapshot=%+v", got)
|
||||
}
|
||||
|
||||
failing := Handler{Provider: providerFunc(func(context.Context) (forecast.Snapshot, error) { return forecast.Snapshot{}, context.DeadlineExceeded })}
|
||||
deadline := httptest.NewRecorder()
|
||||
failing.ServeHTTP(deadline, authenticatedRequest(http.MethodGet, "/api/v1/forecasts"))
|
||||
if deadline.Code != http.StatusOK {
|
||||
t.Fatalf("deadline status=%d", deadline.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user