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