49 lines
1.6 KiB
Go
49 lines
1.6 KiB
Go
package configx
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestLoadYAMLExpandsBraceEnvOnly(t *testing.T) {
|
|
t.Setenv("CONFIGX_TEST_SECRET", "secret-value")
|
|
path := filepath.Join(t.TempDir(), "config.yaml")
|
|
if err := os.WriteFile(path, []byte("secret: \"${CONFIGX_TEST_SECRET}\"\nliteral: \"price$100\"\nmissing: \"${CONFIGX_TEST_MISSING}\"\n"), 0o600); err != nil {
|
|
t.Fatalf("write config failed: %v", err)
|
|
}
|
|
var cfg struct {
|
|
Secret string `yaml:"secret"`
|
|
Literal string `yaml:"literal"`
|
|
Missing string `yaml:"missing"`
|
|
}
|
|
if err := LoadYAMLWithEnv(path, &cfg); err != nil {
|
|
t.Fatalf("LoadYAMLWithEnv failed: %v", err)
|
|
}
|
|
if cfg.Secret != "secret-value" || cfg.Literal != "price$100" || cfg.Missing != "" {
|
|
t.Fatalf("env expansion mismatch: %+v", cfg)
|
|
}
|
|
}
|
|
|
|
func TestLoadDotEnvFileDoesNotOverrideRuntimeEnv(t *testing.T) {
|
|
t.Setenv("CONFIGX_DOTENV_EXISTING", "runtime")
|
|
t.Cleanup(func() {
|
|
_ = os.Unsetenv("CONFIGX_DOTENV_NEW")
|
|
_ = os.Unsetenv("CONFIGX_DOTENV_EXPORTED")
|
|
})
|
|
path := filepath.Join(t.TempDir(), ".env")
|
|
content := []byte("CONFIGX_DOTENV_EXISTING=file\nCONFIGX_DOTENV_NEW=\"file-value\"\n# comment\nexport CONFIGX_DOTENV_EXPORTED='exported-value'\n")
|
|
if err := os.WriteFile(path, content, 0o600); err != nil {
|
|
t.Fatalf("write .env failed: %v", err)
|
|
}
|
|
if err := LoadDotEnvFile(path); err != nil {
|
|
t.Fatalf("LoadDotEnvFile failed: %v", err)
|
|
}
|
|
if os.Getenv("CONFIGX_DOTENV_EXISTING") != "runtime" {
|
|
t.Fatalf(".env must not override runtime env")
|
|
}
|
|
if os.Getenv("CONFIGX_DOTENV_NEW") != "file-value" || os.Getenv("CONFIGX_DOTENV_EXPORTED") != "exported-value" {
|
|
t.Fatalf(".env variables were not loaded")
|
|
}
|
|
}
|