Files
2026-11-14 20:49:39 +01:00

442 lines
16 KiB
Go

package ml
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestPredictObjectResponseAndRequest(t *testing.T) {
var got PredictRequest
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/predict" {
t.Errorf("path=%q", r.URL.Path)
}
if r.Header.Get("Content-Type") != "application/json" {
t.Errorf("Content-Type=%q", r.Header.Get("Content-Type"))
}
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
t.Errorf("decode request: %v", err)
}
_, _ = w.Write([]byte(`{"points":[{"t":"2026-11-16T09:00:00Z","v":12.3,"lo":8.1,"hi":17.2}]}`))
}))
defer srv.Close()
client := New(srv.URL+"/", time.Second)
points, err := client.Predict(context.Background(), PredictRequest{
Sensor: "hn-bahnhof-01", Horizon: "1h", Scenario: "base",
Weather: WeatherInput{TempC: 9, PrecipMM: 0}, IsHoliday: false,
})
if err != nil {
t.Fatalf("Predict: %v", err)
}
if len(points) != 1 || points[0].V != 12.3 || points[0].Lo != 8.1 {
t.Fatalf("points=%+v", points)
}
if got.Sensor != "hn-bahnhof-01" || got.Horizon != "1h" || got.Weather.TempC != 9 {
t.Fatalf("request=%+v", got)
}
}
func TestPredictBareArrayResponse(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`[{"t":"2026-11-16T09:00:00Z","v":1,"lo":0.5,"hi":1.5}]`))
}))
defer srv.Close()
points, err := New(srv.URL, time.Second).Predict(context.Background(), PredictRequest{})
if err != nil {
t.Fatalf("Predict: %v", err)
}
if len(points) != 1 || points[0].V != 1 {
t.Fatalf("points=%+v", points)
}
}
func TestPredictRejectsEmptyAndErrorStatus(t *testing.T) {
empty := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"points":[]}`))
}))
defer empty.Close()
if _, err := New(empty.URL, time.Second).Predict(context.Background(), PredictRequest{}); err == nil {
t.Fatal("expected an error for an empty points array")
}
boom := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "nope", http.StatusInternalServerError)
}))
defer boom.Close()
if _, err := New(boom.URL, time.Second).Predict(context.Background(), PredictRequest{}); err == nil {
t.Fatal("expected an error for HTTP 500")
}
}
func TestPredictTimeout(t *testing.T) {
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(150 * time.Millisecond)
_, _ = w.Write([]byte(`{"points":[{"t":"2026-11-16T09:00:00Z","v":1,"lo":0,"hi":2}]}`))
}))
defer slow.Close()
client := New(slow.URL, 20*time.Millisecond)
start := time.Now()
if _, err := client.Predict(context.Background(), PredictRequest{}); err == nil {
t.Fatal("expected a timeout error")
}
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("timeout took %s", elapsed)
}
}
func TestPlaygroundPredictOptionalWeatherAndHoliday(t *testing.T) {
var bodies []map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/predict" {
t.Errorf("path=%q", r.URL.Path)
}
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode request: %v", err)
}
bodies = append(bodies, body)
_, _ = w.Write([]byte(`{
"sensor":"hn-bahnhof-01",
"horizon":"48h",
"scenario":"base",
"points":[{"t":"2026-11-16T09:00:00Z","v":12.3,"lo":8.1,"hi":17.2}],
"data_version":"d1",
"model_version":"m1",
"context_version":"c1"
}`))
}))
defer srv.Close()
client := New(srv.URL, time.Second)
if _, err := client.PlaygroundPredict(context.Background(), PlaygroundRequest{
Sensor: "hn-bahnhof-01", Horizon: "48h", Scenario: "base",
}); err != nil {
t.Fatalf("PlaygroundPredict without weather: %v", err)
}
if len(bodies) != 1 {
t.Fatalf("requests=%d", len(bodies))
}
if _, ok := bodies[0]["weather"]; ok {
t.Errorf("weather should be omitted when not supplied: %+v", bodies[0])
}
if _, ok := bodies[0]["is_holiday"]; ok {
t.Errorf("is_holiday should be omitted when not supplied: %+v", bodies[0])
}
temp := 29.0
holiday := true
resp, err := client.PlaygroundPredict(context.Background(), PlaygroundRequest{
Sensor: "hn-bahnhof-01", Horizon: "48h", Scenario: "base",
Weather: &PlaygroundWeather{TempC: &temp}, IsHoliday: &holiday,
})
if err != nil {
t.Fatalf("PlaygroundPredict with weather: %v", err)
}
if resp.ModelVersion != "m1" || resp.DataVersion != "d1" || len(resp.Points) != 1 {
t.Fatalf("response=%+v", resp)
}
if len(bodies) != 2 {
t.Fatalf("requests=%d", len(bodies))
}
weather, ok := bodies[1]["weather"].(map[string]any)
if !ok || weather["temp_c"] != float64(29) {
t.Errorf("weather=%+v", bodies[1]["weather"])
}
if _, ok := weather["precip_mm"]; ok {
t.Errorf("precip_mm should be omitted: %+v", weather)
}
if bodies[1]["is_holiday"] != true {
t.Errorf("is_holiday=%+v", bodies[1]["is_holiday"])
}
}
func TestSimulate(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req SimulateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
t.Errorf("decode: %v", err)
}
if req.Scenario != "rainy-saturday" || req.Sensors != "all" {
t.Errorf("request=%+v", req)
}
_, _ = w.Write([]byte(`{"scenario":"rainy-saturday","generated_at":"2026-11-14T09:12:00Z","forecasts":{"hn-bahnhof-01":{"7d":[{"t":"2026-11-16T09:00:00Z","v":5,"lo":4,"hi":6}]}}}`))
}))
defer srv.Close()
forecasts, err := New(srv.URL, time.Second).Simulate(context.Background(), SimulateRequest{
Scenario: "rainy-saturday", Sensors: "all",
})
if err != nil {
t.Fatalf("Simulate: %v", err)
}
points := forecasts["hn-bahnhof-01"]["7d"]
if len(points) != 1 || points[0].V != 5 {
t.Fatalf("forecasts=%+v", forecasts)
}
if _, ok := forecasts["missing"]; ok {
t.Fatal("unexpected sensor")
}
}
func TestBootstrapFetchesSnapshot(t *testing.T) {
var gotMethod, gotPath, gotAuth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath, gotAuth = r.Method, r.URL.Path, r.Header.Get("Authorization")
_, _ = w.Write([]byte(`{
"data_version":"2026-11-07T23:51:00Z",
"model_version":"histgb-2026-11-14",
"context_version":"2026-11-14T03:00:00Z",
"sensors":[{"id":"hn-bahnhof-01","name":"Bahnhof","lat":49.14,"lon":9.2,"mean":24.2,"p95":88.2,"battery":71}],
"series":{"hn-bahnhof-01":[{"t":"2026-11-01T10:00:00Z","v":12.3}]},
"context":{"weather":{"now":{"t":"2026-11-14T03:00:00Z","temp_c":8.9,"precip_mm":0,"cloud_pct":80,"wind_kmh":11,"humidity_pct":79},"forecast":[]},"holidays":[{"date":"2026-11-01","name":"Allerheiligen"}],"updated_at":"2026-11-14T03:00:00Z"},
"meta":{"coverage":{"sensors":8,"from":"2026-06-12T00:00:00Z","to":"2026-11-07T23:51:00Z","cadence_min":15},"metrics":{"model":"weather","mae":3.36,"wape":27.8,"r2":0.779,"baseline_mae":5.4,"baseline_wape":44.7},"limits":["estimated devices, not people"]}
}`))
}))
defer srv.Close()
// The control token is for /train only; /bootstrap must stay unauthenticated.
payload, err := NewWithToken(srv.URL, time.Second, "secret-token").Bootstrap(context.Background())
if err != nil {
t.Fatalf("Bootstrap: %v", err)
}
if gotMethod != http.MethodGet || gotPath != "/bootstrap" {
t.Fatalf("request=%s %s, want GET /bootstrap", gotMethod, gotPath)
}
if gotAuth != "" {
t.Errorf("Authorization=%q, want none", gotAuth)
}
if len(payload.Sensors) != 1 || payload.Sensors[0].ID != "hn-bahnhof-01" || payload.Sensors[0].Battery == nil {
t.Fatalf("sensors=%+v", payload.Sensors)
}
if len(payload.Series["hn-bahnhof-01"]) != 1 || payload.Series["hn-bahnhof-01"][0].V != 12.3 {
t.Fatalf("series=%+v", payload.Series)
}
if payload.Context.UpdatedAt.IsZero() || len(payload.Context.Holidays) != 1 {
t.Fatalf("context=%+v", payload.Context)
}
if payload.DataVersion == "" || payload.ModelVersion == "" || payload.ContextVersion == "" {
t.Fatalf("versions=%+v", payload)
}
if payload.Meta.Coverage.Sensors != 8 || payload.Meta.Metrics.MAE != 3.36 || len(payload.Meta.Limits) != 1 {
t.Fatalf("meta=%+v", payload.Meta)
}
}
func TestBootstrapRejectsErrorAndEmptySensors(t *testing.T) {
boom := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "not ready", http.StatusServiceUnavailable)
}))
defer boom.Close()
if _, err := New(boom.URL, time.Second).Bootstrap(context.Background()); err == nil {
t.Fatal("expected an error for HTTP 503")
}
empty := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"sensors":[]}`))
}))
defer empty.Close()
if _, err := New(empty.URL, time.Second).Bootstrap(context.Background()); err == nil {
t.Fatal("expected an error for an empty sensor list")
}
bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{`))
}))
defer bad.Close()
if _, err := New(bad.URL, time.Second).Bootstrap(context.Background()); err == nil {
t.Fatal("expected an error for invalid JSON")
}
}
func TestBootstrapTimeout(t *testing.T) {
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(150 * time.Millisecond)
_, _ = w.Write([]byte(`{"sensors":[{"id":"s"}]}`))
}))
defer slow.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
start := time.Now()
if _, err := New(slow.URL, time.Second).Bootstrap(ctx); err == nil {
t.Fatal("expected a context timeout")
}
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("timeout took %s", elapsed)
}
}
func TestNewUsesDefaultTimeout(t *testing.T) {
client := New("http://example.invalid", 0)
if client.http.Timeout != DefaultTimeout {
t.Fatalf("timeout=%s, want %s", client.http.Timeout, DefaultTimeout)
}
}
func TestTrainForwardsBodyContentTypeAndStatus(t *testing.T) {
var gotMethod, gotPath, gotType, gotBody string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
gotType = r.Header.Get("Content-Type")
raw, _ := io.ReadAll(r.Body)
gotBody = string(raw)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"job_id":"job-1","status":"queued","model":"small"}`))
}))
defer srv.Close()
status, body, err := New(srv.URL, time.Second).Train(context.Background(), "application/json",
strings.NewReader(`{"path":"/tmp/new.csv","model":"small"}`))
if err != nil {
t.Fatalf("Train: %v", err)
}
if status != http.StatusAccepted {
t.Fatalf("status=%d, want 202", status)
}
if !strings.Contains(string(body), `"job_id":"job-1"`) {
t.Fatalf("body=%s", body)
}
if gotMethod != http.MethodPost || gotPath != "/train" {
t.Fatalf("request=%s %s, want POST /train", gotMethod, gotPath)
}
if gotType != "application/json" || !strings.Contains(gotBody, "/tmp/new.csv") {
t.Fatalf("content-type=%q body=%q", gotType, gotBody)
}
}
func TestControlRequestsForwardBearerToken(t *testing.T) {
var got []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = append(got, r.Header.Get("Authorization"))
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusAccepted)
}
_, _ = w.Write([]byte(`{"job_id":"job-1","status":"queued"}`))
}))
defer srv.Close()
client := NewWithToken(srv.URL, time.Second, "token-123")
if _, _, err := client.Train(context.Background(), "application/json", strings.NewReader(`{"path":"/tmp/x.csv"}`)); err != nil {
t.Fatalf("Train: %v", err)
}
if _, _, err := client.TrainStatus(context.Background(), "job-1"); err != nil {
t.Fatalf("TrainStatus: %v", err)
}
for i, auth := range got {
if auth != "Bearer token-123" {
t.Errorf("request %d Authorization=%q, want Bearer token-123", i, auth)
}
}
}
func TestTrainStatusForwardsJobIDAndUpstreamError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
t.Errorf("method=%s, want GET", r.Method)
}
if r.URL.Path == "/train/job-1" {
_, _ = w.Write([]byte(`{"job_id":"job-1","status":"succeeded","error":null}`))
return
}
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"detail":"job not found"}`))
}))
defer srv.Close()
client := New(srv.URL, time.Second)
status, body, err := client.TrainStatus(context.Background(), "job-1")
if err != nil {
t.Fatalf("TrainStatus: %v", err)
}
if status != http.StatusOK || !strings.Contains(string(body), `"succeeded"`) {
t.Fatalf("status=%d body=%s", status, body)
}
status, body, err = client.TrainStatus(context.Background(), "missing")
if err != nil {
t.Fatalf("TrainStatus missing: %v", err)
}
if status != http.StatusNotFound || !strings.Contains(string(body), "job not found") {
t.Fatalf("status=%d body=%s, want forwarded 404", status, body)
}
}
func TestPreZeroClientsForwardRouteQueryAndStatus(t *testing.T) {
var gotPaths, gotQueries []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
t.Errorf("method=%s, want GET", r.Method)
}
gotPaths = append(gotPaths, r.URL.Path)
gotQueries = append(gotQueries, r.URL.RawQuery)
switch {
case r.URL.Path == "/prezero/summary":
_, _ = w.Write([]byte(`{"summary":{"priority_counts":{"high":88}}}`))
case r.URL.Path == "/prezero/priority":
_, _ = w.Write([]byte(`{"total":88,"count":1,"containers":[]}`))
case r.URL.Path == "/prezero/containers/known-id":
_, _ = w.Write([]byte(`{"container":{"location_id":"known-id"}}`))
default:
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":{"code":"not_found","message":"container not found"}}`))
}
}))
defer srv.Close()
client := New(srv.URL, time.Second)
status, body, err := client.PreZeroSummary(context.Background())
if err != nil || status != http.StatusOK || !strings.Contains(string(body), `"high":88`) {
t.Fatalf("summary status=%d body=%s err=%v", status, body, err)
}
status, body, err = client.PreZeroPriority(context.Background(), "high", 3, 10)
if err != nil || status != http.StatusOK || !strings.Contains(string(body), `"total":88`) {
t.Fatalf("priority status=%d body=%s err=%v", status, body, err)
}
if _, _, err := client.PreZeroPriority(context.Background(), "", 50, 0); err != nil {
t.Fatalf("priority defaults: %v", err)
}
status, body, err = client.PreZeroContainer(context.Background(), "known-id")
if err != nil || status != http.StatusOK || !strings.Contains(string(body), "known-id") {
t.Fatalf("container status=%d body=%s err=%v", status, body, err)
}
status, body, err = client.PreZeroContainer(context.Background(), "missing")
if err != nil {
t.Fatalf("container missing: %v", err)
}
if status != http.StatusNotFound || !strings.Contains(string(body), "container not found") {
t.Fatalf("container missing status=%d body=%s, want forwarded 404", status, body)
}
wantPaths := []string{
"/prezero/summary",
"/prezero/priority",
"/prezero/priority",
"/prezero/containers/known-id",
"/prezero/containers/missing",
}
for i, want := range wantPaths {
if gotPaths[i] != want {
t.Errorf("request %d path=%q, want %q", i, gotPaths[i], want)
}
}
wantQueries := []string{"", "limit=3&offset=10&priority=high", "limit=50&offset=0", "", ""}
for i, want := range wantQueries {
if gotQueries[i] != want {
t.Errorf("request %d query=%q, want %q", i, gotQueries[i], want)
}
}
}