package config import ( "os" "testing" "time" ) // TestDefaultConfigUsesLocalhostAndSaneIntervals 验证默认配置使用本地监听地址与合理的采集间隔。 func TestDefaultConfigUsesLocalhostAndSaneIntervals(t *testing.T) { cfg := Default() if cfg.HTTP.ListenAddress != "127.0.0.1:8080" { t.Fatalf("listen address = %q", cfg.HTTP.ListenAddress) } if cfg.Collect.Interval <= 0 || cfg.Collect.Timeout <= 0 { t.Fatalf("collect intervals must be positive: %+v", cfg.Collect) } if cfg.Report.Enabled { t.Fatal("reporting should be disabled by default") } } // TestLoadAppliesEnvironmentOverrides 验证环境变量可覆盖默认配置。 func TestLoadAppliesEnvironmentOverrides(t *testing.T) { t.Setenv("MFD_AGENT_LISTEN", "127.0.0.1:9090") t.Setenv("MFD_AGENT_REPORT_ENABLED", "true") t.Setenv("MFD_AGENT_REPORT_ENDPOINT", "http://center/status") t.Setenv("MFD_AGENT_REPORT_INTERVAL", "2s") t.Setenv("MFD_AGENT_HOST_ID", "host-a") cfg, err := Load("") if err != nil { t.Fatal(err) } if cfg.HTTP.ListenAddress != "127.0.0.1:9090" { t.Fatalf("listen address = %q", cfg.HTTP.ListenAddress) } if !cfg.Report.Enabled || cfg.Report.Endpoint != "http://center/status" { t.Fatalf("report config not applied: %+v", cfg.Report) } if cfg.Report.Interval.Duration() != 2*time.Second { t.Fatalf("report interval = %s", cfg.Report.Interval.Duration()) } if cfg.HostID != "host-a" { t.Fatalf("host id = %q", cfg.HostID) } } // TestLoadJSONConfigFile 验证可从 JSON 配置文件解析 Config。 func TestLoadJSONConfigFile(t *testing.T) { file, err := os.CreateTemp(t.TempDir(), "config-*.json") if err != nil { t.Fatal(err) } _, _ = file.WriteString(`{"http":{"listen_address":"127.0.0.1:7070"},"collect":{"interval":"3s","timeout":"1s"}}`) _ = file.Close() cfg, err := Load(file.Name()) if err != nil { t.Fatal(err) } if cfg.HTTP.ListenAddress != "127.0.0.1:7070" { t.Fatalf("listen address = %q", cfg.HTTP.ListenAddress) } if cfg.Collect.Interval.Duration() != 3*time.Second || cfg.Collect.Timeout.Duration() != time.Second { t.Fatalf("collect config = %+v", cfg.Collect) } }