Files
2026-05-14 02:27:26 +01:00

1583 lines
54 KiB
Go

package main
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"net/url"
"mime/multipart"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/klipperanywhere/klipperanywhere/internal/protocol"
)
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
func TestParseProxyPath(t *testing.T) {
printerID, path, ok := parseProxyPath("/p/test/moonraker/printer/info")
if !ok {
t.Fatal("expected path to parse")
}
if printerID != "test" {
t.Fatalf("printer id = %q, want test", printerID)
}
if path != "/printer/info" {
t.Fatalf("path = %q, want /printer/info", path)
}
}
func TestParseCameraPath(t *testing.T) {
printerID, camera, kind, ok := parseCameraPath("/p/real-printer/camera/Camera/snapshot")
if !ok {
t.Fatal("expected camera path to parse")
}
if printerID != "real-printer" || camera != "Camera" || kind != "snapshot" {
t.Fatalf("got %q %q %q", printerID, camera, kind)
}
}
func TestNotificationSnapshotCamera(t *testing.T) {
health := &protocol.Health{Cameras: []protocol.CameraHealth{
{Name: "wide", HasSnapshot: true},
{Name: "nozzle", HasSnapshot: true},
{Name: "stream-only", HasSnapshot: false, HasStream: true},
}}
name, camera := notificationSnapshotCamera(health, "")
if name != "wide" || camera == nil || camera.Name != "wide" {
t.Fatalf("default camera = %q %#v, want wide", name, camera)
}
name, camera = notificationSnapshotCamera(health, "nozzle")
if name != "nozzle" || camera == nil || camera.Name != "nozzle" {
t.Fatalf("preferred camera = %q %#v, want nozzle", name, camera)
}
name, camera = notificationSnapshotCamera(health, "missing")
if name != "wide" || camera == nil || camera.Name != "wide" {
t.Fatalf("missing preferred camera = %q %#v, want wide fallback", name, camera)
}
name, camera = notificationSnapshotCamera(health, "stream-only")
if name != "" || camera != nil {
t.Fatalf("non-snapshot preferred camera = %q %#v, want none", name, camera)
}
}
func TestNotificationSnapshotCameraAllowed(t *testing.T) {
health := &protocol.Health{Cameras: []protocol.CameraHealth{
{Name: "wide", HasSnapshot: true},
{Name: "stream-only", HasSnapshot: false, HasStream: true},
}}
if !notificationSnapshotCameraAllowed(health, "") {
t.Fatal("blank preferred camera should be allowed")
}
if !notificationSnapshotCameraAllowed(health, "wide") {
t.Fatal("snapshot-capable camera should be allowed")
}
if notificationSnapshotCameraAllowed(health, "stream-only") {
t.Fatal("stream-only camera should not be allowed")
}
if notificationSnapshotCameraAllowed(health, "missing") {
t.Fatal("missing camera should not be allowed")
}
}
func TestNotificationSettingsStoreDefaultsCommandsToDelivery(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "notification-settings.json")
if err := os.WriteFile(path, []byte(`{"telegram_enabled":true,"telegram_bot_token":"bot123","telegram_chat_id":"chat456"}`), 0o600); err != nil {
t.Fatalf("failed to write settings file: %v", err)
}
store, err := newNotificationSettingsStore(path)
if err != nil {
t.Fatalf("newNotificationSettingsStore returned error: %v", err)
}
snapshot := store.snapshot()
if !snapshot.TelegramEnabled {
t.Fatal("expected telegram delivery to remain enabled")
}
if !snapshot.TelegramCommandsEnabled {
t.Fatal("expected telegram commands to default to delivery state for legacy settings")
}
}
func TestPublicNotificationSettingsIncludesCommandsToggle(t *testing.T) {
settings := publicNotificationSettings(notificationSettingsRecord{
TelegramEnabled: true,
TelegramCommandsEnabled: false,
TelegramBotToken: "bot123",
TelegramChatID: "chat456",
})
if got, ok := settings["telegram_commands_enabled"].(bool); !ok || got {
t.Fatalf("telegram_commands_enabled = %v, want false", settings["telegram_commands_enabled"])
}
}
func TestParsePrinterAPIPath(t *testing.T) {
printerID, action, ok := parsePrinterAPIPath("/api/printers/test")
if !ok {
t.Fatal("expected printer detail path to parse")
}
if printerID != "test" || action != "" {
t.Fatalf("got %q %q", printerID, action)
}
printerID, action, ok = parsePrinterAPIPath("/api/printers/test/health")
if !ok {
t.Fatal("expected printer health path to parse")
}
if printerID != "test" || action != "health" {
t.Fatalf("got %q %q", printerID, action)
}
}
func TestParsePrinterUIPath(t *testing.T) {
printerID, path, ok := parsePrinterUIPath("/printers/test/ui/")
if !ok {
t.Fatal("expected printer ui path to parse")
}
if printerID != "test" || path != "/" {
t.Fatalf("got %q %q", printerID, path)
}
printerID, path, ok = parsePrinterUIPath("/printers/test/ui/assets/app.js")
if !ok {
t.Fatal("expected nested printer ui path to parse")
}
if printerID != "test" || path != "/assets/app.js" {
t.Fatalf("got %q %q", printerID, path)
}
}
func TestParsePrinterRootPath(t *testing.T) {
printerID, ok := parsePrinterRootPath("/printers/test")
if !ok || printerID != "test" {
t.Fatalf("got %q %t", printerID, ok)
}
}
func TestParsePrinterSettingsPath(t *testing.T) {
printerID, ok := parsePrinterSettingsPath("/printers/test/settings")
if !ok || printerID != "test" {
t.Fatalf("got %q %t", printerID, ok)
}
if _, ok := parsePrinterSettingsPath("/printers/test/ui"); ok {
t.Fatal("ui path should not parse as settings path")
}
}
func TestParsePrinterAgentPath(t *testing.T) {
printerID, ok := parsePrinterAgentPath("/printers/test/agent")
if !ok || printerID != "test" {
t.Fatalf("got %q %t", printerID, ok)
}
if _, ok := parsePrinterAgentPath("/printers/test/settings"); ok {
t.Fatal("settings path should not parse as agent path")
}
}
func TestLegacyWebcamPrinterIDCookieFallback(t *testing.T) {
r := &http.Request{Header: http.Header{}}
r.AddCookie(&http.Cookie{Name: "ka_printer_context", Value: "real-printer"})
printerID, ok := legacyWebcamPrinterID(r)
if !ok {
t.Fatal("expected cookie fallback to resolve printer id")
}
if printerID != "real-printer" {
t.Fatalf("printer id = %q, want real-printer", printerID)
}
}
func TestPublicPrinterUIAsset(t *testing.T) {
if !isPublicPrinterUIAsset("/printers/real-printer/ui/manifest.webmanifest") {
t.Fatal("manifest should be public")
}
if !isPublicPrinterUIAsset("/printers/real-printer/ui/sw.js") {
t.Fatal("sw should be public")
}
if isPublicPrinterUIAsset("/printers/real-printer/ui/assets/app.js") {
t.Fatal("regular assets should not be public by default")
}
}
func TestRewriteUIResponse(t *testing.T) {
body := []byte(`<html><link href="/assets/app.css"><script src="/assets/app.js"></script><script>fetch("/printer/info"); const ws="ws://127.0.0.1:7125/websocket"; const api="http://127.0.0.1:7125";</script></html>`)
rewritten := string(rewriteUIResponse([]protocol.Header{{
Name: "Content-Type",
Values: []string{"text/html; charset=utf-8"},
}}, body, "test"))
for _, want := range []string{
`href="/printers/test/ui/assets/app.css"`,
`src="/printers/test/ui/assets/app.js"`,
`fetch("/p/test/moonraker/printer/info")`,
`"/p/test/moonraker"`,
`"/p/test/moonraker/websocket"`,
`window.__KA_PRINTER_ID = "test"`,
`window.__KA_UI_PRINTER_TOKEN = "test"`,
`rewriteWebSocketUrl`,
`proto.getItem = function`,
} {
if !strings.Contains(rewritten, want) {
t.Fatalf("rewritten response missing %q in %s", want, rewritten)
}
}
}
func TestInjectPrinterUIResetScript(t *testing.T) {
rewritten := injectPrinterUIResetScript(`<html><head></head><body></body></html>`, "rockchip")
for _, want := range []string{
`currentUrl.searchParams.set("printer", "rockchip")`,
`window.__KA_PRINTER_ID = "rockchip"`,
`window.__KA_UI_PRINTER_TOKEN = "rockchip"`,
`var storagePrefix = "ka-ui-rockchip:"`,
`window.WebSocket`,
} {
if !strings.Contains(rewritten, want) {
t.Fatalf("injected script missing %q in %s", want, rewritten)
}
}
}
func TestInjectPrinterUIResetScriptIsPrinterSpecific(t *testing.T) {
rockchip := injectPrinterUIResetScript(`<html><head></head><body></body></html>`, "rockchip")
f005 := injectPrinterUIResetScript(`<html><head></head><body></body></html>`, "f005-020b")
for _, want := range []string{
`currentUrl.searchParams.set("printer", "rockchip")`,
`window.__KA_PRINTER_ID = "rockchip"`,
`window.__KA_UI_PRINTER_TOKEN = "rockchip"`,
`var storagePrefix = "ka-ui-rockchip:"`,
`/p/rockchip/moonraker/websocket`,
} {
if !strings.Contains(rockchip, want) {
t.Fatalf("rockchip script missing %q in %s", want, rockchip)
}
}
for _, want := range []string{
`currentUrl.searchParams.set("printer", "f005-020b")`,
`window.__KA_PRINTER_ID = "f005-020b"`,
`window.__KA_UI_PRINTER_TOKEN = "f005-020b"`,
`var storagePrefix = "ka-ui-f005-020b:"`,
`/p/f005-020b/moonraker/websocket`,
} {
if !strings.Contains(f005, want) {
t.Fatalf("f005 script missing %q in %s", want, f005)
}
}
if rockchip == f005 {
t.Fatal("expected printer bootstrap scripts to differ between printers")
}
}
func TestSanitizeUIProxyQuery(t *testing.T) {
if got := sanitizeUIProxyQuery("printer=abc123&foo=bar"); got != "foo=bar" {
t.Fatalf("unexpected sanitized query: %q", got)
}
if got := sanitizeUIProxyQuery("foo=bar&printer=abc123"); got != "foo=bar" {
t.Fatalf("unexpected sanitized query order: %q", got)
}
if got := sanitizeUIProxyQuery("foo=bar"); got != "foo=bar" {
t.Fatalf("unexpected passthrough query: %q", got)
}
}
func TestRewriteMoonrakerDatabaseNamespace(t *testing.T) {
got := rewriteMoonrakerDatabaseNamespace("/server/database/item?namespace=fluidd", "rockchip")
if got != "/server/database/item?namespace=fluidd-rockchip" {
t.Fatalf("unexpected rewritten database namespace: %q", got)
}
got = rewriteMoonrakerDatabaseNamespace("/server/database/item?namespace=fluidd", "f005-020b")
if got != "/server/database/item?namespace=fluidd-f005-020b" {
t.Fatalf("unexpected rewritten database namespace for f005: %q", got)
}
got = rewriteMoonrakerDatabaseNamespace("/server/database/item?namespace=fluidd-rockchip", "rockchip")
if got != "/server/database/item?namespace=fluidd-rockchip" {
t.Fatalf("unexpected preserved database namespace: %q", got)
}
got = rewriteMoonrakerDatabaseNamespace("/server/database/item?namespace=other", "rockchip")
if got != "/server/database/item?namespace=other" {
t.Fatalf("unexpected non-fluidd namespace rewrite: %q", got)
}
}
func TestRewriteFluiddConfig(t *testing.T) {
body := []byte(`{"blacklist":["fluidd.xyz"],"endpoints":[],"hosted":false}`)
rewritten := string(rewriteFluiddConfig(body, "https://example.com", "real-printer"))
if !strings.Contains(rewritten, `"endpoints": [`) {
t.Fatalf("rewritten config missing endpoints array: %s", rewritten)
}
if !strings.Contains(rewritten, `https://example.com/p/real-printer/moonraker`) {
t.Fatalf("rewritten config missing printer endpoint: %s", rewritten)
}
}
func TestRewriteMoonrakerWebcams(t *testing.T) {
body := []byte(`{"result":{"webcams":[{"name":"Camera","service":"mjpegstreamer-adaptive","stream_url":"/webcam/?action=stream","snapshot_url":"/webcam/?action=snapshot"}]}}`)
rewritten := string(rewriteMoonrakerWebcams(body, "real-printer"))
if !strings.Contains(rewritten, `/p/real-printer/camera/Camera/stream`) {
t.Fatalf("rewritten webcams missing stream url: %s", rewritten)
}
if !strings.Contains(rewritten, `/p/real-printer/camera/Camera/snapshot`) {
t.Fatalf("rewritten webcams missing snapshot url: %s", rewritten)
}
if !strings.Contains(rewritten, `"service": "mjpegstreamer"`) {
t.Fatalf("rewritten webcams missing normalized service: %s", rewritten)
}
}
func TestParseMoonrakerPrintStatus(t *testing.T) {
body := []byte(`{"result":{"status":{"print_stats":{"state":"printing","filename":"benchy.gcode","print_duration":12.5,"total_duration":24.5,"filament_used":34.2},"display_status":{"progress":0.5}}}}`)
status, err := parseMoonrakerPrintStatus(body)
if err != nil {
t.Fatalf("parseMoonrakerPrintStatus returned error: %v", err)
}
printStats, ok := status["print_stats"].(map[string]any)
if !ok {
t.Fatalf("missing print_stats: %+v", status)
}
if got, _ := printStats["state"].(string); got != "printing" {
t.Fatalf("state = %q, want printing", got)
}
if got, _ := printStats["filename"].(string); got != "benchy.gcode" {
t.Fatalf("filename = %q, want benchy.gcode", got)
}
displayStatus, ok := status["display_status"].(map[string]any)
if !ok {
t.Fatalf("missing display_status: %+v", status)
}
if got, _ := displayStatus["progress"].(float64); got != 0.5 {
t.Fatalf("progress = %v, want 0.5", got)
}
}
func TestPrintStatusFromHealth(t *testing.T) {
status := printStatusFromHealth(&protocol.Health{
PrintStatus: &protocol.PrintStatus{
State: "printing",
Filename: "benchy.gcode",
Message: "Printing benchy",
Progress: 0.5,
PrintDuration: 12.5,
TotalDuration: 24.5,
FilamentUsed: 34.2,
EstimatedTimeRemaining: 120.0,
MoonrakerStatus: map[string]any{
"print_stats": map[string]any{"state": "printing"},
},
MoonrakerMetadata: map[string]any{
"metadata": map[string]any{"layer_height": 0.2},
},
LayerSource: "metadata",
},
})
if status == nil {
t.Fatal("expected cached print status")
}
printStats, ok := status["print_stats"].(map[string]any)
if !ok {
t.Fatalf("missing print_stats: %+v", status)
}
if got, _ := printStats["state"].(string); got != "printing" {
t.Fatalf("state = %q, want printing", got)
}
displayStatus, ok := status["display_status"].(map[string]any)
if !ok {
t.Fatalf("missing display_status: %+v", status)
}
if got, _ := displayStatus["progress"].(float64); got != 0.5 {
t.Fatalf("progress = %v, want 0.5", got)
}
if _, ok := status["moonraker_status"].(map[string]any); !ok {
t.Fatalf("missing moonraker_status: %+v", status)
}
if _, ok := status["moonraker_metadata"].(map[string]any); !ok {
t.Fatalf("missing moonraker_metadata: %+v", status)
}
if got, _ := status["layer_source"].(string); got != "metadata" {
t.Fatalf("layer_source = %q, want metadata", got)
}
}
func TestParseMoonrakerJobHistory(t *testing.T) {
body := []byte(`{"result":{"jobs":[{"filename":"benchy.gcode","status":"completed","total_duration":3600.0,"print_duration":3555.0,"start_time":100,"end_time":200,"message":"done"}]}}`)
jobs, err := parseMoonrakerJobHistory(body)
if err != nil {
t.Fatalf("parseMoonrakerJobHistory returned error: %v", err)
}
if len(jobs) != 1 {
t.Fatalf("jobs length = %d, want 1", len(jobs))
}
if got, _ := jobs[0]["filename"].(string); got != "benchy.gcode" {
t.Fatalf("filename = %q, want benchy.gcode", got)
}
}
func TestRequestOrigin(t *testing.T) {
r := &http.Request{
Header: http.Header{
"X-Forwarded-Proto": []string{"https"},
},
Host: "printer.example.com",
}
if got := requestOrigin(r); got != "https://printer.example.com" {
t.Fatalf("requestOrigin = %q, want https://printer.example.com", got)
}
}
func TestRequestAgentTunnelURL(t *testing.T) {
if got := requestAgentTunnelURL("https://printer.example.com"); got != "wss://printer.example.com/agent/tunnel" {
t.Fatalf("requestAgentTunnelURL = %q", got)
}
if got := requestAgentTunnelURL("http://printer.example.com"); got != "ws://printer.example.com/agent/tunnel" {
t.Fatalf("requestAgentTunnelURL = %q", got)
}
}
func TestOriginIsLoopback(t *testing.T) {
for _, origin := range []string{
"http://127.0.0.1:8080",
"https://localhost",
"http://[::1]:8080",
} {
if !originIsLoopback(origin) {
t.Fatalf("expected %q to be loopback", origin)
}
}
if originIsLoopback("https://klipperanywhere.example.com") {
t.Fatal("expected public origin to be non-loopback")
}
}
func TestReleaseAssetForMachine(t *testing.T) {
tests := map[string]string{
"amd64": "klipperanywhere-agent-linux-amd64",
"aarch64": "klipperanywhere-agent-linux-arm64",
"armv7l": "klipperanywhere-agent-linux-armv7",
"mipsel": "klipperanywhere-agent-linux-mipsle",
}
for machine, want := range tests {
got, err := releaseAssetForMachine(machine)
if err != nil {
t.Fatalf("releaseAssetForMachine(%q) returned error: %v", machine, err)
}
if got != want {
t.Fatalf("releaseAssetForMachine(%q) = %q, want %q", machine, got, want)
}
}
}
func TestDescribeLoadedAgentBinary(t *testing.T) {
tests := map[string]string{
"source": "Built agent binary from the server container source.",
"bundled": "Loaded bundled agent binary from the server container.",
"release": "Downloaded release agent binary from https://example.test/releases.",
}
for source, want := range tests {
if got := describeLoadedAgentBinary(source, "https://example.test/releases"); got != want {
t.Fatalf("describeLoadedAgentBinary(%q) = %q, want %q", source, got, want)
}
}
}
func TestBuildSSHInstallConfig(t *testing.T) {
uiAutoDetect := false
body := buildSSHInstallConfig("https://printer.example.com", "real-printer", "agent-token", sshInstallRequest{
MoonrakerURL: "http://192.168.1.60:7125",
UIURL: "http://192.168.1.60",
UIAutoDetect: &uiAutoDetect,
})
text := string(body)
for _, want := range []string{
`"server_url": "wss://printer.example.com/agent/tunnel"`,
`"printer_id": "real-printer"`,
`"token": "agent-token"`,
`"moonraker_url": "http://192.168.1.60:7125"`,
`"ui_url": "http://192.168.1.60"`,
`"ui_auto_detect": false`,
} {
if !strings.Contains(text, want) {
t.Fatalf("config missing %q: %s", want, text)
}
}
}
func TestBuildSSHInstallConfigWithStateFile(t *testing.T) {
body := buildSSHInstallConfigWithStateFile("https://printer.example.com", "real-printer", "agent-token", sshInstallRequest{}, "/useremain/home/rinkhals/apps/60-klipperanywhere-agent/agent-state.json")
text := string(body)
if !strings.Contains(text, `"state_file": "/useremain/home/rinkhals/apps/60-klipperanywhere-agent/agent-state.json"`) {
t.Fatalf("config missing state_file: %s", text)
}
}
func TestNormalizeInstallHostType(t *testing.T) {
tests := map[string]string{
"": installHostTypeStandard,
"standard": installHostTypeStandard,
"Rinkhals": installHostTypeRinkhals,
"unknown": installHostTypeStandard,
" rinkhals ": installHostTypeRinkhals,
}
for input, want := range tests {
if got := normalizeInstallHostType(input); got != want {
t.Fatalf("normalizeInstallHostType(%q) = %q, want %q", input, got, want)
}
}
}
func TestResolveInstallServerURL(t *testing.T) {
got, err := resolveInstallServerURL("http://127.0.0.1:8080", "https://printer.example.com")
if err != nil {
t.Fatalf("resolveInstallServerURL returned error: %v", err)
}
if got != "https://printer.example.com" {
t.Fatalf("resolveInstallServerURL = %q, want https://printer.example.com", got)
}
if _, err := resolveInstallServerURL("http://127.0.0.1:8080", "http://localhost:8080"); err == nil {
t.Fatal("expected loopback server url to be rejected")
}
got, err = resolveInstallServerURL("https://printer.example.com", "")
if err != nil {
t.Fatalf("resolveInstallServerURL fallback returned error: %v", err)
}
if got != "https://printer.example.com" {
t.Fatalf("resolveInstallServerURL fallback = %q, want https://printer.example.com", got)
}
}
func TestMoonrakerRequestHeaders(t *testing.T) {
headers := moonrakerRequestHeaders(http.Header{
"If-None-Match": []string{"abc"},
"If-Modified-Since": []string{"yesterday"},
"If-Range": []string{"range"},
"Cache-Control": []string{"max-age=0"},
"Accept": []string{"application/json"},
})
for _, h := range headers {
if strings.EqualFold(h.Name, "If-None-Match") || strings.EqualFold(h.Name, "If-Modified-Since") || strings.EqualFold(h.Name, "If-Range") || strings.EqualFold(h.Name, "Cache-Control") {
t.Fatalf("unexpected header preserved: %s", h.Name)
}
}
foundAccept := false
for _, h := range headers {
if strings.EqualFold(h.Name, "Accept") {
foundAccept = true
}
}
if !foundAccept {
t.Fatal("expected Accept header to be preserved")
}
}
func TestWriteResponseHeadersStripsHopByHopHeaders(t *testing.T) {
w := httptest.NewRecorder()
writeResponseHeaders(w, protocol.Message{
Headers: []protocol.Header{
{Name: "Content-Type", Values: []string{"multipart/x-mixed-replace; boundary=frame"}},
{Name: "Content-Length", Values: []string{"123"}},
{Name: "Transfer-Encoding", Values: []string{"chunked"}},
{Name: "Connection", Values: []string{"keep-alive"}},
{Name: "Keep-Alive", Values: []string{"timeout=5"}},
{Name: "Cache-Control", Values: []string{"no-cache"}},
},
})
if got := w.Header().Get("Content-Type"); got != "multipart/x-mixed-replace; boundary=frame" {
t.Fatalf("content-type = %q", got)
}
if got := w.Header().Get("Cache-Control"); got != "no-cache" {
t.Fatalf("cache-control = %q", got)
}
for _, name := range []string{"Content-Length", "Transfer-Encoding", "Connection", "Keep-Alive"} {
if got := w.Header().Get(name); got != "" {
t.Fatalf("%s should be stripped, got %q", name, got)
}
}
}
func TestUIProxySpecialPaths(t *testing.T) {
manifest := httptest.NewRecorder()
manifest.WriteHeader(http.StatusOK)
manifestBody := []byte(`{"name":"fluidd"}`)
manifestHeader := protocol.Message{
Headers: []protocol.Header{{Name: "Content-Type", Values: []string{"application/octet-stream"}}},
}
writeResponseHeaders(manifest, manifestHeader)
manifest.Header().Set("Cache-Control", "no-store, max-age=0")
manifest.Header().Set("Content-Type", "application/manifest+json")
if got := manifest.Header().Get("Content-Type"); got != "application/manifest+json" {
t.Fatalf("manifest content-type = %q", got)
}
_ = manifestBody
sw := httptest.NewRecorder()
writeResponseHeaders(sw, protocol.Message{})
sw.Header().Set("Content-Type", "application/javascript")
if got := sw.Header().Get("Content-Type"); got != "application/javascript" {
t.Fatalf("sw content-type = %q", got)
}
}
func TestReadOnlyMoonrakerRequestPolicy(t *testing.T) {
tests := []struct {
method string
path string
want bool
}{
{http.MethodGet, "/printer/info", true},
{http.MethodPost, "/printer/gcode/script", false},
{http.MethodPost, "/server/files/upload", false},
{http.MethodPost, "/printer/print/pause", false},
{http.MethodPost, "/printer/print/cancel", false},
{http.MethodPost, "/printer/emergency_stop", false},
}
for _, tt := range tests {
if got := isReadOnlyMoonrakerRequest(tt.method, tt.path); got != tt.want {
t.Fatalf("isReadOnlyMoonrakerRequest(%q, %q) = %t, want %t", tt.method, tt.path, got, tt.want)
}
}
}
func TestReadOnlyMoonrakerWebSocketPolicy(t *testing.T) {
tests := []struct {
payload string
want bool
}{
{`{"jsonrpc":"2.0","method":"printer.objects.subscribe","id":1}`, true},
{`{"jsonrpc":"2.0","method":"server.info","id":2}`, true},
{`{"jsonrpc":"2.0","method":"server.files.get_directory","id":5}`, true},
{`{"jsonrpc":"2.0","method":"printer.gcode.script","id":3}`, false},
{`{"jsonrpc":"2.0","method":"printer.print.pause","id":4}`, false},
{`{"jsonrpc":"2.0","method":"server.files.upload","id":6}`, false},
}
for _, tt := range tests {
if got := isReadOnlyMoonrakerWebSocketPayload([]byte(tt.payload)); got != tt.want {
t.Fatalf("isReadOnlyMoonrakerWebSocketPayload(%s) = %t, want %t", tt.payload, got, tt.want)
}
}
}
func TestControlModeForPrinterUsesStoredSettings(t *testing.T) {
s := &server{
controlMode: "readonly",
printerSettings: &printerSettingsStore{
records: map[string]printerSettingsRecord{
"real-printer": {
PrinterID: "real-printer",
ControlMode: "full",
},
},
},
}
if got := s.controlModeForPrinter("real-printer", &protocol.Health{ControlMode: "readonly"}); got != "full" {
t.Fatalf("controlModeForPrinter = %q, want full", got)
}
if got := s.controlModeForPrinter("missing", nil); got != "readonly" {
t.Fatalf("controlModeForPrinter = %q, want readonly", got)
}
}
func TestPrinterSettingsSyncStatus(t *testing.T) {
s := &server{
controlMode: "readonly",
printerSettings: &printerSettingsStore{
records: map[string]printerSettingsRecord{
"real-printer": {
PrinterID: "real-printer",
ControlMode: "full",
UIURL: "http://192.168.1.60",
UIAutoDetect: false,
UpdatedAt: time.Now().UTC(),
LastSyncedAt: time.Now().UTC(),
},
},
},
}
synced, state, detail := s.printerSettingsSyncStatus("real-printer", &protocol.Health{
ControlMode: "full",
UIURL: "http://192.168.1.60",
UIAutoDetect: false,
})
if !synced || state != "Synced" {
t.Fatalf("expected synced state, got synced=%t state=%q detail=%q", synced, state, detail)
}
s.printerSettings.records["real-printer"] = printerSettingsRecord{
PrinterID: "real-printer",
ControlMode: "full",
UIURL: "http://192.168.1.60",
UIAutoDetect: false,
UpdatedAt: time.Now().UTC(),
LastSyncedAt: time.Time{},
}
synced, state, detail = s.printerSettingsSyncStatus("real-printer", &protocol.Health{
ControlMode: "readonly",
UIURL: "http://192.168.1.60",
UIAutoDetect: false,
})
if synced || state != "Pending" {
t.Fatalf("expected pending state, got synced=%t state=%q detail=%q", synced, state, detail)
}
if !strings.Contains(detail, "Waiting for the agent to confirm the latest settings.") {
t.Fatalf("pending detail missing confirmation text: %q", detail)
}
}
func TestTelegramNotifierSendTestNotification(t *testing.T) {
var gotRequest *http.Request
var gotBody string
notifier := &telegramNotifier{
client: &http.Client{
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
gotRequest = req
body, _ := io.ReadAll(req.Body)
gotBody = string(body)
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
Header: make(http.Header),
Request: req,
}, nil
}),
},
settings: &notificationSettingsStore{
record: notificationSettingsRecord{
TelegramEnabled: false,
TelegramBotToken: "bot123",
TelegramChatID: "chat456",
},
},
}
if err := notifier.SendTestNotification(context.Background(), ""); err != nil {
t.Fatalf("SendTestNotification returned error: %v", err)
}
if gotRequest == nil {
t.Fatal("expected telegram request to be sent")
}
if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/sendMessage" {
t.Fatalf("request url = %q, want telegram sendMessage endpoint", got)
}
values, err := url.ParseQuery(gotBody)
if err != nil {
t.Fatalf("failed to parse form body: %v", err)
}
if got := values.Get("chat_id"); got != "chat456" {
t.Fatalf("chat_id = %q, want chat456", got)
}
if got := values.Get("text"); !strings.Contains(got, "KlipperAnywhere test notification") {
t.Fatalf("text = %q, want test notification message", got)
}
}
func TestTelegramNotifierSendPhoto(t *testing.T) {
var gotRequest *http.Request
var gotContentType string
var gotBody []byte
notifier := &telegramNotifier{
client: &http.Client{
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
gotRequest = req
gotContentType = req.Header.Get("Content-Type")
body, _ := io.ReadAll(req.Body)
gotBody = append([]byte(nil), body...)
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
Header: make(http.Header),
Request: req,
}, nil
}),
},
}
snapshot := []byte{0x01, 0x02, 0x03, 0x04}
if err := notifier.sendTelegramPhoto(context.Background(), "bot123", "chat456", "Print started", snapshot, "snapshot.jpg"); err != nil {
t.Fatalf("sendTelegramPhoto returned error: %v", err)
}
if gotRequest == nil {
t.Fatal("expected telegram request to be sent")
}
if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/sendPhoto" {
t.Fatalf("request url = %q, want telegram sendPhoto endpoint", got)
}
if !strings.HasPrefix(gotContentType, "multipart/form-data; boundary=") {
t.Fatalf("content-type = %q, want multipart form", gotContentType)
}
mr := multipart.NewReader(bytes.NewReader(gotBody), strings.TrimPrefix(gotContentType, "multipart/form-data; boundary="))
fields := map[string]string{}
var photoName string
var photoBody []byte
for {
part, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("failed to parse multipart body: %v", err)
}
data, err := io.ReadAll(part)
if err != nil {
t.Fatalf("failed to read multipart part: %v", err)
}
switch part.FormName() {
case "chat_id", "caption":
fields[part.FormName()] = string(data)
case "photo":
photoName = part.FileName()
photoBody = append([]byte(nil), data...)
}
}
if got := fields["chat_id"]; got != "chat456" {
t.Fatalf("chat_id = %q, want chat456", got)
}
if got := fields["caption"]; got != "Print started" {
t.Fatalf("caption = %q, want Print started", got)
}
if photoName != "snapshot.jpg" {
t.Fatalf("photo filename = %q, want snapshot.jpg", photoName)
}
if !bytes.Equal(photoBody, snapshot) {
t.Fatalf("photo body = %x, want %x", photoBody, snapshot)
}
}
func TestTelegramNotifierAddsCheckInButton(t *testing.T) {
var gotRequest *http.Request
var gotBody string
notifier := &telegramNotifier{
client: &http.Client{
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
gotRequest = req
body, _ := io.ReadAll(req.Body)
gotBody = string(body)
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
Header: make(http.Header),
Request: req,
}, nil
}),
},
settings: &notificationSettingsStore{
record: notificationSettingsRecord{
TelegramEnabled: true,
TelegramBotToken: "bot123",
TelegramChatID: "chat456",
},
},
}
record := printerSettingsRecord{
PrinterID: "Rockchip",
Install: &printerInstallRecord{
ServerURL: "wss://services.example.com/agent/tunnel",
},
}
health := &protocol.Health{
PrintStatus: &protocol.PrintStatus{
State: "printing",
Filename: "benchy.gcode",
},
}
if err := notifier.NotifyPrinterPrintStatus(context.Background(), "Rockchip", record, health, nil, ""); err != nil {
t.Fatalf("NotifyPrinterPrintStatus returned error: %v", err)
}
if gotRequest == nil {
t.Fatal("expected telegram request to be sent")
}
if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/sendMessage" {
t.Fatalf("request url = %q, want telegram sendMessage endpoint", got)
}
values, err := url.ParseQuery(gotBody)
if err != nil {
t.Fatalf("failed to parse form body: %v", err)
}
replyMarkup := values.Get("reply_markup")
if replyMarkup == "" {
t.Fatal("expected reply_markup to be present")
}
if !strings.Contains(replyMarkup, `"text":"Printer overview"`) {
t.Fatalf("reply_markup = %q, want Printer overview button", replyMarkup)
}
if !strings.Contains(replyMarkup, "https://services.example.com/printers/Rockchip") {
t.Fatalf("reply_markup = %q, want printer overview url", replyMarkup)
}
}
func TestTelegramNotifierDeleteMessage(t *testing.T) {
var gotRequest *http.Request
var gotBody string
notifier := &telegramNotifier{
client: &http.Client{
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
gotRequest = req
body, _ := io.ReadAll(req.Body)
gotBody = string(body)
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
Header: make(http.Header),
Request: req,
}, nil
}),
},
}
if err := notifier.deleteTelegramMessage(context.Background(), "bot123", "chat456", 99); err != nil {
t.Fatalf("deleteTelegramMessage returned error: %v", err)
}
if gotRequest == nil {
t.Fatal("expected telegram request to be sent")
}
if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/deleteMessage" {
t.Fatalf("request url = %q, want deleteMessage endpoint", got)
}
values, err := url.ParseQuery(gotBody)
if err != nil {
t.Fatalf("failed to parse form body: %v", err)
}
if got := values.Get("chat_id"); got != "chat456" {
t.Fatalf("chat_id = %q, want chat456", got)
}
if got := values.Get("message_id"); got != "99" {
t.Fatalf("message_id = %q, want 99", got)
}
}
func TestTelegramNotifierSetCommandMenu(t *testing.T) {
var gotRequest *http.Request
var gotBody string
notifier := &telegramNotifier{
client: &http.Client{
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
gotRequest = req
body, _ := io.ReadAll(req.Body)
gotBody = string(body)
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
Header: make(http.Header),
Request: req,
}, nil
}),
},
}
if err := notifier.setTelegramCommandMenu(context.Background(), "bot123", telegramCommandMenu()); err != nil {
t.Fatalf("setTelegramCommandMenu returned error: %v", err)
}
if gotRequest == nil {
t.Fatal("expected telegram request to be sent")
}
if got := gotRequest.URL.String(); got != "https://api.telegram.org/botbot123/setMyCommands" {
t.Fatalf("request url = %q, want setMyCommands endpoint", got)
}
if !strings.Contains(gotBody, `"commands"`) || !strings.Contains(gotBody, `"print"`) || !strings.Contains(gotBody, `"camera"`) || !strings.Contains(gotBody, `"set"`) || !strings.Contains(gotBody, `"all_private_chats"`) {
t.Fatalf("command menu payload missing expected commands: %s", gotBody)
}
}
func TestPrinterLayerNotificationEvent(t *testing.T) {
if got := printerLayerNotificationEvents(0, 2, "printing"); len(got) != 1 || got[0] != "first_layer" {
t.Fatalf("first layer events = %v, want [first_layer]", got)
}
if got := printerLayerNotificationEvents(2, 4, "printing"); len(got) != 1 || got[0] != "third_layer" {
t.Fatalf("third layer events = %v, want [third_layer]", got)
}
if got := printerLayerNotificationEvents(0, 4, "printing"); len(got) != 2 || got[0] != "first_layer" || got[1] != "third_layer" {
t.Fatalf("crossing events = %v, want [first_layer third_layer]", got)
}
if got := printerLayerNotificationEvents(1, 3, "paused"); len(got) != 0 {
t.Fatalf("paused layer events = %v, want empty", got)
}
if got := printerLayerNotificationEvents(3, 1, "printing"); len(got) != 0 {
t.Fatalf("layer reset events = %v, want empty", got)
}
}
func TestPrinterLayerNotificationEventsForStatusRequiresTrustedLayerSource(t *testing.T) {
metadataOnly := &protocol.PrintStatus{
State: "printing",
CurrentLayer: 4,
TotalLayer: 100,
Filename: "benchy.gcode",
LayerSource: "metadata",
}
if got := printerLayerNotificationEventsForStatus(0, metadataOnly); len(got) != 0 {
t.Fatalf("metadata-only layer events = %v, want empty", got)
}
if printerLayerNotificationsTrusted(metadataOnly) {
t.Fatal("metadata-only layer source should not be trusted for notifications")
}
printStats := &protocol.PrintStatus{
State: "printing",
CurrentLayer: 4,
LayerSource: "print_stats+metadata",
}
if got := printerLayerNotificationEventsForStatus(0, printStats); len(got) != 2 || got[0] != "first_layer" || got[1] != "third_layer" {
t.Fatalf("print_stats layer events = %v, want [first_layer third_layer]", got)
}
if !printerLayerNotificationsTrusted(printStats) {
t.Fatal("print_stats layer source should be trusted for notifications")
}
}
func TestShouldPersistPrinterLayerObservationSkipsPrintingZeroLayer(t *testing.T) {
if shouldPersistPrinterLayerObservation(&protocol.PrintStatus{State: "printing", CurrentLayer: 0}) {
t.Fatal("printing zero-layer status should not reset layer observation")
}
if !shouldPersistPrinterLayerObservation(&protocol.PrintStatus{State: "printing", CurrentLayer: 5, LayerSource: "print_stats"}) {
t.Fatal("trusted nonzero printing layer should be persisted")
}
if !shouldPersistPrinterLayerObservation(&protocol.PrintStatus{State: "complete", CurrentLayer: 0}) {
t.Fatal("non-printing zero-layer status should be allowed to reset observation")
}
if shouldPersistPrinterLayerObservation(&protocol.PrintStatus{State: "printing", CurrentLayer: 5, LayerSource: "metadata"}) {
t.Fatal("untrusted layer source should not be persisted")
}
}
func TestTelegramNotifierBuildLayerMessage(t *testing.T) {
msg := buildTelegramLayerMessage("real-printer", printerSettingsRecord{DisplayName: "Workshop"}, &protocol.Health{
PrintStatus: &protocol.PrintStatus{
State: "printing",
Filename: "benchy.gcode",
CurrentLayer: 3,
TotalLayer: 4,
Progress: 0.42,
PrintDuration: 1234,
EstimatedTimeRemaining: 456,
Message: "Layer change",
},
}, "third_layer")
if !strings.Contains(msg, "Printer: Workshop") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Event: Third layer completed") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "State: printing") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Layer: 3") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Total layers: 4") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Printed:") || !strings.Contains(msg, "Remaining:") {
t.Fatalf("message = %q", msg)
}
}
func TestTelegramNotifierBuildPrintStatusMessageUsesTotalLayerOnStart(t *testing.T) {
msg := buildTelegramPrintStatusMessage("real-printer", printerSettingsRecord{DisplayName: "Workshop"}, &protocol.Health{
PrintStatus: &protocol.PrintStatus{
State: "printing",
Filename: "benchy.gcode",
CurrentLayer: 1,
TotalLayer: 4,
Progress: 0.11,
Message: "Printing benchy",
},
})
if !strings.Contains(msg, "Printer: Workshop") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Event: Print started") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "State: printing") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "File: benchy.gcode") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Total layers: 4") {
t.Fatalf("message = %q", msg)
}
if strings.Contains(msg, "Layer: 1/4") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Progress: 11%") {
t.Fatalf("message = %q", msg)
}
}
func TestParseTelegramCommand(t *testing.T) {
command, args := parseTelegramCommand("/status Rockchip")
if command != "status" || args != "Rockchip" {
t.Fatalf("command=%q args=%q, want status/Rockchip", command, args)
}
if command, args := parseTelegramCommand("hello"); command != "" || args != "" {
t.Fatalf("expected non-command input to be ignored, got %q/%q", command, args)
}
}
func TestTelegramBotBuildMessages(t *testing.T) {
store := &printerSettingsStore{
records: map[string]printerSettingsRecord{
"Rockchip": {
PrinterID: "Rockchip",
DisplayName: "Workshop",
},
},
}
bot := &telegramBot{
server: &server{
printerSettings: store,
tunnels: map[string]*tunnel{
"Rockchip": {
health: &protocol.Health{
PrintStatus: &protocol.PrintStatus{
State: "printing",
Filename: "benchy.gcode",
CurrentLayer: 3,
TotalLayer: 4,
Progress: 0.42,
},
},
},
},
},
}
printers := bot.buildPrintersMessage()
if !strings.Contains(printers, "Workshop (Rockchip)") {
t.Fatalf("printers = %q", printers)
}
if !strings.Contains(printers, "printing, layer 3/4") {
t.Fatalf("printers = %q", printers)
}
status := bot.buildPrinterStatusMessage(telegramPrinterTarget{
record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"},
health: &protocol.Health{
PrintStatus: &protocol.PrintStatus{
State: "printing",
Filename: "benchy.gcode",
CurrentLayer: 3,
TotalLayer: 4,
Progress: 0.42,
},
},
})
if !strings.Contains(status, "Printer: Workshop") || !strings.Contains(status, "Layer: 3/4") {
t.Fatalf("status = %q", status)
}
detailed := bot.buildPrinterStatusMessageWithLiveData(telegramPrinterTarget{
record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"},
health: &protocol.Health{
PrintStatus: &protocol.PrintStatus{
State: "printing",
Filename: "benchy.gcode",
CurrentLayer: 3,
TotalLayer: 4,
Progress: 0.42,
},
},
}, map[string]any{
"extruder": map[string]any{"temperature": 215.4, "target": 220.0},
"fan": map[string]any{"speed": 0.5},
"display_status": map[string]any{"progress": 0.42},
})
if !strings.Contains(detailed, "Temperatures:") || !strings.Contains(detailed, "Fans:") {
t.Fatalf("detailed status = %q", detailed)
}
if !strings.Contains(detailed, "extruder") || !strings.Contains(detailed, "fan") {
t.Fatalf("detailed status = %q", detailed)
}
}
func TestSelectLastPrintableJob(t *testing.T) {
jobs := []map[string]any{
{"filename": "active.gcode", "status": "printing"},
{"filename": "cancelled.gcode", "status": "cancelled"},
{"filename": "completed.gcode", "status": "completed"},
}
filename, status := selectLastPrintableJob(jobs)
if filename != "cancelled.gcode" || status != "cancelled" {
t.Fatalf("filename=%q status=%q, want cancelled.gcode/cancelled", filename, status)
}
if !isTerminalJobHistoryStatus("completed") || !isTerminalJobHistoryStatus("canceled") {
t.Fatal("expected terminal history statuses to be recognized")
}
if isTerminalJobHistoryStatus("printing") {
t.Fatal("printing should not be treated as terminal history status")
}
}
func TestSelectPrintableJobs(t *testing.T) {
jobs := []map[string]any{
{"filename": "active.gcode", "status": "printing"},
{"filename": "first.gcode", "status": "completed"},
{"filename": "second.gcode", "status": "cancelled"},
{"filename": "third.gcode", "status": "completed"},
}
selected := selectPrintableJobs(jobs, 2)
if len(selected) != 2 {
t.Fatalf("len(selected) = %d, want 2", len(selected))
}
if selected[0].Filename != "first.gcode" || selected[1].Filename != "second.gcode" {
t.Fatalf("selected = %+v", selected)
}
if selected[0].ButtonLabel == "" || selected[1].ButtonLabel == "" {
t.Fatalf("button labels should not be empty: %+v", selected)
}
}
func TestBuildJobHistoryLines(t *testing.T) {
lines := buildJobHistoryLines("Printer: Workshop", []map[string]any{
{"filename": "first.gcode", "status": "completed"},
{"filename": "second.gcode"},
})
if len(lines) != 4 {
t.Fatalf("len(lines) = %d, want 4", len(lines))
}
if !strings.Contains(lines[2], "first.gcode (completed)") || !strings.Contains(lines[3], "second.gcode") {
t.Fatalf("unexpected lines: %+v", lines)
}
}
func TestTelegramBotPrintCancelDeletesConfirmationMessage(t *testing.T) {
var gotURLs []string
var gotBodies []string
notifier := &telegramNotifier{
client: &http.Client{
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
gotURLs = append(gotURLs, req.URL.String())
body, _ := io.ReadAll(req.Body)
gotBodies = append(gotBodies, string(body))
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
Header: make(http.Header),
Request: req,
}, nil
}),
},
}
bot := &telegramBot{
server: &server{notifier: notifier},
selections: map[string]telegramPrintSelection{
"sel": {
PrinterID: "Rockchip",
Filename: "benchy.gcode",
Label: "benchy.gcode",
CreatedAt: time.Now().UTC(),
},
},
}
query := &telegramCallbackQuery{
ID: "cb1",
Data: "cancel:sel",
Message: &telegramMessage{
MessageID: 99,
Chat: telegramChat{ID: 456},
},
}
if err := bot.handleCallbackQuery(context.Background(), "bot123", "456", query); err != nil {
t.Fatalf("handleCallbackQuery returned error: %v", err)
}
if len(gotURLs) == 0 {
t.Fatal("expected telegram requests to be sent")
}
deleteIndex := -1
for i, gotURL := range gotURLs {
if gotURL == "https://api.telegram.org/botbot123/deleteMessage" {
deleteIndex = i
break
}
}
if deleteIndex == -1 {
t.Fatalf("deleteMessage request not sent: %+v", gotURLs)
}
values, err := url.ParseQuery(gotBodies[deleteIndex])
if err != nil {
t.Fatalf("failed to parse deleteMessage body: %v", err)
}
if got := values.Get("message_id"); got != "99" {
t.Fatalf("message_id = %q, want 99", got)
}
}
func TestSelectPrintableFiles(t *testing.T) {
files := []moonrakerFileInfo{
{Path: "active.gcode", Modified: 100},
{Path: "older.gcode", Modified: 50},
{Path: "newer.gcode", Modified: 150},
}
selected := selectPrintableFiles(files, 2)
if len(selected) != 2 {
t.Fatalf("len(selected) = %d, want 2", len(selected))
}
if selected[0].Path != "newer.gcode" || selected[1].Path != "active.gcode" {
t.Fatalf("selected = %+v", selected)
}
if selected[0].ButtonLabel == "" || selected[1].ButtonLabel == "" {
t.Fatalf("button labels should not be empty: %+v", selected)
}
}
func TestTemperatureObjectSummary(t *testing.T) {
lines := temperatureObjectSummary(map[string]any{
"extruder": map[string]any{"temperature": 215.4, "target": 220.0},
"heater_bed": map[string]any{"temperature": 60.0},
"toolhead": map[string]any{"position": []float64{0, 0, 0}},
})
if len(lines) != 2 {
t.Fatalf("len(lines) = %d, want 2", len(lines))
}
if !strings.Contains(lines[0], "\u00b0C") || !strings.Contains(lines[1], "heater_bed") {
t.Fatalf("unexpected temperature lines: %+v", lines)
}
}
func TestFanObjectSummary(t *testing.T) {
lines := fanObjectSummary(map[string]any{
"fan": map[string]any{"speed": 0.5},
"fan_generic part_cooling": map[string]any{"speed": 0.25, "rpm": 1200.0},
})
if len(lines) != 2 {
t.Fatalf("len(lines) = %d, want 2", len(lines))
}
if !strings.Contains(lines[0], "%") || !strings.Contains(lines[1], "rpm") {
t.Fatalf("unexpected fan lines: %+v", lines)
}
}
func TestParseTelegramCallbackAction(t *testing.T) {
action := parseTelegramCallbackAction("select:abc123")
if action.Kind != "select" || action.ID != "abc123" {
t.Fatalf("action = %+v", action)
}
action = parseTelegramCallbackAction("status:rockchip%2Fmain")
if action.Kind != "status" || action.ID != "rockchip/main" {
t.Fatalf("escaped action = %+v", action)
}
action = parseTelegramCallbackAction("print:rockchip")
if action.Kind != "print" || action.ID != "rockchip" {
t.Fatalf("print action = %+v", action)
}
action = parseTelegramCallbackAction("reprint:rockchip")
if action.Kind != "reprint" || action.ID != "rockchip" {
t.Fatalf("reprint action = %+v", action)
}
action = parseTelegramCallbackAction("camera:rockchip")
if action.Kind != "camera" || action.ID != "rockchip" {
t.Fatalf("camera action = %+v", action)
}
action = parseTelegramCallbackAction("camera-shot:abc123")
if action.Kind != "camera-shot" || action.ID != "abc123" {
t.Fatalf("camera-shot action = %+v", action)
}
action = parseTelegramCallbackAction("jobs:rockchip")
if action.Kind != "jobs" || action.ID != "rockchip" {
t.Fatalf("jobs action = %+v", action)
}
action = parseTelegramCallbackAction("set-temp:abc123:rockchip")
if action.Kind != "set-temp" || action.ID != "abc123:rockchip" {
t.Fatalf("set-temp action = %+v", action)
}
action = parseTelegramCallbackAction("temp-confirm:xyz")
if action.Kind != "temp-confirm" || action.ID != "xyz" {
t.Fatalf("temp-confirm action = %+v", action)
}
action = parseTelegramCallbackAction("temp-cancel:xyz")
if action.Kind != "temp-cancel" || action.ID != "xyz" {
t.Fatalf("temp-cancel action = %+v", action)
}
action = parseTelegramCallbackAction("confirm:xyz")
if action.Kind != "confirm" || action.ID != "xyz" {
t.Fatalf("action = %+v", action)
}
if got := parseTelegramCallbackAction("bogus"); got.Kind != "" || got.ID != "" {
t.Fatalf("unexpected action = %+v", got)
}
}
func TestPrinterSelectionRecordsIncludesConnectedUnknownPrinters(t *testing.T) {
bot := &telegramBot{
server: &server{
printerSettings: &printerSettingsStore{
records: map[string]printerSettingsRecord{
"saved": {
PrinterID: "saved",
DisplayName: "Saved Printer",
},
},
},
tunnels: map[string]*tunnel{
"saved": {},
"connected-only": {},
},
},
}
records := bot.printerSelectionRecords()
if len(records) != 2 {
t.Fatalf("len(records) = %d, want 2", len(records))
}
if records[0].PrinterID != "connected-only" || records[1].PrinterID != "saved" {
t.Fatalf("records = %+v", records)
}
}
func TestBuildPrintConfirmationMessage(t *testing.T) {
bot := &telegramBot{}
msg := bot.buildPrintConfirmationMessage(
telegramPrinterTarget{
record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"},
health: &protocol.Health{
PrintStatus: &protocol.PrintStatus{State: "idle"},
},
},
telegramPrintSelection{PrinterID: "Rockchip", Filename: "benchy.gcode", Label: "benchy.gcode (completed)"},
"select",
)
if !strings.Contains(msg, "Printer: Workshop") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Action: Start print") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "File: benchy.gcode") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Selection: benchy.gcode (completed)") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Snapshot: review the bed before confirming") {
t.Fatalf("message = %q", msg)
}
}
func TestBuildReprintConfirmationMessage(t *testing.T) {
bot := &telegramBot{}
msg := bot.buildReprintConfirmationMessage(
telegramPrinterTarget{
record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"},
health: &protocol.Health{
PrintStatus: &protocol.PrintStatus{State: "idle"},
},
},
telegramPrintSelection{PrinterID: "Rockchip", Filename: "benchy.gcode", Label: "benchy.gcode (completed)"},
)
if !strings.Contains(msg, "Action: Reprint last job") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Snapshot: review the bed before confirming") {
t.Fatalf("message = %q", msg)
}
}
func TestBuildTemperatureConfirmationMessage(t *testing.T) {
bot := &telegramBot{}
msg := bot.buildTemperatureConfirmationMessage(
telegramPrinterTarget{
record: printerSettingsRecord{PrinterID: "Rockchip", DisplayName: "Workshop"},
health: &protocol.Health{
PrintStatus: &protocol.PrintStatus{State: "printing"},
},
},
telegramTemperatureSelection{
Heater: "heater_bed",
Target: 60,
},
)
if !strings.Contains(msg, "Printer: Workshop") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Action: Set bed target") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Target: bed 60.0\u00b0C") {
t.Fatalf("message = %q", msg)
}
if !strings.Contains(msg, "Snapshot: review the bed before confirming") {
t.Fatalf("message = %q", msg)
}
}
func TestTelegramHelpMessageIncludesNewCommands(t *testing.T) {
msg := telegramHelpMessage()
for _, want := range []string{"/jobs", "/camera", "/status", "/set"} {
if !strings.Contains(msg, want) {
t.Fatalf("help message missing %q: %s", want, msg)
}
}
for _, unwanted := range []string{"/temps", "/fans", "/snapshot"} {
if strings.Contains(msg, unwanted) {
t.Fatalf("help message should not include %q: %s", unwanted, msg)
}
}
}
func TestParseTelegramTemperatureSetArgs(t *testing.T) {
printer, heater, target, err := parseTelegramTemperatureSetArgs("extruder 215")
if err != nil {
t.Fatalf("parseTelegramTemperatureSetArgs returned error: %v", err)
}
if printer != "" || heater != "extruder" || target != 215 {
t.Fatalf("parsed args = %q %q %v", printer, heater, target)
}
printer, heater, target, err = parseTelegramTemperatureSetArgs("Rockchip bed 60")
if err != nil {
t.Fatalf("parseTelegramTemperatureSetArgs returned error: %v", err)
}
if printer != "Rockchip" || heater != "heater_bed" || target != 60 {
t.Fatalf("parsed args = %q %q %v", printer, heater, target)
}
if _, _, _, err := parseTelegramTemperatureSetArgs("something 60"); err == nil {
t.Fatal("expected unknown heater to fail")
}
}
func TestNormalizeTemperatureHeater(t *testing.T) {
tests := map[string]string{
"extruder": "extruder",
"nozzle": "extruder",
"bed": "heater_bed",
"heatedbed": "heater_bed",
"heater_bed": "heater_bed",
}
for input, want := range tests {
got, err := normalizeTemperatureHeater(input)
if err != nil {
t.Fatalf("normalizeTemperatureHeater(%q) returned error: %v", input, err)
}
if got != want {
t.Fatalf("normalizeTemperatureHeater(%q) = %q, want %q", input, got, want)
}
}
if _, err := normalizeTemperatureHeater("side"); err == nil {
t.Fatal("expected unknown heater to fail")
}
}
func TestSnapshotCapableCameras(t *testing.T) {
health := &protocol.Health{Cameras: []protocol.CameraHealth{
{Name: "wide", HasSnapshot: true},
{Name: "stream-only", HasSnapshot: false, HasStream: true},
{Name: "nozzle", HasSnapshot: true},
}}
cameras := snapshotCapableCameras(health)
if len(cameras) != 2 {
t.Fatalf("len(cameras) = %d, want 2", len(cameras))
}
if cameras[0].Name != "nozzle" || cameras[1].Name != "wide" {
t.Fatalf("cameras = %+v", cameras)
}
}