Files

90 lines
2.2 KiB
Go

package config
import (
"maps"
"os"
"path/filepath"
"testing"
)
func TestEnvFilePath(t *testing.T) {
if got := EnvFilePath("/home/sam/.config/archie/config.toml"); got != "/home/sam/.config/archie/env" {
t.Errorf("EnvFilePath = %q", got)
}
}
func TestDefaultConfigPath(t *testing.T) {
tests := []struct {
name string
xdgConfigHome string
instance string
want string
}{
{name: "defaults", want: filepath.Join(homeConfigDir(t), "archie", "config.toml")},
{name: "xdg config home", xdgConfigHome: "/xdg", want: filepath.Join("/xdg", "archie", "config.toml")},
{name: "named instance", xdgConfigHome: "/xdg", instance: "archie-dev", want: filepath.Join("/xdg", "archie-dev", "config.toml")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", tt.xdgConfigHome)
t.Setenv("ARCHIE_INSTANCE", tt.instance)
if got := DefaultConfigPath(); got != tt.want {
t.Errorf("DefaultConfigPath = %q, want %q", got, tt.want)
}
})
}
}
func homeConfigDir(t *testing.T) string {
t.Helper()
home, err := os.UserHomeDir()
if err != nil {
t.Fatal(err)
}
return filepath.Join(home, ".config")
}
func TestParseEnvFile(t *testing.T) {
data := `# archie secrets
PGPASSWORD='s3cret'
GITEA_TOKEN='a'\''b'
PLAIN=unquoted
DOUBLE="double-quoted"
no-equals-sign-line
=orphan
`
got := ParseEnvFile([]byte(data))
want := map[string]string{
"PGPASSWORD": "s3cret",
"GITEA_TOKEN": "a'b",
"PLAIN": "unquoted",
"DOUBLE": "double-quoted",
}
if !maps.Equal(got, want) {
t.Errorf("ParseEnvFile = %v, want %v", got, want)
}
}
func TestLoadEnvFile(t *testing.T) {
t.Run("missing file is no entries and no error", func(t *testing.T) {
entries, err := LoadEnvFile(filepath.Join(t.TempDir(), "env"))
if err != nil || entries != nil {
t.Errorf("LoadEnvFile = %v, %v, want nil, nil", entries, err)
}
})
t.Run("existing file parses", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "env")
if err := os.WriteFile(path, []byte("PGPASSWORD='pw'\n"), 0o600); err != nil {
t.Fatal(err)
}
entries, err := LoadEnvFile(path)
if err != nil {
t.Fatal(err)
}
if entries["PGPASSWORD"] != "pw" {
t.Errorf("entries = %v", entries)
}
})
}