Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Chore: enhance core api and metrics testability
rcourtmaneb2d07e48f74
diff --git a/internal/api/router.go b/internal/api/router.goindex c861d4401d..67905725bf 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -102,6 +102,7 @@ type Router struct {bootstrapTokenPath stringchecksumMu sync.RWMutexchecksumCache map[string]checksumCacheEntry+ installScriptClient *http.Client}func pulseBinDir() string {diff --git a/internal/api/unified_agent.go b/internal/api/unified_agent.goindex 30665ea227..fc57e105bc 100644--- a/internal/api/unified_agent.go+++ b/internal/api/unified_agent.go@@ -192,8 +192,11 @@ func (r *Router) proxyInstallScriptFromGitHub(w http.ResponseWriter, req *http.R// Use raw.githubusercontent.com to fetch from main branchgithubURL := "https://raw.githubusercontent.com/rcourtman/Pulse/main/scripts/" + scriptName- client := &http.Client{- Timeout: 30 * time.Second,+ client := r.installScriptClient+ if client == nil {+ client = &http.Client{+ Timeout: 30 * time.Second,+ }}resp, err := client.Get(githubURL)diff --git a/internal/api/unified_agent_more_test.go b/internal/api/unified_agent_more_test.gonew file mode 100644index 0000000000..0994c938fc--- /dev/null+++ b/internal/api/unified_agent_more_test.go@@ -0,0 +1,189 @@+package api++import (+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "testing"+)++type roundTripFunc func(*http.Request) (*http.Response, error)++func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {+ return f(req)+}++func newTestInstallScriptClient(t *testing.T, expectedURL string, status int, body string, err error) *http.Client {+ t.Helper()++ return &http.Client{+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ if expectedURL != "" && req.URL.String() != expectedURL {+ t.Fatalf("unexpected URL: %s", req.URL.String())+ }+ if err != nil {+ return nil, err+ }+ return &http.Response{+ StatusCode: status,+ Status: fmt.Sprintf("%d %s", status, http.StatusText(status)),+ Header: make(http.Header),+ Body: io.NopCloser(strings.NewReader(body)),+ }, nil+ }),+ }+}++func TestDownloadUnifiedInstallScript_MethodNotAllowed(t *testing.T) {+ router := &Router{}++ req := httptest.NewRequest(http.MethodPost, "/install.sh", nil)+ w := httptest.NewRecorder()++ router.handleDownloadUnifiedInstallScript(w, req)++ if w.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected 405, got %d", w.Code)+ }+}++func TestDownloadUnifiedInstallScriptPS_MethodNotAllowed(t *testing.T) {+ router := &Router{}++ req := httptest.NewRequest(http.MethodPut, "/install.ps1", nil)+ w := httptest.NewRecorder()++ router.handleDownloadUnifiedInstallScriptPS(w, req)++ if w.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected 405, got %d", w.Code)+ }+}++func TestDownloadUnifiedInstallScript_ProxyFallback(t *testing.T) {+ router, _ := setupUnifiedAgentRouter(t)+ expectedURL := "https://raw.githubusercontent.com/rcourtman/Pulse/main/scripts/install.sh"+ payload := "#!/bin/bash\necho hi"+ router.installScriptClient = newTestInstallScriptClient(t, expectedURL, http.StatusOK, payload, nil)++ req := httptest.NewRequest(http.MethodGet, "/install.sh", nil)+ w := httptest.NewRecorder()++ router.handleDownloadUnifiedInstallScript(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ if got := w.Header().Get("X-Served-From"); got != "github-fallback" {+ t.Fatalf("unexpected X-Served-From header: %q", got)+ }+ if got := w.Header().Get("Content-Type"); got != "text/x-shellscript" {+ t.Fatalf("unexpected Content-Type: %q", got)+ }+ if !strings.Contains(w.Header().Get("Content-Disposition"), "install.sh") {+ t.Fatalf("missing Content-Disposition filename")+ }+ if strings.TrimSpace(w.Body.String()) != payload {+ t.Fatalf("unexpected response body")+ }+}++func TestDownloadUnifiedInstallScriptPS_ProxyFallback(t *testing.T) {+ router, _ := setupUnifiedAgentRouter(t)+ expectedURL := "https://raw.githubusercontent.com/rcourtman/Pulse/main/scripts/install.ps1"+ payload := "Write-Host 'hi'"+ router.installScriptClient = newTestInstallScriptClient(t, expectedURL, http.StatusOK, payload, nil)++ req := httptest.NewRequest(http.MethodGet, "/install.ps1", nil)+ w := httptest.NewRecorder()++ router.handleDownloadUnifiedInstallScriptPS(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ if got := w.Header().Get("Content-Type"); got != "text/plain" {+ t.Fatalf("unexpected Content-Type: %q", got)+ }+ if !strings.Contains(w.Header().Get("Content-Disposition"), "install.ps1") {+ t.Fatalf("missing Content-Disposition filename")+ }+}++func TestProxyInstallScriptFromGitHub_NonOK(t *testing.T) {+ router := &Router{+ installScriptClient: newTestInstallScriptClient(t, "", http.StatusNotFound, "", nil),+ }++ req := httptest.NewRequest(http.MethodGet, "/install.sh", nil)+ w := httptest.NewRecorder()++ router.proxyInstallScriptFromGitHub(w, req, "install.sh")++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d", w.Code)+ }+ if !strings.Contains(w.Body.String(), "Install script not found") {+ t.Fatalf("expected not found message")+ }+}++func TestProxyInstallScriptFromGitHub_Error(t *testing.T) {+ router := &Router{+ installScriptClient: newTestInstallScriptClient(t, "", 0, "", errors.New("boom")),+ }++ req := httptest.NewRequest(http.MethodGet, "/install.sh", nil)+ w := httptest.NewRecorder()++ router.proxyInstallScriptFromGitHub(w, req, "install.sh")++ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503, got %d", w.Code)+ }+ if !strings.Contains(w.Body.String(), "Failed to fetch install script") {+ t.Fatalf("expected fetch failure message")+ }+}++func TestDownloadUnifiedAgent_MethodNotAllowed(t *testing.T) {+ router := &Router{}++ req := httptest.NewRequest(http.MethodPost, "/download/pulse-agent", nil)+ w := httptest.NewRecorder()++ router.handleDownloadUnifiedAgent(w, req)++ if w.Code != http.StatusMethodNotAllowed {+ t.Fatalf("expected 405, got %d", w.Code)+ }+}++func TestDownloadUnifiedAgent_NoArchNotFound(t *testing.T) {+ tempDir := t.TempDir()+ t.Setenv("PULSE_BIN_DIR", tempDir)++ if _, err := os.Stat("/opt/pulse/pulse-agent"); err == nil {+ t.Skip("local /opt/pulse/pulse-agent exists; skipping")+ }+ if _, err := os.Stat("/app/pulse-agent"); err == nil {+ t.Skip("local /app/pulse-agent exists; skipping")+ }++ router := &Router{projectRoot: tempDir}+ req := httptest.NewRequest(http.MethodGet, "/download/pulse-agent", nil)+ w := httptest.NewRecorder()++ router.handleDownloadUnifiedAgent(w, req)++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d", w.Code)+ }+ if !strings.Contains(w.Body.String(), "Specify ?arch=linux-amd64") {+ t.Fatalf("expected guidance message")+ }+}diff --git a/pkg/metrics/store_additional_test.go b/pkg/metrics/store_additional_test.gonew file mode 100644index 0000000000..638552b73c--- /dev/null+++ b/pkg/metrics/store_additional_test.go@@ -0,0 +1,125 @@+package metrics++import (+ "path/filepath"+ "testing"+ "time"+)++func TestStoreWriteBatchSync(t *testing.T) {+ dir := t.TempDir()+ store, err := NewStore(DefaultConfig(dir))+ if err != nil {+ t.Fatalf("NewStore returned error: %v", err)+ }+ defer store.Close()++ ts := time.Unix(1000, 0)+ metrics := []WriteMetric{+ {ResourceType: "vm", ResourceID: "v1", MetricType: "cpu", Value: 10.0, Timestamp: ts, Tier: TierRaw},+ {ResourceType: "vm", ResourceID: "v1", MetricType: "mem", Value: 50.0, Timestamp: ts, Tier: TierRaw},+ }++ store.WriteBatchSync(metrics)++ // Verify data was written+ points, err := store.Query("vm", "v1", "cpu", ts.Add(-time.Second), ts.Add(time.Second), 0)+ if err != nil {+ t.Fatalf("Query failed: %v", err)+ }+ if len(points) != 1 || points[0].Value != 10.0 {+ t.Fatalf("expected 1 point with value 10.0, got %v", points)+ }+}++func TestStoreClear(t *testing.T) {+ dir := t.TempDir()+ store, err := NewStore(DefaultConfig(dir))+ if err != nil {+ t.Fatalf("NewStore returned error: %v", err)+ }+ defer store.Close()++ // Write some data+ store.Write("vm", "v1", "cpu", 10.0, time.Now())+ store.Flush()++ // Write some data+ store.Write("vm", "v1", "cpu", 10.0, time.Now())+ store.Flush()++ // Wait for data to be written (Flush is async via channel)+ deadline := time.Now().Add(2 * time.Second)+ var stats Stats+ for time.Now().Before(deadline) {+ stats = store.GetStats()+ if stats.RawCount > 0 {+ break+ }+ time.Sleep(50 * time.Millisecond)+ }++ if stats.RawCount == 0 {+ t.Fatal("expected data to be written before clearing")+ }++ // clear+ if err := store.Clear(); err != nil {+ t.Fatalf("Clear failed: %v", err)+ }++ // Verify empty+ stats = store.GetStats()+ if stats.RawCount != 0 {+ t.Fatalf("expected empty store, got %d raw records", stats.RawCount)+ }+}++func TestStoreSetMaxOpenConns(t *testing.T) {+ dir := t.TempDir()+ store, err := NewStore(DefaultConfig(dir))+ if err != nil {+ t.Fatalf("NewStore returned error: %v", err)+ }+ defer store.Close()++ // Just verifying it doesn't panic+ store.SetMaxOpenConns(5)+}++func TestStoreRunRollupManually(t *testing.T) {+ // Tests the runRollup function wrapper which was showing 0% coverage+ dir := t.TempDir()+ cfg := DefaultConfig(dir)+ // Create separate DB for this test+ cfg.DBPath = filepath.Join(dir, "metrics-rollup-manual.db")++ store, err := NewStore(cfg)+ if err != nil {+ t.Fatalf("NewStore returned error: %v", err)+ }+ defer store.Close()++ // Trigger manual rollup - should not panic+ store.runRollup()+}++func TestStoreGetMetaIntInvalid(t *testing.T) {+ dir := t.TempDir()+ store, err := NewStore(DefaultConfig(dir))+ if err != nil {+ t.Fatalf("NewStore returned error: %v", err)+ }+ defer store.Close()++ // Insert invalid int value+ _, err = store.db.Exec("INSERT INTO metrics_meta (key, value) VALUES (?, ?)", "bad_key", "not_an_int")+ if err != nil {+ t.Fatalf("failed to insert invalid meta: %v", err)+ }++ val, ok := store.getMetaInt("bad_key")+ if ok {+ t.Fatalf("expected getMetaInt to fail for invalid int, got %d", val)+ }+}