ebf246beb0
- dotenv_load: parser .env con no-sobreescritura y soporte de comillas - env_require: os.Getenv con error descriptivo fail-fast - env_require_all: verifica multiples vars y lista todas las faltantes - config_from_env: reflection sobre struct tags env/default/required/secret, 5 tipos soportados - config_from_file: JSON via stdlib, YAML stub con not-implemented - 25 tests unitarios, todos PASS Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
package infra
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestConfigFromFile(t *testing.T) {
|
|
t.Run("carga JSON valido en struct", func(t *testing.T) {
|
|
type Cfg struct {
|
|
Host string `json:"host"`
|
|
Port int `json:"port"`
|
|
}
|
|
content := `{"host":"testhost","port":5432}`
|
|
dir := t.TempDir()
|
|
p := filepath.Join(dir, "config.json")
|
|
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
var c Cfg
|
|
if err := ConfigFromFile(p, &c); err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if c.Host != "testhost" || c.Port != 5432 {
|
|
t.Errorf("unexpected: %+v", c)
|
|
}
|
|
})
|
|
|
|
t.Run("JSON invalido retorna error", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
p := filepath.Join(dir, "bad.json")
|
|
os.WriteFile(p, []byte("{not valid json}"), 0o600)
|
|
|
|
var target map[string]any
|
|
err := ConfigFromFile(p, &target)
|
|
if err == nil {
|
|
t.Error("expected error for invalid JSON")
|
|
}
|
|
})
|
|
|
|
t.Run("archivo inexistente retorna error", func(t *testing.T) {
|
|
var target map[string]any
|
|
err := ConfigFromFile("/nonexistent/config.json", &target)
|
|
if err == nil {
|
|
t.Error("expected error for missing file")
|
|
}
|
|
})
|
|
|
|
t.Run("extension YAML retorna not implemented", func(t *testing.T) {
|
|
var target map[string]any
|
|
err := ConfigFromFile("config.yaml", &target)
|
|
if err == nil {
|
|
t.Error("expected not-implemented error for YAML")
|
|
}
|
|
})
|
|
|
|
t.Run("extension desconocida retorna error", func(t *testing.T) {
|
|
var target map[string]any
|
|
err := ConfigFromFile("config.toml", &target)
|
|
if err == nil {
|
|
t.Error("expected error for unsupported extension")
|
|
}
|
|
})
|
|
}
|