RUD/internal/builder/builder_test.go

355 lines
10 KiB
Go

package builder
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"git.gsdistance.org/tyuXX/RUD/internal/config"
)
func runScripted(t *testing.T, opts Options, lines []string) string {
t.Helper()
var out bytes.Buffer
opts.Plain = true
opts.NoColor = true
opts.In = strings.NewReader(strings.Join(lines, "\n") + "\n")
opts.Out = &out
if err := Run(context.Background(), opts); err != nil {
t.Fatalf("builder.Run failed: %v\n--- Output ---\n%s", err, out.String())
}
return out.String()
}
func TestStarterTemplatesValidAndLintClean(t *testing.T) {
blank := BlankMinimalConfig()
if err := blank.Validate(); err != nil {
t.Fatalf("BlankMinimalConfig invalid: %v", err)
}
for name, cfg := range map[string]config.Config{
"WebAPIStarter": WebAPIStarterConfig(),
"HomelabStarter": HomelabStarterConfig(),
} {
if err := cfg.Validate(); err != nil {
t.Fatalf("%s invalid: %v", name, err)
}
raw, err := config.MarshalConfig(&cfg)
if err != nil {
t.Fatalf("%s marshal failed: %v", name, err)
}
if issues := cfg.Lint(raw); len(issues) != 0 {
t.Fatalf("%s has lint issues: %v", name, issues)
}
}
}
func TestBuilderNewConfigFromStarter(t *testing.T) {
cfgPath := filepath.Join(t.TempDir(), "sub", "rud.json")
// 3 = Web & API Starter, 8 = Save, 10 = Exit
out := runScripted(t, Options{ConfigPath: cfgPath}, []string{
"3",
"8",
"10",
})
if !strings.Contains(out, "Saved configuration") {
t.Fatalf("expected save confirmation in output:\n%s", out)
}
loaded, created, err := config.LoadOrInit(cfgPath, false)
if err != nil {
t.Fatalf("LoadOrInit on built config failed: %v", err)
}
if created {
t.Fatalf("expected file to already exist")
}
if loaded.Page.Title != "API & Web Status" || len(loaded.Monitors) != 3 {
t.Fatalf("unexpected loaded config: title=%q monitors=%d", loaded.Page.Title, len(loaded.Monitors))
}
}
func TestBuilderEditAddLiveTestRenameDeleteWithSyncAndBackup(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}))
defer ts.Close()
cfgPath := filepath.Join(t.TempDir(), "rud.json")
seed := config.DefaultConfig()
// Use explicit monitor IDs in monitor_group so we test page reference sync as well
seed.Page.Elements[3].Monitors = []string{"rud-http", "rud-tcp"}
if err := config.SaveConfig(cfgPath, &seed); err != nil {
t.Fatalf("seed SaveConfig failed: %v", err)
}
out := runScripted(t, Options{ConfigPath: cfgPath}, []string{
"1", // Monitors
// Add HTTP monitor and live test it
"1", // Add monitor
"test-http",
"Test HTTP",
"Local test endpoint",
"2", // Method: http
ts.URL, // URL
"", // HTTP verb (GET)
"200", // Expected status
"^ok$", // Body regex
"n", // Overrides? no
"y", // Test live now? yes
// Rename rud-http -> core-http and sync refs
"2", // Edit monitor
"1", // rud-http
"1", // Edit identity & metadata
"core-http",
"", // keep name
"", // keep desc
"", // keep link
"y", // Sync references? yes
"6", // Done editing monitor
// Delete rud-tcp and clean dangling refs
"6", // Delete monitor
"2", // rud-tcp
"y", // Confirm delete
"y", // Clean dangling refs
"7", // Back to main hub
"8", // Save
"y", // Create .bak backup
"10", // Exit
})
if !strings.Contains(out, "test-http") || !strings.Contains(out, "UP") {
t.Fatalf("expected live test output for test-http UP, got:\n%s", out)
}
bakBytes, err := os.ReadFile(cfgPath + ".bak")
if err != nil {
t.Fatalf("expected backup file at %s.bak: %v", cfgPath, err)
}
if !strings.Contains(string(bakBytes), `"rud-http"`) {
t.Fatalf("backup did not preserve original monitor ID")
}
reloaded, _, err := config.LoadOrInit(cfgPath, false)
if err != nil {
t.Fatalf("LoadOrInit failed: %v", err)
}
byID := make(map[string]config.MonitorConfig)
for _, m := range reloaded.Monitors {
byID[m.ID] = m
}
if _, ok := byID["core-http"]; !ok {
t.Fatalf("expected renamed monitor 'core-http' in config")
}
if _, ok := byID["test-http"]; !ok {
t.Fatalf("expected added monitor 'test-http' in config")
}
if _, ok := byID["rud-tcp"]; ok {
t.Fatalf("expected deleted monitor 'rud-tcp' to be removed")
}
evMons := reloaded.Events[0].Condition.Conditions[0].Monitors
if len(evMons) != 1 || evMons[0] != "core-http" {
t.Fatalf("expected event condition monitors to sync to [core-http], got %v", evMons)
}
pgMons := reloaded.Page.Elements[3].Monitors
if len(pgMons) != 1 || pgMons[0] != "core-http" {
t.Fatalf("expected page group monitors to sync to [core-http], got %v", pgMons)
}
}
func TestBuilderRecursiveEventTreeAndDiscordPreset(t *testing.T) {
cfgPath := filepath.Join(t.TempDir(), "rud.json")
seed := BlankMinimalConfig()
seed.Monitors = []config.MonitorConfig{
{ID: "api", Name: "API", Method: "http", URL: "http://127.0.0.1:8080/health"},
}
seed.Events = []config.EventConfig{
{
ID: "api-alert",
Name: "API Alert",
Condition: config.EventCondition{
Type: "state",
Monitors: []string{"api"},
Match: "all",
State: "down",
},
Actions: []config.EventAction{
{Type: "command", Command: "echo alert", Shell: true},
},
},
}
if err := config.SaveConfig(cfgPath, &seed); err != nil {
t.Fatalf("seed SaveConfig failed: %v", err)
}
_ = runScripted(t, Options{ConfigPath: cfgPath}, []string{
"2", // Events & Alerts
"2", // Edit event rule
"1", // api-alert
"2", // Edit condition tree
"1", // Select root leaf node
"2", // Wrap in new AND/OR group
"1", // or
"1", // Select new OR group node
"2", // Add child leaf condition
"2", // metric
"1", // * (All monitors)
"2", // any
"2", // latency_ms
"3", // >
"250",
"1m",
"4", // Done editing condition tree
"3", // Edit alert actions
"1", // Add action
"1", // Webhook from preset
"1", // Discord Webhook
"https://discord.com/api/webhooks/123456/token",
"4", // Done editing actions
"5", // Done editing event
"5", // Back to main hub
"8", // Save
"n", // No backup
"10", // Exit
})
reloaded, raw, err := config.LoadForEdit(cfgPath)
if err != nil {
t.Fatalf("LoadForEdit failed: %v", err)
}
if err := reloaded.Validate(); err != nil {
t.Fatalf("reloaded config invalid: %v", err)
}
if issues := reloaded.Lint(raw); len(issues) != 0 {
t.Fatalf("reloaded config has lint issues: %v", issues)
}
ev := reloaded.Events[0]
if ev.Condition.Operator != "or" || len(ev.Condition.Conditions) != 2 {
t.Fatalf("expected OR group with 2 children, got %+v", ev.Condition)
}
if ev.Condition.Conditions[1].Metric != "latency_ms" || ev.Condition.Conditions[1].Value != 250 {
t.Fatalf("unexpected second child condition: %+v", ev.Condition.Conditions[1])
}
if len(ev.Actions) != 2 || !strings.Contains(ev.Actions[1].URL, "discord.com") {
t.Fatalf("expected Discord webhook action to be added, got %+v", ev.Actions)
}
}
func TestBuilderThemePresetReorderAndUnsavedGuard(t *testing.T) {
cfgPath := filepath.Join(t.TempDir(), "rud.json")
seed := config.DefaultConfig()
if err := config.SaveConfig(cfgPath, &seed); err != nil {
t.Fatalf("seed SaveConfig failed: %v", err)
}
_ = runScripted(t, Options{ConfigPath: cfgPath}, []string{
"3", // Page & Theme
"2", // Apply theme preset
"4", // Nord
"4", // Manage page elements
"4", // Reorder page elements
"1", // header
"2", // Move down
"0", // Done reordering
"6", // Back from elements
"5", // Back to main hub
"8", // Save
"n", // No backup
// Make an unsaved modification and test exit guard
"3", // Page & Theme
"1", // Page HTML title
"Unsaved Title", // New title
"5", // Back to main hub
"10", // Exit
"3", // Cancel exit guard
"10", // Exit again
"2", // Discard changes & Exit
})
reloaded, _, err := config.LoadOrInit(cfgPath, false)
if err != nil {
t.Fatalf("LoadOrInit failed: %v", err)
}
if reloaded.Page.Theme.BgColor != "#2e3440" {
t.Fatalf("expected Nord theme BgColor #2e3440, got %q", reloaded.Page.Theme.BgColor)
}
if reloaded.Page.Elements[0].Type != "status_banner" || reloaded.Page.Elements[1].Type != "header" {
t.Fatalf("expected header moved after status_banner, got [%s, %s]",
reloaded.Page.Elements[0].Type, reloaded.Page.Elements[1].Type)
}
if reloaded.Page.Title != "R u ded?" {
t.Fatalf("expected discarded title change not to persist, got %q", reloaded.Page.Title)
}
}
func TestBuilderQuickStartWizardPreviewAndSaveAs(t *testing.T) {
tmpDir := t.TempDir()
initialPath := filepath.Join(tmpDir, "initial.json")
saveAsPath := filepath.Join(tmpDir, "wizard-out.json")
out := runScripted(t, Options{ConfigPath: initialPath}, []string{
"1", // Guided Quick-Start Wizard
"", // Listen (:8080)
"", // Endpoint (/)
// Monitor 1
"wiz-cmd",
"Wizard Cmd",
"", // description
"6", // cmd
"echo ok",
"y", // shell
"0", // expected exit code
"^ok$",
"n", // overrides
"y", // test live
"n", // add another monitor
"n", // add event rule
"My Wizard Status",
"y", // pick theme preset
"2", // Clean Light
// Hub: Validate & Preview JSON / Diff
"7",
"1", // diff
"2", // JSON preview
"3", // back
// Save As
"9",
saveAsPath,
"10", // Exit
})
if !strings.Contains(out, `"My Wizard Status"`) {
t.Fatalf("expected preview JSON to contain new title, got:\n%s", out)
}
if _, err := os.Stat(initialPath); !os.IsNotExist(err) {
t.Fatalf("expected initialPath not to be written when using Save As")
}
loaded, raw, err := config.LoadForEdit(saveAsPath)
if err != nil {
t.Fatalf("LoadForEdit on Save As file failed: %v", err)
}
if err := loaded.Validate(); err != nil {
t.Fatalf("saved wizard config invalid: %v", err)
}
if issues := loaded.Lint(raw); len(issues) != 0 {
t.Fatalf("saved wizard config has lint issues: %v", issues)
}
if loaded.Page.Theme.BgColor != "#f8fafc" || len(loaded.Monitors) != 1 || loaded.Monitors[0].ID != "wiz-cmd" {
t.Fatalf("unexpected wizard config: theme=%s monitors=%v", loaded.Page.Theme.BgColor, loaded.Monitors)
}
}