|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | + "github.com/thand-io/agent/internal/common" |
| 11 | +) |
| 12 | + |
| 13 | +func TestLoad_PrefersExplicitConfigFileOverEnvOverride(t *testing.T) { |
| 14 | + envConfigPath := writeTestConfigFile(t, filepath.Join(t.TempDir(), "env.yaml"), "env-secret") |
| 15 | + explicitConfigPath := writeTestConfigFile(t, filepath.Join(t.TempDir(), "explicit.yaml"), "explicit-secret") |
| 16 | + |
| 17 | + t.Setenv(configPathEnvVar, envConfigPath) |
| 18 | + |
| 19 | + cfg, err := Load(explicitConfigPath) |
| 20 | + require.NoError(t, err) |
| 21 | + |
| 22 | + assert.Equal(t, "explicit-secret", cfg.Secret) |
| 23 | +} |
| 24 | + |
| 25 | +func TestLoad_UsesConfigPathEnvOverrideWhenFlagNotProvided(t *testing.T) { |
| 26 | + configPath := writeTestConfigFile(t, filepath.Join(t.TempDir(), "env.yaml"), "env-secret") |
| 27 | + |
| 28 | + t.Setenv(configPathEnvVar, configPath) |
| 29 | + |
| 30 | + cfg, err := Load("") |
| 31 | + require.NoError(t, err) |
| 32 | + |
| 33 | + assert.Equal(t, "env-secret", cfg.Secret) |
| 34 | +} |
| 35 | + |
| 36 | +func TestLoad_FindsDefaultConfigInHomeConfigDir(t *testing.T) { |
| 37 | + homeDir := t.TempDir() |
| 38 | + t.Setenv("HOME", homeDir) |
| 39 | + t.Setenv(configPathEnvVar, "") |
| 40 | + |
| 41 | + configPath := filepath.Join(homeDir, ".config", "thand", "config.yaml") |
| 42 | + writeTestConfigFile(t, configPath, "home-secret") |
| 43 | + |
| 44 | + cfg, err := Load("") |
| 45 | + require.NoError(t, err) |
| 46 | + |
| 47 | + assert.Equal(t, "home-secret", cfg.Secret) |
| 48 | +} |
| 49 | + |
| 50 | +func TestLoad_DoesNotUseLegacyThandConfigPath(t *testing.T) { |
| 51 | + homeDir := t.TempDir() |
| 52 | + t.Setenv("HOME", homeDir) |
| 53 | + t.Setenv(configPathEnvVar, "") |
| 54 | + |
| 55 | + legacyConfigPath := filepath.Join(homeDir, ".thand", "config.yaml") |
| 56 | + writeTestConfigFile(t, legacyConfigPath, "legacy-secret") |
| 57 | + |
| 58 | + cfg, err := Load("") |
| 59 | + require.NoError(t, err) |
| 60 | + |
| 61 | + assert.Equal(t, common.DefaultServerSecret, cfg.Secret) |
| 62 | +} |
| 63 | + |
| 64 | +func writeTestConfigFile(t *testing.T, path string, secret string) string { |
| 65 | + t.Helper() |
| 66 | + |
| 67 | + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) |
| 68 | + require.NoError(t, os.WriteFile(path, []byte("secret: "+secret+"\n"), 0o644)) |
| 69 | + |
| 70 | + return path |
| 71 | +} |
0 commit comments