| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | |
| 9 | log "github.com/sirupsen/logrus" |
| 10 | ) |
| 11 | |
| 12 | func TestGetEnv(t *testing.T) { |
| 13 | tests := []struct { |
| 14 | name string |
| 15 | key string |
| 16 | defaultVal string |
| 17 | envValue string |
| 18 | setEnv bool |
| 19 | expected string |
| 20 | }{ |
| 21 | { |
| 22 | name: "environment variable exists", |
| 23 | key: "TEST_ENV_VAR", |
| 24 | defaultVal: "default", |
| 25 | envValue: "from_env", |
| 26 | setEnv: true, |
| 27 | expected: "from_env", |
| 28 | }, |
| 29 | { |
| 30 | name: "environment variable does not exist", |
| 31 | key: "NONEXISTENT_ENV_VAR", |
| 32 | defaultVal: "default_value", |
| 33 | setEnv: false, |
| 34 | expected: "default_value", |
| 35 | }, |
| 36 | { |
| 37 | name: "empty environment variable", |
| 38 | key: "EMPTY_ENV_VAR", |
| 39 | defaultVal: "default", |
| 40 | envValue: "", |
| 41 | setEnv: true, |
| 42 | expected: "", |
| 43 | }, |
| 44 | } |
| 45 | |
| 46 | for _, tt := range tests { |
| 47 | t.Run(tt.name, func(t *testing.T) { |
| 48 | if tt.setEnv { |
| 49 | os.Setenv(tt.key, tt.envValue) |
| 50 | defer os.Unsetenv(tt.key) |
| 51 | } |
| 52 | |
| 53 | result := getEnv(tt.key, tt.defaultVal) |
| 54 | if result != tt.expected { |
| 55 | t.Errorf("getEnv() = %v, expected %v", result, tt.expected) |
| 56 | } |
| 57 | }) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | func TestGetEnvBool(t *testing.T) { |
| 62 | tests := []struct { |
| 63 | name string |
| 64 | key string |
| 65 | defaultVal bool |
| 66 | envValue string |
| 67 | setEnv bool |
| 68 | expected bool |
| 69 | }{ |
| 70 | { |
| 71 | name: "true from environment", |
| 72 | key: "TEST_BOOL_TRUE", |
| 73 | defaultVal: false, |
| 74 | envValue: "true", |
| 75 | setEnv: true, |
| 76 | expected: true, |
| 77 | }, |
| 78 | { |
| 79 | name: "false from environment", |
| 80 | key: "TEST_BOOL_FALSE", |
| 81 | defaultVal: true, |
| 82 | envValue: "false", |
| 83 | setEnv: true, |
| 84 | expected: false, |
| 85 | }, |
| 86 | { |
| 87 | name: "1 from environment (true)", |
| 88 | key: "TEST_BOOL_ONE", |
| 89 | defaultVal: false, |
| 90 | envValue: "1", |
| 91 | setEnv: true, |
| 92 | expected: true, |
| 93 | }, |
| 94 | { |
| 95 | name: "0 from environment (false)", |
| 96 | key: "TEST_BOOL_ZERO", |
| 97 | defaultVal: true, |
| 98 | envValue: "0", |
| 99 | setEnv: true, |
| 100 | expected: false, |
| 101 | }, |
| 102 | { |
| 103 | name: "invalid bool value returns default", |
| 104 | key: "TEST_BOOL_INVALID", |
| 105 | defaultVal: true, |
| 106 | envValue: "invalid", |
| 107 | setEnv: true, |
| 108 | expected: true, |
| 109 | }, |
| 110 | { |
| 111 | name: "environment variable does not exist", |
| 112 | key: "NONEXISTENT_BOOL_VAR", |
| 113 | defaultVal: false, |
| 114 | setEnv: false, |
| 115 | expected: false, |
| 116 | }, |
| 117 | } |
| 118 | |
| 119 | for _, tt := range tests { |
| 120 | t.Run(tt.name, func(t *testing.T) { |
| 121 | if tt.setEnv { |
| 122 | os.Setenv(tt.key, tt.envValue) |
| 123 | defer os.Unsetenv(tt.key) |
| 124 | } |
| 125 | |
| 126 | result := getEnvBool(tt.key, tt.defaultVal) |
| 127 | if result != tt.expected { |
| 128 | t.Errorf("getEnvBool() = %v, expected %v", result, tt.expected) |
| 129 | } |
| 130 | }) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | func TestGetEnvInt64(t *testing.T) { |
| 135 | tests := []struct { |
| 136 | name string |
| 137 | key string |
| 138 | defaultVal int64 |
| 139 | envValue string |
| 140 | setEnv bool |
| 141 | expected int64 |
| 142 | }{ |
| 143 | { |
| 144 | name: "valid positive integer", |
| 145 | key: "TEST_INT_POSITIVE", |
| 146 | defaultVal: 100, |
| 147 | envValue: "1234", |
| 148 | setEnv: true, |
| 149 | expected: 1234, |
| 150 | }, |
| 151 | { |
| 152 | name: "valid negative integer", |
| 153 | key: "TEST_INT_NEGATIVE", |
| 154 | defaultVal: 100, |
| 155 | envValue: "-567", |
| 156 | setEnv: true, |
| 157 | expected: -567, |
| 158 | }, |
| 159 | { |
| 160 | name: "zero value", |
| 161 | key: "TEST_INT_ZERO", |
| 162 | defaultVal: 100, |
| 163 | envValue: "0", |
| 164 | setEnv: true, |
| 165 | expected: 0, |
| 166 | }, |
| 167 | { |
| 168 | name: "invalid integer returns default", |
| 169 | key: "TEST_INT_INVALID", |
| 170 | defaultVal: 999, |
| 171 | envValue: "not_a_number", |
| 172 | setEnv: true, |
| 173 | expected: 999, |
| 174 | }, |
| 175 | { |
| 176 | name: "empty value returns default", |
| 177 | key: "TEST_INT_EMPTY", |
| 178 | defaultVal: 500, |
| 179 | envValue: "", |
| 180 | setEnv: true, |
| 181 | expected: 500, |
| 182 | }, |
| 183 | { |
| 184 | name: "environment variable does not exist", |
| 185 | key: "NONEXISTENT_INT_VAR", |
| 186 | defaultVal: 42, |
| 187 | setEnv: false, |
| 188 | expected: 42, |
| 189 | }, |
| 190 | { |
| 191 | name: "large integer value", |
| 192 | key: "TEST_INT_LARGE", |
| 193 | defaultVal: 1, |
| 194 | envValue: "9223372036854775807", // max int64 |
| 195 | setEnv: true, |
| 196 | expected: 9223372036854775807, |
| 197 | }, |
| 198 | } |
| 199 | |
| 200 | for _, tt := range tests { |
| 201 | t.Run(tt.name, func(t *testing.T) { |
| 202 | if tt.setEnv { |
| 203 | os.Setenv(tt.key, tt.envValue) |
| 204 | defer os.Unsetenv(tt.key) |
| 205 | } |
| 206 | |
| 207 | result := getEnvInt64(tt.key, tt.defaultVal) |
| 208 | if result != tt.expected { |
| 209 | t.Errorf("getEnvInt64() = %v, expected %v", result, tt.expected) |
| 210 | } |
| 211 | }) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | func TestParseLogLevel(t *testing.T) { |
| 216 | tests := []struct { |
| 217 | name string |
| 218 | level string |
| 219 | expected log.Level |
| 220 | expectError bool |
| 221 | }{ |
| 222 | {"debug level", "debug", log.DebugLevel, false}, |
| 223 | {"DEBUG level", "DEBUG", log.DebugLevel, false}, |
| 224 | {"info level", "info", log.InfoLevel, false}, |
| 225 | {"INFO level", "INFO", log.InfoLevel, false}, |
| 226 | {"warn level", "warn", log.WarnLevel, false}, |
| 227 | {"WARN level", "WARN", log.WarnLevel, false}, |
| 228 | {"warning level", "warning", log.WarnLevel, false}, |
| 229 | {"WARNING level", "WARNING", log.WarnLevel, false}, |
| 230 | {"error level", "error", log.ErrorLevel, false}, |
| 231 | {"ERROR level", "ERROR", log.ErrorLevel, false}, |
| 232 | {"invalid level", "invalid", log.InfoLevel, true}, |
| 233 | {"empty level", "", log.InfoLevel, true}, |
| 234 | } |
| 235 | |
| 236 | for _, tt := range tests { |
| 237 | t.Run(tt.name, func(t *testing.T) { |
| 238 | result, err := parseLogLevel(tt.level) |
| 239 | if tt.expectError { |
| 240 | if err == nil { |
| 241 | t.Errorf("parseLogLevel(%s) expected error but got none", tt.level) |
| 242 | } |
| 243 | // For invalid levels, we still expect InfoLevel as default |
| 244 | if result != tt.expected { |
| 245 | t.Errorf("parseLogLevel(%s) = %v, expected %v", tt.level, result, tt.expected) |
| 246 | } |
| 247 | } else { |
| 248 | if err != nil { |
| 249 | t.Errorf("parseLogLevel(%s) unexpected error: %v", tt.level, err) |
| 250 | } |
| 251 | if result != tt.expected { |
| 252 | t.Errorf("parseLogLevel(%s) = %v, expected %v", tt.level, result, tt.expected) |
| 253 | } |
| 254 | } |
| 255 | }) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | func TestValidateTLSClientConfig(t *testing.T) { |
| 260 | tests := []struct { |
| 261 | name string |
| 262 | certFile string |
| 263 | keyFile string |
| 264 | expectError bool |
| 265 | }{ |
| 266 | {"both files provided", "/path/to/cert.pem", "/path/to/key.pem", false}, |
| 267 | {"both files empty", "", "", false}, |
| 268 | {"only cert file provided", "/path/to/cert.pem", "", true}, |
| 269 | {"only key file provided", "", "/path/to/key.pem", true}, |
| 270 | } |
| 271 | |
| 272 | for _, tt := range tests { |
| 273 | t.Run(tt.name, func(t *testing.T) { |
| 274 | err := validateTLSClientConfig(tt.certFile, tt.keyFile) |
| 275 | if tt.expectError { |
| 276 | if err == nil { |
| 277 | t.Errorf("validateTLSClientConfig(%s, %s) expected error but got none", tt.certFile, tt.keyFile) |
| 278 | } |
| 279 | } else { |
| 280 | if err != nil { |
| 281 | t.Errorf("validateTLSClientConfig(%s, %s) unexpected error: %v", tt.certFile, tt.keyFile, err) |
| 282 | } |
| 283 | } |
| 284 | }) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | func TestLoadScripts(t *testing.T) { |
| 289 | // Create temporary directory for test scripts |
| 290 | tmpDir := t.TempDir() |
| 291 | |
| 292 | // Create test script files |
| 293 | script1 := filepath.Join(tmpDir, "script1.lua") |
| 294 | script1Content := "return {\"key1\", \"value1\"}" |
| 295 | if err := os.WriteFile(script1, []byte(script1Content), 0644); err != nil { |
| 296 | t.Fatalf("Failed to create test script1: %v", err) |
| 297 | } |
| 298 | |
| 299 | script2 := filepath.Join(tmpDir, "script2.lua") |
| 300 | script2Content := "return {\"key2\", \"value2\"}" |
| 301 | if err := os.WriteFile(script2, []byte(script2Content), 0644); err != nil { |
| 302 | t.Fatalf("Failed to create test script2: %v", err) |
| 303 | } |
| 304 | |
| 305 | tests := []struct { |
| 306 | name string |
| 307 | scriptPath string |
| 308 | expectError bool |
| 309 | expectedLen int |
| 310 | }{ |
| 311 | {"empty script path", "", false, 0}, |
| 312 | {"single script", script1, false, 1}, |
| 313 | {"multiple scripts", script1 + "," + script2, false, 2}, |
| 314 | {"nonexistent script", "/nonexistent/script.lua", true, 0}, |
| 315 | {"mixed valid and invalid", script1 + ",/nonexistent/script.lua", true, 0}, |
| 316 | } |
| 317 | |
| 318 | for _, tt := range tests { |
| 319 | t.Run(tt.name, func(t *testing.T) { |
| 320 | result, err := loadScripts(tt.scriptPath) |
| 321 | if tt.expectError { |
| 322 | if err == nil { |
| 323 | t.Errorf("loadScripts(%s) expected error but got none", tt.scriptPath) |
| 324 | } |
| 325 | } else { |
| 326 | if err != nil { |
| 327 | t.Errorf("loadScripts(%s) unexpected error: %v", tt.scriptPath, err) |
| 328 | } |
| 329 | if tt.expectedLen == 0 && result != nil { |
| 330 | t.Errorf("loadScripts(%s) expected nil result but got %v", tt.scriptPath, result) |
| 331 | } |
| 332 | if tt.expectedLen > 0 { |
| 333 | if result == nil { |
| 334 | t.Errorf("loadScripts(%s) expected non-nil result", tt.scriptPath) |
| 335 | } else if len(result) != tt.expectedLen { |
| 336 | t.Errorf("loadScripts(%s) expected %d scripts, got %d", tt.scriptPath, tt.expectedLen, len(result)) |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | // Verify content for successful cases |
| 342 | if !tt.expectError && tt.expectedLen > 0 { |
| 343 | scripts := strings.SplitSeq(tt.scriptPath, ",") |
| 344 | for scriptPath := range scripts { |
| 345 | if content, exists := result[scriptPath]; !exists { |
| 346 | t.Errorf("loadScripts(%s) missing script %s", tt.scriptPath, scriptPath) |
| 347 | } else if len(content) == 0 { |
| 348 | t.Errorf("loadScripts(%s) empty content for script %s", tt.scriptPath, scriptPath) |
| 349 | } |
| 350 | } |
| 351 | } |
| 352 | }) |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | func TestSetupLogging(t *testing.T) { |
| 357 | // Save original log level to restore after tests |
| 358 | originalLevel := log.GetLevel() |
| 359 | defer log.SetLevel(originalLevel) |
| 360 | |
| 361 | tests := []struct { |
| 362 | name string |
| 363 | isDebug bool |
| 364 | logLevel string |
| 365 | logFormat string |
| 366 | expectedLevel log.Level |
| 367 | }{ |
| 368 | {"debug enabled", true, "info", "txt", log.DebugLevel}, |
| 369 | {"info level", false, "info", "txt", log.InfoLevel}, |
| 370 | {"warn level", false, "warn", "txt", log.WarnLevel}, |
| 371 | {"error level", false, "error", "txt", log.ErrorLevel}, |
| 372 | {"invalid level defaults to info", false, "invalid", "txt", log.InfoLevel}, |
| 373 | {"json format", false, "info", "json", log.InfoLevel}, |
| 374 | {"text format", false, "info", "txt", log.InfoLevel}, |
| 375 | } |
| 376 | |
| 377 | for _, tt := range tests { |
| 378 | t.Run(tt.name, func(t *testing.T) { |
| 379 | err := setupLogging(tt.isDebug, tt.logLevel, tt.logFormat) |
| 380 | if err != nil { |
| 381 | t.Errorf("setupLogging() unexpected error: %v", err) |
| 382 | } |
| 383 | |
| 384 | if log.GetLevel() != tt.expectedLevel { |
| 385 | t.Errorf("setupLogging() level = %v, expected %v", log.GetLevel(), tt.expectedLevel) |
| 386 | } |
| 387 | |
| 388 | // Check formatter type (basic check) |
| 389 | formatter := log.StandardLogger().Formatter |
| 390 | if tt.logFormat == "json" { |
| 391 | if _, ok := formatter.(*log.JSONFormatter); !ok { |
| 392 | t.Errorf("setupLogging() expected JSONFormatter for json format") |
| 393 | } |
| 394 | } else { |
| 395 | if _, ok := formatter.(*log.TextFormatter); !ok { |
| 396 | t.Errorf("setupLogging() expected TextFormatter for txt format") |
| 397 | } |
| 398 | } |
| 399 | }) |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | func TestCreatePrometheusRegistry(t *testing.T) { |
| 404 | tests := []struct { |
| 405 | name string |
| 406 | redisMetricsOnly bool |
| 407 | inclGoRuntimeMetrics bool |
| 408 | description string |
| 409 | }{ |
| 410 | {"redis metrics only", true, false, "should create registry with only Redis metrics"}, |
| 411 | {"redis + process metrics", false, false, "should create registry with Redis and process metrics"}, |
| 412 | {"all metrics", false, true, "should create registry with process and Go metrics"}, |
| 413 | } |
| 414 | |
| 415 | for _, tt := range tests { |
| 416 | t.Run(tt.name, func(t *testing.T) { |
| 417 | registry := createPrometheusRegistry(tt.redisMetricsOnly, tt.inclGoRuntimeMetrics) |
| 418 | if registry == nil { |
| 419 | t.Errorf("createPrometheusRegistry(%v, %v) returned nil registry", tt.redisMetricsOnly, tt.inclGoRuntimeMetrics) |
| 420 | } |
| 421 | |
| 422 | // Verify it's a valid Prometheus registry (it's already *prometheus.Registry) |
| 423 | |
| 424 | // Basic functionality test - gather metrics |
| 425 | metricFamilies, err := registry.Gather() |
| 426 | if err != nil { |
| 427 | t.Errorf("createPrometheusRegistry(%v, %v) registry.Gather() error: %v", tt.redisMetricsOnly, tt.inclGoRuntimeMetrics, err) |
| 428 | } |
| 429 | |
| 430 | // When redisMetricsOnly=false, inclGoRuntimeMetrics=false we should have process metrics |
| 431 | // When redisMetricsOnly=false, inclGoRuntimeMetrics=true we should have Go process+runtime metrics |
| 432 | // When redisMetricsOnly=true, we should have fewer (or no) built-in metrics |
| 433 | if !tt.redisMetricsOnly { |
| 434 | if len(metricFamilies) == 0 { |
| 435 | t.Errorf("createPrometheusRegistry(%v, %v) expected Go process+runtime metrics but got none", tt.redisMetricsOnly, tt.inclGoRuntimeMetrics) |
| 436 | } |
| 437 | if !tt.inclGoRuntimeMetrics { |
| 438 | if len(metricFamilies) > 20 { // process metrics count is less than 10 |
| 439 | t.Errorf("createPrometheusRegistry(%v, %v) expected only process metrics but got %v metrics", tt.redisMetricsOnly, tt.inclGoRuntimeMetrics, len(metricFamilies)) |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | }) |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | // Integration test to verify the functions work together |
| 448 | func TestMainFunctionsIntegration(t *testing.T) { |
| 449 | // Test that the extracted functions can be used together |
| 450 | tmpDir := t.TempDir() |
| 451 | scriptFile := filepath.Join(tmpDir, "test.lua") |
| 452 | scriptContent := "return redis.call('ping')" |
| 453 | |
| 454 | if err := os.WriteFile(scriptFile, []byte(scriptContent), 0644); err != nil { |
| 455 | t.Fatalf("Failed to create test script: %v", err) |
| 456 | } |
| 457 | |
| 458 | // Test logging setup |
| 459 | originalLevel := log.GetLevel() |
| 460 | defer log.SetLevel(originalLevel) |
| 461 | |
| 462 | err := setupLogging(false, "debug", "json") |
| 463 | if err != nil { |
| 464 | t.Errorf("setupLogging failed: %v", err) |
| 465 | } |
| 466 | |
| 467 | if log.GetLevel() != log.DebugLevel { |
| 468 | t.Errorf("Expected debug level, got %v", log.GetLevel()) |
| 469 | } |
| 470 | |
| 471 | // Test script loading |
| 472 | scripts, err := loadScripts(scriptFile) |
| 473 | if err != nil { |
| 474 | t.Errorf("loadScripts failed: %v", err) |
| 475 | } |
| 476 | |
| 477 | if len(scripts) != 1 { |
| 478 | t.Errorf("Expected 1 script, got %d", len(scripts)) |
| 479 | } |
| 480 | |
| 481 | if string(scripts[scriptFile]) != scriptContent { |
| 482 | t.Errorf("Script content mismatch") |
| 483 | } |
| 484 | |
| 485 | // Test TLS validation |
| 486 | if err := validateTLSClientConfig("/cert.pem", ""); err == nil { |
| 487 | t.Error("Expected TLS validation error for mismatched cert/key") |
| 488 | } |
| 489 | |
| 490 | if err := validateTLSClientConfig("/cert.pem", "/key.pem"); err != nil { |
| 491 | t.Errorf("Unexpected TLS validation error: %v", err) |
| 492 | } |
| 493 | |
| 494 | // Test registry creation |
| 495 | registry := createPrometheusRegistry(true, false) |
| 496 | if registry == nil { |
| 497 | t.Error("Registry creation failed") |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | func TestValidateAuthParams(t *testing.T) { |
| 502 | tests := []struct { |
| 503 | name string |
| 504 | basicAuthPassword string |
| 505 | basicAuthHashPassword string |
| 506 | expectError bool |
| 507 | }{ |
| 508 | { |
| 509 | name: "Both passwords set", |
| 510 | basicAuthPassword: "password", |
| 511 | basicAuthHashPassword: "$2b$12$ODSJd0tmxY7H/adgD7R5SO43d8nmhUsa8OM6Weo7VFs3MbrsEY7tu", |
| 512 | expectError: true, |
| 513 | }, |
| 514 | { |
| 515 | name: "Only basicAuthPassword set", |
| 516 | basicAuthPassword: "password", |
| 517 | basicAuthHashPassword: "", |
| 518 | expectError: false, |
| 519 | }, |
| 520 | { |
| 521 | name: "Only basicAuthHashPassword set", |
| 522 | basicAuthPassword: "", |
| 523 | basicAuthHashPassword: "$2b$12$ODSJd0tmxY7H/adgD7R5SO43d8nmhUsa8OM6Weo7VFs3MbrsEY7tu", |
| 524 | expectError: false, |
| 525 | }, |
| 526 | { |
| 527 | name: "Invalid basicAuthHashPassword", |
| 528 | basicAuthPassword: "", |
| 529 | basicAuthHashPassword: "invalid_hash", |
| 530 | expectError: true, |
| 531 | }, |
| 532 | { |
| 533 | name: "Neither password set", |
| 534 | basicAuthPassword: "", |
| 535 | basicAuthHashPassword: "", |
| 536 | expectError: false, |
| 537 | }, |
| 538 | } |
| 539 | |
| 540 | for _, tt := range tests { |
| 541 | t.Run(tt.name, func(t *testing.T) { |
| 542 | err := validateAuthParams(tt.basicAuthPassword, tt.basicAuthHashPassword) |
| 543 | if (err != nil) != tt.expectError { |
| 544 | t.Errorf("Expected error: %v, got: %v", tt.expectError, err) |
| 545 | } |
| 546 | }) |
| 547 | } |
| 548 | } |