dotenv_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package config
  2. import (
  3. "os"
  4. "path/filepath"
  5. "testing"
  6. )
  7. func unsetEnv(t *testing.T, key string) {
  8. t.Helper()
  9. os.Unsetenv(key)
  10. t.Cleanup(func() { os.Unsetenv(key) })
  11. }
  12. func TestLoadDotEnvLoadsValues(t *testing.T) {
  13. const key = "WIKIJS_TEST_DOTENV_LOAD"
  14. unsetEnv(t, key)
  15. path := filepath.Join(t.TempDir(), ".env")
  16. body := "# comment\n\nWIKIJS_TEST_DOTENV_LOAD=\"hello world\"\n"
  17. if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
  18. t.Fatalf("write env file: %v", err)
  19. }
  20. t.Setenv("ENV_FILE", path)
  21. if err := LoadDotEnv(); err != nil {
  22. t.Fatalf("LoadDotEnv() error = %v", err)
  23. }
  24. if got, want := os.Getenv(key), "hello world"; got != want {
  25. t.Errorf("%s = %q, want %q", key, got, want)
  26. }
  27. }
  28. func TestLoadEnvFileExplicit(t *testing.T) {
  29. const key = "WIKIJS_TEST_ENVFILE_EXPLICIT"
  30. unsetEnv(t, key)
  31. path := filepath.Join(t.TempDir(), "custom.env")
  32. if err := os.WriteFile(path, []byte(key+"=value\n"), 0o600); err != nil {
  33. t.Fatalf("write env file: %v", err)
  34. }
  35. if err := LoadEnvFile(path); err != nil {
  36. t.Fatalf("LoadEnvFile() error = %v", err)
  37. }
  38. if got, want := os.Getenv(key), "value"; got != want {
  39. t.Errorf("%s = %q, want %q", key, got, want)
  40. }
  41. }
  42. func TestLoadEnvFileEmptyPath(t *testing.T) {
  43. if err := LoadEnvFile(" "); err == nil {
  44. t.Fatal("LoadEnvFile() error = nil, want error")
  45. }
  46. }
  47. func TestLoadDotEnvDoesNotOverrideProcessEnv(t *testing.T) {
  48. const key = "WIKIJS_TEST_DOTENV_OVERRIDE"
  49. path := filepath.Join(t.TempDir(), ".env")
  50. if err := os.WriteFile(path, []byte(key+"=from-file\n"), 0o600); err != nil {
  51. t.Fatalf("write env file: %v", err)
  52. }
  53. t.Setenv("ENV_FILE", path)
  54. t.Setenv(key, "from-process")
  55. if err := LoadDotEnv(); err != nil {
  56. t.Fatalf("LoadDotEnv() error = %v", err)
  57. }
  58. if got, want := os.Getenv(key), "from-process"; got != want {
  59. t.Errorf("%s = %q, want %q", key, got, want)
  60. }
  61. }
  62. func TestLoadDotEnvMissingDefaultIsIgnored(t *testing.T) {
  63. t.Chdir(t.TempDir())
  64. t.Setenv("ENV_FILE", "")
  65. if err := LoadDotEnv(); err != nil {
  66. t.Fatalf("LoadDotEnv() error = %v", err)
  67. }
  68. }
  69. func TestLoadDotEnvMissingExplicitFileFails(t *testing.T) {
  70. t.Setenv("ENV_FILE", filepath.Join(t.TempDir(), "does-not-exist.env"))
  71. if err := LoadDotEnv(); err == nil {
  72. t.Fatal("LoadDotEnv() error = nil, want error")
  73. }
  74. }