mugit/internal/config/config_test.go (view raw)
| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "testing" |
| 7 | |
| 8 | "olexsmir.xyz/x/is" |
| 9 | ) |
| 10 | |
| 11 | func TestConfig_parseValue(t *testing.T) { |
| 12 | def := "qwerty123" |
| 13 | |
| 14 | t.Run("string", func(t *testing.T) { |
| 15 | r, err := parseValue(def) |
| 16 | is.Err(t, err, nil) |
| 17 | is.Equal(t, r, def) |
| 18 | }) |
| 19 | |
| 20 | t.Run("env var", func(t *testing.T) { |
| 21 | t.Setenv("secret_value", "123") |
| 22 | r, err := parseValue("$env:secret_value") |
| 23 | is.Err(t, err, nil) |
| 24 | is.Equal(t, r, "123") |
| 25 | }) |
| 26 | |
| 27 | t.Run("unset env var", func(t *testing.T) { |
| 28 | _, err := parseValue("$env:secret_password") |
| 29 | is.Err(t, err, ErrUnsetEnv) |
| 30 | }) |
| 31 | |
| 32 | t.Run("file", func(t *testing.T) { |
| 33 | fpath, _ := filepath.Abs("./testdata/file_value") |
| 34 | r, err := parseValue("$file:" + fpath) |
| 35 | is.Err(t, err, nil) |
| 36 | is.Equal(t, r, def) |
| 37 | }) |
| 38 | |
| 39 | t.Run("non existing file", func(t *testing.T) { |
| 40 | _, err := parseValue("$file:/not/exists") |
| 41 | is.Err(t, err, ErrFileNotFound) |
| 42 | }) |
| 43 | |
| 44 | t.Run("file, not set path", func(t *testing.T) { |
| 45 | _, err := parseValue("$file:") |
| 46 | is.Err(t, err, ErrFileNotFound) |
| 47 | }) |
| 48 | } |
| 49 | |
| 50 | func TestPathOrDefaultWithCandidates(t *testing.T) { |
| 51 | first := candidateFile(t, "first.yaml") |
| 52 | second := candidateFile(t, "second.yaml") |
| 53 | third := candidateFile(t, "third.yaml") |
| 54 | |
| 55 | t.Run("returns user path when exists", func(t *testing.T) { |
| 56 | userPath := candidateFile(t, "user.yaml") |
| 57 | candidates := []string{first, second, third} |
| 58 | got := pathOrDefaultWithCandidates(userPath, candidates) |
| 59 | if got != userPath { |
| 60 | t.Errorf("got %q, want %q", got, userPath) |
| 61 | } |
| 62 | }) |
| 63 | |
| 64 | t.Run("returns first existing candidate", func(t *testing.T) { |
| 65 | candidates := []string{first, second, third} |
| 66 | got := pathOrDefaultWithCandidates("", candidates) |
| 67 | is.Equal(t, got, first) |
| 68 | }) |
| 69 | |
| 70 | t.Run("returns empty when nothing exists", func(t *testing.T) { |
| 71 | candidates := []string{} |
| 72 | got := pathOrDefaultWithCandidates("", candidates) |
| 73 | if got != "" { |
| 74 | t.Errorf("got %q, want empty", got) |
| 75 | } |
| 76 | }) |
| 77 | } |
| 78 | |
| 79 | func candidateFile(t *testing.T, name string) string { |
| 80 | t.Helper() |
| 81 | out := filepath.Join(t.TempDir(), name) |
| 82 | _ = os.WriteFile(out, []byte("test"), 0o644) |
| 83 | return out |
| 84 | } |