package config import ( "os" "path/filepath" "strings" "testing" "time" ) func TestLoadOrInitGeneratesDefault(t *testing.T) { tmpDir := t.TempDir() cfgPath := filepath.Join(tmpDir, "rud.json") cfg, created, err := LoadOrInit(cfgPath, true) if err != nil { t.Fatalf("LoadOrInit failed: %v", err) } if !created { t.Fatalf("expected created=true when file did not exist") } if len(cfg.Monitors) == 0 { t.Fatalf("expected default monitors to be populated") } if len(cfg.Page.Elements) == 0 { t.Fatalf("expected default page elements to be populated") } // Reload existing file cfg2, created2, err := LoadOrInit(cfgPath, true) if err != nil { t.Fatalf("second LoadOrInit failed: %v", err) } if created2 { t.Fatalf("expected created=false when file already exists") } if len(cfg2.Monitors) != len(cfg.Monitors) { t.Fatalf("expected %d monitors, got %d", len(cfg.Monitors), len(cfg2.Monitors)) } } func TestDurationMarshalUnmarshal(t *testing.T) { d := NewDuration(5 * time.Hour) b, err := d.MarshalJSON() if err != nil { t.Fatalf("MarshalJSON failed: %v", err) } if string(b) != `"5h"` { t.Fatalf("expected \"5h\", got %s", string(b)) } var parsed Duration if err := parsed.UnmarshalJSON([]byte(`"15m"`)); err != nil { t.Fatalf("UnmarshalJSON failed: %v", err) } if parsed.Std() != 15*time.Minute { t.Fatalf("expected 15m, got %v", parsed.Std()) } } func TestConfigValidation(t *testing.T) { cfg := DefaultConfig() if err := cfg.Validate(); err != nil { t.Fatalf("DefaultConfig should validate cleanly, got: %v", err) } rawDef, err := MarshalConfig(&cfg) if err != nil { t.Fatalf("MarshalConfig failed: %v", err) } if issues := cfg.Lint(rawDef); len(issues) != 0 { t.Fatalf("DefaultConfig should have 0 lint issues, got: %v", issues) } // Duplicate monitor ID cfg.Monitors = []MonitorConfig{ {ID: "dup", Method: "tcp", Target: "127.0.0.1:80"}, {ID: "dup", Method: "tcp", Target: "127.0.0.1:81"}, } if err := cfg.Validate(); err == nil { t.Fatalf("expected duplicate monitor id error") } // Invalid regex cfg.Monitors = []MonitorConfig{ {ID: "bad-regex", Method: "http", URL: "http://example.com", BodyRegex: "["}, } if err := cfg.Validate(); err == nil { t.Fatalf("expected invalid body_regex error") } // Invalid HTTP URL cfg.Monitors = []MonitorConfig{ {ID: "bad-url", Method: "https", URL: "not-a-url"}, } if err := cfg.Validate(); err == nil { t.Fatalf("expected invalid HTTP URL error") } // Negative duration / retries cfg = DefaultConfig() cfg.Defaults.Interval = NewDuration(-5 * time.Second) if err := cfg.Validate(); err == nil { t.Fatalf("expected negative defaults.interval error") } cfg = DefaultConfig() cfg.Monitors[0].Retries = IntPtr(-1) if err := cfg.Validate(); err == nil { t.Fatalf("expected negative monitor retries error") } // Duplicate event IDs cfg = DefaultConfig() cfg.Events = append(cfg.Events, cfg.Events[0]) if err := cfg.Validate(); err == nil { t.Fatalf("expected duplicate event id error") } // Invalid webhook template cfg = DefaultConfig() cfg.Events[0].Actions = []EventAction{ {Type: "webhook", URL: "https://hooks.example.com/test", BodyTemplate: "{{.Unclosed"}, } if err := cfg.Validate(); err == nil { t.Fatalf("expected invalid webhook body_template error") } // Valid json/jsonStr template functions in webhook cfg.Events[0].Actions = []EventAction{ {Type: "webhook", URL: "https://hooks.example.com/test", BodyTemplate: `{"msg":{{json .EventName}},"sub":"{{jsonStr .Status}}"}`}, } if err := cfg.Validate(); err != nil { t.Fatalf("expected valid json template functions, got: %v", err) } // Invalid command template cfg.Events[0].Actions = []EventAction{ {Type: "command", Command: "echo {{.MissingParen"}, } if err := cfg.Validate(); err == nil { t.Fatalf("expected invalid command template error") } } func TestAtomicSaveAndBackup(t *testing.T) { tmpDir := t.TempDir() nestedPath := filepath.Join(tmpDir, "nested", "dir", "rud.json") cfg := DefaultConfig() cfg.Page.Title = "Initial Title" if err := SaveConfig(nestedPath, &cfg); err != nil { t.Fatalf("SaveConfig nested path failed: %v", err) } cfg.Page.Title = "Updated Title" bakPath, err := SaveConfigWithBackup(nestedPath, &cfg, true) if err != nil { t.Fatalf("SaveConfigWithBackup failed: %v", err) } if bakPath != nestedPath+".bak" { t.Fatalf("unexpected backup path %q", bakPath) } bakBytes, err := os.ReadFile(bakPath) if err != nil { t.Fatalf("read backup failed: %v", err) } if !strings.Contains(string(bakBytes), "Initial Title") { t.Fatalf("backup did not contain initial content") } loaded, raw, err := LoadForEdit(nestedPath) if err != nil { t.Fatalf("LoadForEdit failed: %v", err) } if loaded.Page.Title != "Updated Title" { t.Fatalf("expected Updated Title, got %q", loaded.Page.Title) } if len(raw) == 0 { t.Fatalf("expected raw bytes from LoadForEdit") } cloned, err := loaded.Clone() if err != nil { t.Fatalf("Clone failed: %v", err) } cloned.Page.Title = "Mutated Clone" if loaded.Page.Title != "Updated Title" { t.Fatalf("Clone mutation affected original") } } func TestConfigLint(t *testing.T) { raw := []byte(`{ "unknown_top": true, "monitors": [ { "id": "tcp-bad", "method": "tcp", "target": "no-port-here", "body_regx": "typo" } ], "events": [ { "id": "ev1", "name": "Ev", "condition": { "type": "state", "monitors": ["missing-mon"], "match": "some", "state": "down" }, "actions": [] } ], "page": { "title": "Test", "elements": [ { "type": "monitor_group", "monitors": ["missing-mon-2"], "layout": "carousel" }, { "type": "unknown_widget" } ] } }`) cfg := Config{ Monitors: []MonitorConfig{ {ID: "tcp-bad", Method: "tcp", Target: "no-port-here"}, }, Events: []EventConfig{ { ID: "ev1", Name: "Ev", Condition: EventCondition{ Type: "state", Monitors: []string{"missing-mon"}, Match: "some", State: "down", }, }, }, Page: PageConfig{ Title: "Test", Elements: []PageElement{ {Type: "monitor_group", Monitors: []string{"missing-mon-2"}, Layout: "carousel"}, {Type: "unknown_widget"}, }, }, } issues := cfg.Lint(raw) joined := make([]string, 0, len(issues)) for _, iss := range issues { joined = append(joined, iss.String()) } all := strings.Join(joined, "\n") wantSubstrings := []string{ "unknown_top", "monitors[0].body_regx", "host:port", "has no actions", "missing-mon", "unknown match mode", "missing-mon-2", "unknown monitor_group layout", "unknown page element type", } for _, want := range wantSubstrings { if !strings.Contains(all, want) { t.Errorf("expected lint issues to contain %q, got:\n%s", want, all) } } }