package config import ( "strings" "testing" ) // containsWarning 判断告警列表里是否存在包含指定片段的告警。 func containsWarning(warnings []string, fragment string) bool { for _, w := range warnings { if strings.Contains(w, fragment) { return true } } return false } func TestSecurityWarnings(t *testing.T) { cases := []struct { name string cfg Config wantWarning string // 期望命中的告警片段;为空表示期望无任何告警 }{ { name: "示例 JWT_SECRET 必须告警", cfg: Config{JWTSecret: exampleJWTSecret, Mode: "debug"}, wantWarning: "JWT_SECRET", }, { name: "release 模式开启 OPEN_API_DEBUG 必须告警", cfg: Config{JWTSecret: "a-real-jwt-secret", Mode: "release", OpenAPIDebug: true}, wantWarning: "OPEN_API_DEBUG", }, { name: "健康配置不应产生任何告警", cfg: Config{ JWTSecret: "a-real-jwt-secret", Mode: "release", OpenAPIDebug: false, }, wantWarning: "", }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { warnings := tc.cfg.SecurityWarnings() if tc.wantWarning == "" { if len(warnings) != 0 { t.Fatalf("期望无告警,实际得到 %v", warnings) } return } if !containsWarning(warnings, tc.wantWarning) { t.Fatalf("期望告警包含 %q,实际得到 %v", tc.wantWarning, warnings) } }) } }