package config import ( "os" "path/filepath" "testing" ) func unsetEnv(t *testing.T, key string) { t.Helper() os.Unsetenv(key) t.Cleanup(func() { os.Unsetenv(key) }) } func TestLoadDotEnvLoadsValues(t *testing.T) { const key = "WIKIJS_TEST_DOTENV_LOAD" unsetEnv(t, key) path := filepath.Join(t.TempDir(), ".env") body := "# comment\n\nWIKIJS_TEST_DOTENV_LOAD=\"hello world\"\n" if err := os.WriteFile(path, []byte(body), 0o600); err != nil { t.Fatalf("write env file: %v", err) } t.Setenv("ENV_FILE", path) if err := LoadDotEnv(); err != nil { t.Fatalf("LoadDotEnv() error = %v", err) } if got, want := os.Getenv(key), "hello world"; got != want { t.Errorf("%s = %q, want %q", key, got, want) } } func TestLoadEnvFileExplicit(t *testing.T) { const key = "WIKIJS_TEST_ENVFILE_EXPLICIT" unsetEnv(t, key) path := filepath.Join(t.TempDir(), "custom.env") if err := os.WriteFile(path, []byte(key+"=value\n"), 0o600); err != nil { t.Fatalf("write env file: %v", err) } if err := LoadEnvFile(path); err != nil { t.Fatalf("LoadEnvFile() error = %v", err) } if got, want := os.Getenv(key), "value"; got != want { t.Errorf("%s = %q, want %q", key, got, want) } } func TestLoadEnvFileEmptyPath(t *testing.T) { if err := LoadEnvFile(" "); err == nil { t.Fatal("LoadEnvFile() error = nil, want error") } } func TestLoadDotEnvDoesNotOverrideProcessEnv(t *testing.T) { const key = "WIKIJS_TEST_DOTENV_OVERRIDE" path := filepath.Join(t.TempDir(), ".env") if err := os.WriteFile(path, []byte(key+"=from-file\n"), 0o600); err != nil { t.Fatalf("write env file: %v", err) } t.Setenv("ENV_FILE", path) t.Setenv(key, "from-process") if err := LoadDotEnv(); err != nil { t.Fatalf("LoadDotEnv() error = %v", err) } if got, want := os.Getenv(key), "from-process"; got != want { t.Errorf("%s = %q, want %q", key, got, want) } } func TestLoadDotEnvMissingDefaultIsIgnored(t *testing.T) { t.Chdir(t.TempDir()) t.Setenv("ENV_FILE", "") if err := LoadDotEnv(); err != nil { t.Fatalf("LoadDotEnv() error = %v", err) } } func TestLoadDotEnvMissingExplicitFileFails(t *testing.T) { t.Setenv("ENV_FILE", filepath.Join(t.TempDir(), "does-not-exist.env")) if err := LoadDotEnv(); err == nil { t.Fatal("LoadDotEnv() error = nil, want error") } }