From 6a7381aa5ad1775f416567c555ba73cd327b6462 Mon Sep 17 00:00:00 2001 From: Deluan Date: Sat, 29 Nov 2025 11:44:24 -0500 Subject: [PATCH] test: prevent environment variables from overriding config file values in tests Added a loadEnvVars parameter to InitConfig to control whether environment variables should be loaded via viper.AutomaticEnv(). In tests, environment variables (like ND_MUSICFOLDER) were overriding values from config test files, causing tests to fail when these variables were set in the developer's environment. Now tests can pass loadEnvVars=false to isolate from the environment while production code continues to use loadEnvVars=true. Signed-off-by: Deluan --- cmd/root.go | 2 +- conf/configuration.go | 12 +++++++----- conf/configuration_test.go | 2 +- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 9618b16e..4a1305ca 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -346,7 +346,7 @@ func startPluginManager(ctx context.Context) func() error { // TODO: Implement some struct tags to map flags to viper func init() { cobra.OnInitialize(func() { - conf.InitConfig(cfgFile) + conf.InitConfig(cfgFile, true) }) rootCmd.PersistentFlags().StringVarP(&cfgFile, "configfile", "c", "", `config file (default "./navidrome.toml")`) diff --git a/conf/configuration.go b/conf/configuration.go index cca19945..f6b1c4cb 100644 --- a/conf/configuration.go +++ b/conf/configuration.go @@ -617,7 +617,7 @@ func init() { setViperDefaults() } -func InitConfig(cfgFile string) { +func InitConfig(cfgFile string, loadEnvVars bool) { codecRegistry := viper.NewCodecRegistry() _ = codecRegistry.RegisterCodec("ini", ini.Codec{ LoadOptions: ini.LoadOptions{ @@ -638,10 +638,12 @@ func InitConfig(cfgFile string) { } _ = viper.BindEnv("port") - viper.SetEnvPrefix("ND") - replacer := strings.NewReplacer(".", "_") - viper.SetEnvKeyReplacer(replacer) - viper.AutomaticEnv() + if loadEnvVars { + viper.SetEnvPrefix("ND") + replacer := strings.NewReplacer(".", "_") + viper.SetEnvKeyReplacer(replacer) + viper.AutomaticEnv() + } err := viper.ReadInConfig() if viper.ConfigFileUsed() != "" && err != nil { diff --git a/conf/configuration_test.go b/conf/configuration_test.go index 88454d20..15d12795 100644 --- a/conf/configuration_test.go +++ b/conf/configuration_test.go @@ -31,7 +31,7 @@ var _ = Describe("Configuration", func() { filename := filepath.Join("testdata", "cfg."+format) // Initialize config with the test file - conf.InitConfig(filename) + conf.InitConfig(filename, false) // Load the configuration (with noConfigDump=true) conf.Load(true)