package config_test import ( "os" "path/filepath" "testing" "time" "github.com/go-playground/validator/v10" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "mtusi-messenger/internal/config" "mtusi-messenger/internal/logger" ) func TestDefaults(t *testing.T) { cfg, err := config.Load() require.NoError(t, err) assert.Equal(t, "0.0.0.0", cfg.Server.Host) assert.Equal(t, 8080, cfg.Server.Port) assert.Equal(t, 10*time.Second, cfg.Server.ReadHeaderTimeout) assert.Equal(t, 10*time.Second, cfg.Server.ShutdownTimeout) assert.Equal(t, "info", cfg.Log.Level) assert.Equal(t, "json", cfg.Log.Format) assert.Equal(t, config.Postgres{}, cfg.Postgres, "postgres defaults live in the adapter") } func TestEnvOverridesDefaults(t *testing.T) { t.Setenv("SERVER_HOST", "127.0.0.1") t.Setenv("SERVER_PORT", "9090") t.Setenv("SERVER_READ_HEADER_TIMEOUT", "3s") t.Setenv("SERVER_SHUTDOWN_TIMEOUT", "30s") t.Setenv("LOG_LEVEL", "debug") t.Setenv("LOG_FORMAT", "console") cfg, err := config.Load() require.NoError(t, err) assert.Equal(t, "127.0.0.1", cfg.Server.Host) assert.Equal(t, 9090, cfg.Server.Port) assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout) assert.Equal(t, 30*time.Second, cfg.Server.ShutdownTimeout) assert.Equal(t, "debug", cfg.Log.Level) assert.Equal(t, "console", cfg.Log.Format) } func TestDsnEncodesCredentials(t *testing.T) { cfg := config.Postgres{ Host: "db", Port: 5432, Database: "app", User: "user", Password: "p@ss:w/rd", SSLMode: "disable", } assert.Equal(t, "postgres://user:p%40ss%3Aw%2Frd@db:5432/app?sslmode=disable", cfg.DSN()) } func writeConfig(t *testing.T, body string) string { t.Helper() path := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(path, []byte(body), 0o600)) return path } func TestLoadsYAMLFile(t *testing.T) { path := writeConfig(t, ` env: dev server: host: 10.0.0.1 port: 9999 read_header_timeout: 3s shutdown_timeout: 7s log: level: debug format: console postgres: host: db port: 5433 database: app user: app password: secret ssl_mode: disable max_conns: 7 min_conns: 2 max_conn_lifetime: 2h max_conn_idle_time: 10m connect_timeout: 2s query_timeout: 3s `) t.Setenv("APP_CONFIG", path) cfg, err := config.Load() require.NoError(t, err) assert.Equal(t, "10.0.0.1", cfg.Server.Host) assert.Equal(t, 9999, cfg.Server.Port) assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout) assert.Equal(t, "debug", cfg.Log.Level) assert.Equal(t, "console", cfg.Log.Format) assert.Equal(t, "db", cfg.Postgres.Host) assert.Equal(t, 5433, cfg.Postgres.Port) assert.Equal(t, "app", cfg.Postgres.Database) assert.Equal(t, int32(7), cfg.Postgres.MaxConns) assert.Equal(t, 2*time.Second, cfg.Postgres.ConnectTimeout) } func TestEnvOverridesYAML(t *testing.T) { path := writeConfig(t, ` env: dev server: host: 10.0.0.1 port: 9999 read_header_timeout: 3s shutdown_timeout: 7s log: level: debug format: console postgres: host: db port: 5433 database: app user: app password: file ssl_mode: disable `) t.Setenv("APP_CONFIG", path) t.Setenv("SERVER_HOST", "127.0.0.1") t.Setenv("POSTGRES_PASSWORD", "env") cfg, err := config.Load() require.NoError(t, err) assert.Equal(t, "127.0.0.1", cfg.Server.Host, "env переопределяет YAML") assert.Equal(t, 9999, cfg.Server.Port) assert.Equal(t, "env", cfg.Postgres.Password) } func TestSessionTTLFromContractEnv(t *testing.T) { t.Setenv("SESSION_TTL_SECONDS", "2") cfg, err := config.Load() require.NoError(t, err) assert.Equal(t, 2, cfg.Session.TTLSeconds) } func TestInvalidValues(t *testing.T) { tests := map[string]map[string]string{ "пустой server.host": {"SERVER_HOST": ""}, "host не адрес и не имя": {"SERVER_HOST": "не адрес"}, "порт ниже диапазона": {"SERVER_PORT": "0"}, "порт выше диапазона": {"SERVER_PORT": "65536"}, "нулевой read header timeout": {"SERVER_READ_HEADER_TIMEOUT": "0s"}, "отрицательный shutdown": {"SERVER_SHUTDOWN_TIMEOUT": "-1s"}, "неизвестный log level": {"LOG_LEVEL": "trace"}, "неизвестный log format": {"LOG_FORMAT": "xml"}, } for name, env := range tests { t.Run(name, func(t *testing.T) { for key, value := range env { t.Setenv(key, value) } _, err := config.Load() require.Error(t, err) var validationErrs validator.ValidationErrors require.ErrorAs(t, err, &validationErrs) require.NotEmpty(t, validationErrs) }) } } func TestInvalidPostgresValues(t *testing.T) { path := writeConfig(t, ` env: dev postgres: host: db port: 5432 database: messenger user: messenger ssl_mode: disable max_conns: 10 `) tests := map[string]map[string]string{ "неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"}, "отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"}, } for name, env := range tests { t.Run(name, func(t *testing.T) { t.Setenv("APP_CONFIG", path) for key, value := range env { t.Setenv(key, value) } _, err := config.Load() require.Error(t, err) var validationErrs validator.ValidationErrors require.ErrorAs(t, err, &validationErrs) require.NotEmpty(t, validationErrs) }) } } func TestUnparsableValues(t *testing.T) { tests := map[string]map[string]string{ "порт не число": {"SERVER_PORT": "не-число"}, "timeout не duration": {"SERVER_READ_HEADER_TIMEOUT": "быстро"}, } for name, env := range tests { t.Run(name, func(t *testing.T) { for key, value := range env { t.Setenv(key, value) } _, err := config.Load() require.Error(t, err) }) } } func TestLoggerSettings(t *testing.T) { t.Setenv("LOG_LEVEL", "warn") t.Setenv("LOG_FORMAT", "console") cfg, err := config.Load() require.NoError(t, err) level, err := logger.ParseLevel(cfg.Log.Level) require.NoError(t, err) assert.Equal(t, level, cfg.SlogLevel()) format, err := logger.ParseFormat(cfg.Log.Format) require.NoError(t, err) assert.Equal(t, format, cfg.LoggerFormat()) } func TestAddr(t *testing.T) { t.Setenv("SERVER_HOST", "0.0.0.0") t.Setenv("SERVER_PORT", "8080") cfg, err := config.Load() require.NoError(t, err) assert.Equal(t, "0.0.0.0:8080", cfg.Addr()) } func TestAddrWithIPv6Host(t *testing.T) { t.Setenv("SERVER_HOST", "::1") cfg, err := config.Load() require.NoError(t, err) assert.Equal(t, "[::1]:8080", cfg.Addr()) } func TestLoadIsIndependentOfProcessState(t *testing.T) { t.Setenv("SERVER_PORT", "7070") first, err := config.Load() require.NoError(t, err) second, err := config.Load() require.NoError(t, err) assert.Equal(t, first, second) } func TestRedisDefaultsDisabled(t *testing.T) { cfg, err := config.Load() require.NoError(t, err) assert.False(t, cfg.Redis.Enabled) assert.Equal(t, "localhost", cfg.Redis.Host) assert.Equal(t, 6379, cfg.Redis.Port) assert.Equal(t, -1, cfg.Redis.MaxRetries) assert.Equal(t, 300*time.Millisecond, cfg.Redis.DialTimeout) assert.Equal(t, 200*time.Millisecond, cfg.Redis.ReadTimeout) assert.Equal(t, 200*time.Millisecond, cfg.Redis.WriteTimeout) assert.False(t, cfg.Cache.Enabled) assert.Equal(t, 5*time.Minute, cfg.Cache.ChatListTTL) assert.Equal(t, 10*time.Second, cfg.Cache.LockTTL) assert.Equal(t, 2*time.Second, cfg.Cache.LockWaitTimeout) } func TestRedisEnvOverrides(t *testing.T) { t.Setenv("REDIS_ENABLED", "true") t.Setenv("REDIS_HOST", "cache") t.Setenv("REDIS_PORT", "6380") t.Setenv("CACHE_ENABLED", "true") t.Setenv("CACHE_CHAT_LIST_TTL", "1m") t.Setenv("CACHE_LOCK_TTL", "7s") t.Setenv("CACHE_LOCK_WAIT_TIMEOUT", "1500ms") cfg, err := config.Load() require.NoError(t, err) assert.True(t, cfg.Redis.Enabled) assert.Equal(t, "cache", cfg.Redis.Host) assert.Equal(t, 6380, cfg.Redis.Port) assert.True(t, cfg.Cache.Enabled) assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL) assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL) assert.Equal(t, 1500*time.Millisecond, cfg.Cache.LockWaitTimeout) } func TestInvalidCacheTTL(t *testing.T) { for _, key := range []string{ "CACHE_CHAT_LIST_TTL", "CACHE_LOCK_TTL", "CACHE_LOCK_WAIT_TIMEOUT", } { for _, value := range []string{"0s", "-1s"} { t.Run(key+"/"+value, func(t *testing.T) { t.Setenv(key, value) _, err := config.Load() require.Error(t, err) var validationErrs validator.ValidationErrors require.ErrorAs(t, err, &validationErrs) }) } } } func TestCacheRequiresRedis(t *testing.T) { t.Setenv("CACHE_ENABLED", "true") _, err := config.Load() require.ErrorContains(t, err, "cache.enabled requires redis.enabled") }