package config import ( "os" "path/filepath" "testing" ) func TestLoadDotEnv(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, ".env") content := `# full-line comment PLAIN=hello INLINE=value # trailing comment QUOTED="quoted # not a comment" SINGLE='single quoted' export EXPORTED=yes EMPTY= SPACED = padded value ` if err := os.WriteFile(path, []byte(content), 0o600); err != nil { t.Fatal(err) } t.Setenv("PLAIN", "preexisting") // real env must win for _, k := range []string{"INLINE", "QUOTED", "SINGLE", "EXPORTED", "EMPTY", "SPACED"} { os.Unsetenv(k) t.Cleanup(func() { os.Unsetenv(k) }) } if err := LoadDotEnv(path); err != nil { t.Fatalf("LoadDotEnv: %v", err) } want := map[string]string{ "PLAIN": "preexisting", "INLINE": "value", "QUOTED": "quoted # not a comment", "SINGLE": "single quoted", "EXPORTED": "yes", "EMPTY": "", "SPACED": "padded value", } for k, v := range want { if got := os.Getenv(k); got != v { t.Errorf("%s = %q, want %q", k, got, v) } } } func TestLoadDotEnvMissingFileIsOK(t *testing.T) { if err := LoadDotEnv(filepath.Join(t.TempDir(), "absent")); err != nil { t.Fatalf("missing file should not error, got %v", err) } } func TestLoadDotEnvMalformed(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, ".env") if err := os.WriteFile(path, []byte("NOT A KV LINE\n"), 0o600); err != nil { t.Fatal(err) } if err := LoadDotEnv(path); err == nil { t.Fatal("want error for malformed line") } }