package main import ( "encoding/json" "net" "net/http" "net/http/httptest" "net/url" "testing" "time" "github.com/klipperanywhere/klipperanywhere/internal/protocol" ) func TestResolveCameraURL(t *testing.T) { base, err := url.Parse("http://192.168.1.60:7125") if err != nil { t.Fatal(err) } got := resolveCameraURL(base, "/webcam/?action=snapshot") want := "http://192.168.1.60:7125/webcam/?action=snapshot" if got != want { t.Fatalf("resolved url = %q, want %q", got, want) } } func TestNormalizeDiscoveredCameraURLRewritesLoopback(t *testing.T) { base, err := url.Parse("http://192.168.1.60:7125") if err != nil { t.Fatal(err) } got := normalizeDiscoveredCameraURL(base, "http://127.0.0.1:80/webcam/?action=snapshot") want := "http://192.168.1.60:80/webcam/?action=snapshot" if got != want { t.Fatalf("normalized url = %q, want %q", got, want) } } func TestFetchMoonrakerCameras(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/server/webcams/list": _ = json.NewEncoder(w).Encode(map[string]any{ "result": map[string]any{ "webcams": []map[string]any{ { "name": "Camera", "enabled": true, "stream_url": "/webcam/?action=stream", "snapshot_url": "/webcam/?action=snapshot", "aspect_ratio": "4:3", "service": "mjpegstreamer-adaptive", "location": "printer", "source": "database", "flip_horizontal": true, }, }, }, }) case "/server/webcams/test": _ = json.NewEncoder(w).Encode(map[string]any{ "result": map[string]any{ "name": "Camera", "snapshot_url": "http://127.0.0.1:80/webcam/?action=snapshot", "stream_url": "http://127.0.0.1:80/webcam/?action=stream", }, }) default: http.NotFound(w, r) } })) defer server.Close() base, err := url.Parse(server.URL) if err != nil { t.Fatal(err) } cameras := fetchMoonrakerCameras(base) if len(cameras) != 1 { t.Fatalf("camera count = %d, want 1", len(cameras)) } camera := cameras[0] if camera.Name != "Camera" { t.Fatalf("camera name = %q, want Camera", camera.Name) } if camera.AspectRatio != "4:3" || camera.Service != "mjpegstreamer-adaptive" || !camera.FlipHorizontal { t.Fatalf("camera metadata not preserved: %+v", camera) } if camera.SnapshotURL == "" || camera.StreamURL == "" { t.Fatalf("camera urls not populated: %+v", camera) } } func TestFetchCameraSnapshot(t *testing.T) { snapshot := []byte{0x01, 0x02, 0x03, 0x04} server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/snapshot.jpg" { http.NotFound(w, r) return } w.Header().Set("Content-Type", "image/jpeg") _, _ = w.Write(snapshot) })) defer server.Close() data, headers, status, err := fetchCameraSnapshot(cameraConfig{SnapshotURL: server.URL + "/snapshot.jpg"}) if err != nil { t.Fatalf("fetchCameraSnapshot returned error: %v", err) } if status != http.StatusOK { t.Fatalf("status = %d, want 200", status) } if string(data) != string(snapshot) { t.Fatalf("snapshot = %x, want %x", data, snapshot) } if len(headers) == 0 { t.Fatal("expected response headers") } } func TestDiscoverUIUsesConfiguredURL(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok")) })) defer server.Close() ui := discoverUI(server.URL, true, nil) if ui == nil { t.Fatal("expected configured ui to be discovered") } if ui.URL.String() != server.URL || ui.Source != "config" || !ui.Reachable { t.Fatalf("unexpected ui target: %+v", ui) } } func TestDiscoverUIAutoDetectsCommonPort(t *testing.T) { listener, err := net.Listen("tcp", "127.0.0.1:4408") if err != nil { t.Skipf("127.0.0.1:4408 unavailable: %v", err) } server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok")) })) server.Listener = listener server.Start() defer server.Close() moonrakerURL, err := url.Parse("http://127.0.0.1:7125") if err != nil { t.Fatal(err) } ui := discoverUI("", true, moonrakerURL) if ui == nil { t.Fatal("expected auto-detected ui") } if ui.URL.String() != "http://127.0.0.1:4408" || ui.Source != "auto" || !ui.Reachable { t.Fatalf("unexpected auto ui target: %+v", ui) } } func TestIsActivePrintStatus(t *testing.T) { for _, state := range []string{"printing", "paused", " Printing "} { if !isActivePrintStatus(&protocol.PrintStatus{State: state}) { t.Fatalf("state %q should be active", state) } } for _, state := range []string{"", "standby", "complete", "error"} { if isActivePrintStatus(&protocol.PrintStatus{State: state}) { t.Fatalf("state %q should not be active", state) } } if isActivePrintStatus(nil) { t.Fatal("nil status should not be active") } } func TestMoonrakerSubscriptionStatus(t *testing.T) { initial := map[string]any{ "result": map[string]any{ "status": map[string]any{ "print_stats": map[string]any{"state": "printing"}, }, }, } if got := moonrakerSubscriptionStatus(initial); got == nil { t.Fatal("expected initial subscription status") } update := map[string]any{ "method": "notify_status_update", "params": []any{ map[string]any{ "print_stats": map[string]any{ "info": map[string]any{"current_layer": 2}, }, }, 123.4, }, } got := moonrakerSubscriptionStatus(update) if got == nil { t.Fatal("expected notify_status_update status") } printStats, ok := got["print_stats"].(map[string]any) if !ok { t.Fatalf("missing print_stats: %+v", got) } info, ok := printStats["info"].(map[string]any) if !ok || info["current_layer"] != 2 { t.Fatalf("unexpected subscription info: %+v", got) } if got := moonrakerSubscriptionStatus(map[string]any{"method": "server.info"}); got != nil { t.Fatalf("non-status message returned %+v", got) } } func TestMoonrakerStatusCacheMergesPartialLayerUpdates(t *testing.T) { cache := &moonrakerStatusCache{} status, changed, _ := cache.update(map[string]any{ "print_stats": map[string]any{ "state": "printing", "filename": "benchy.gcode", "info": map[string]any{ "current_layer": 1, "total_layer": 5, }, }, }) if !changed || status == nil { t.Fatalf("initial status changed=%t status=%+v, want changed status", changed, status) } if status.CurrentLayer != 1 || status.TotalLayer != 5 { t.Fatalf("initial layers = %d/%d, want 1/5", status.CurrentLayer, status.TotalLayer) } status, changed, _ = cache.update(map[string]any{ "print_stats": map[string]any{ "info": map[string]any{ "current_layer": 2, }, }, }) if !changed || status == nil { t.Fatalf("layer update changed=%t status=%+v, want changed status", changed, status) } if status.State != "printing" || status.Filename != "benchy.gcode" { t.Fatalf("partial update lost print identity: %+v", status) } if status.CurrentLayer != 2 || status.TotalLayer != 5 { t.Fatalf("merged layers = %d/%d, want 2/5", status.CurrentLayer, status.TotalLayer) } _, changed, _ = cache.update(map[string]any{ "display_status": map[string]any{"progress": 0.42}, }) if !changed { t.Fatal("progress-only update should trigger notification heartbeat") } } func TestMoonrakerStatusCacheSnapshotAndReset(t *testing.T) { cache := &moonrakerStatusCache{} if got := cache.snapshot(time.Second); got != nil { t.Fatalf("expected empty cache snapshot to be nil, got %+v", got) } cache.update(map[string]any{ "print_stats": map[string]any{ "state": "printing", "filename": "benchy.gcode", }, }) if got := cache.snapshot(time.Minute); got == nil || got.State != "printing" || got.Filename != "benchy.gcode" { t.Fatalf("unexpected cached snapshot: %+v", got) } cache.reset() if got := cache.snapshot(time.Minute); got != nil { t.Fatalf("expected reset cache snapshot to be nil, got %+v", got) } } func TestSelectMoonrakerSubscriptionObjects(t *testing.T) { selected := selectMoonrakerSubscriptionObjects([]string{ "toolhead", "fan", "temperature_sensor chamber", "display_status", "heater_bed", "gcode_move", "print_stats", "controller_fan case", "bed_mesh", }) for _, want := range []string{"print_stats", "display_status", "gcode_move", "toolhead", "heater_bed", "fan", "temperature_sensor chamber", "controller_fan case"} { found := false for _, got := range selected { if got == want { found = true break } } if !found { t.Fatalf("selected objects missing %q: %+v", want, selected) } } } func TestCollectPrintStatusIncludesLayerFields(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/printer/objects/query" { http.NotFound(w, r) return } if got := r.URL.RawQuery; got != "print_stats&display_status&gcode_move&toolhead" { t.Fatalf("unexpected query = %q", got) } _ = json.NewEncoder(w).Encode(map[string]any{ "result": map[string]any{ "status": map[string]any{ "print_stats": map[string]any{ "state": "printing", "filename": "benchy.gcode", "message": "Layer change", "print_duration": 123.5, "total_duration": 456.5, "filament_used": 789.5, "estimated_time_remaining": 321.5, "info": map[string]any{ "current_layer": 2, "total_layer": 4, }, }, "display_status": map[string]any{ "progress": 0.42, "message": "Printing benchy", }, }, }, }) })) defer server.Close() base, err := url.Parse(server.URL) if err != nil { t.Fatal(err) } got := collectPrintStatus(base) if got == nil { t.Fatal("expected print status to be collected") } if got.State != "printing" { t.Fatalf("state = %q, want printing", got.State) } if got.Filename != "benchy.gcode" { t.Fatalf("filename = %q, want benchy.gcode", got.Filename) } if got.CurrentLayer != 2 { t.Fatalf("current_layer = %d, want 2", got.CurrentLayer) } if got.TotalLayer != 4 { t.Fatalf("total_layer = %d, want 4", got.TotalLayer) } if got.Progress != 0.42 { t.Fatalf("progress = %v, want 0.42", got.Progress) } if got.MoonrakerStatus == nil { t.Fatal("expected raw moonraker status to be preserved") } if _, ok := got.MoonrakerStatus["display_status"].(map[string]any); !ok { t.Fatalf("raw moonraker status missing display_status: %+v", got.MoonrakerStatus) } } func TestCollectPrintStatusDoesNotUseMetadataForLayers(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/printer/objects/query", func(w http.ResponseWriter, r *http.Request) { if got := r.URL.RawQuery; got != "print_stats&display_status&gcode_move&toolhead" { t.Fatalf("unexpected query = %q", got) } _ = json.NewEncoder(w).Encode(map[string]any{ "result": map[string]any{ "status": map[string]any{ "print_stats": map[string]any{ "state": "printing", "filename": "benchy.gcode", "message": "Layer change", "print_duration": 123.5, "total_duration": 456.5, "filament_used": 789.5, "estimated_time_remaining": 321.5, "info": map[string]any{ "current_layer": 0, "total_layer": 0, }, }, "display_status": map[string]any{ "progress": 0.42, "message": "Printing benchy", }, "gcode_move": map[string]any{ "position": []float64{0, 0, 0.41}, }, "toolhead": map[string]any{ "position": []float64{0, 0, 0.42}, }, }, }, }) }) mux.HandleFunc("/server/files/metadata", func(w http.ResponseWriter, r *http.Request) { if got := r.URL.Query().Get("filename"); got != "benchy.gcode" { t.Fatalf("metadata filename = %q, want benchy.gcode", got) } _ = json.NewEncoder(w).Encode(map[string]any{ "result": map[string]any{ "metadata": map[string]any{ "layer_height": 0.2, "first_layer_height": 0.2, "object_height": 0.8, }, }, }) }) server := httptest.NewServer(mux) defer server.Close() base, err := url.Parse(server.URL) if err != nil { t.Fatal(err) } got := collectPrintStatus(base) if got == nil { t.Fatal("expected print status to be collected") } if got.CurrentLayer != 0 { t.Fatalf("current_layer = %d, want 0", got.CurrentLayer) } if got.TotalLayer != 0 { t.Fatalf("total_layer = %d, want 0", got.TotalLayer) } if got.LayerSource != "" { t.Fatalf("layer_source = %q, want empty", got.LayerSource) } if got.MoonrakerMetadata != nil { t.Fatalf("moonraker metadata = %+v, want nil", got.MoonrakerMetadata) } }