Skip to content

Commit

Permalink
Fix failing Cobra/Viper tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Djadih committed Dec 19, 2024
1 parent ea2f14e commit 8f2f12a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
2 changes: 2 additions & 0 deletions cmd/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package utils
import (
"errors"
"io/fs"
"strings"

"github.com/spf13/viper"

Expand Down Expand Up @@ -40,4 +41,5 @@ func InitConfig() {
log.Global.Infof("Loading config from environment variables with prefix: '%s_'", constants.ENV_PREFIX)
viper.SetEnvPrefix(constants.ENV_PREFIX)
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) // Replace hyphens with underscores for env variables
}
15 changes: 9 additions & 6 deletions cmd/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils

import (
"os"
"strings"
"testing"

"github.com/dominant-strategies/go-quai/common/constants"
Expand All @@ -21,8 +22,8 @@ func testXDGConfigLoading(t *testing.T) {
defer tempFile.Close()
defer os.RemoveAll(mockConfigPath)

// write 'LOG_LEVEL=debug' config to mock config.yaml file
_, err := tempFile.WriteString(LogLevelFlag.Name + " : " + "debug\n")
// write 'log-level = debug' config to mock config.yaml file
_, err := tempFile.WriteString(LogLevelFlag.Name + " = " + "\"debug\"\n")
require.NoError(t, err)

// Set config path to the temporary config directory
Expand All @@ -38,19 +39,21 @@ func testXDGConfigLoading(t *testing.T) {
// the loading of the environment variable and the loading of the cobra flag.
// It verifies the expected order of precedence of config loading.
func TestCobraFlagConfigLoading(t *testing.T) {
t.Skip("Todo: fix failing test")
// Clear viper instance to simulate a fresh start
viper.Reset()
viper.AutomaticEnv()
viper.SetEnvPrefix(constants.ENV_PREFIX)
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) // Replace hyphens with underscores

// Test loading config from XDG config home
testXDGConfigLoading(t)
assert.Equal(t, "debug", viper.GetString(LogLevelFlag.Name))

// Test loading config from environment variable
err := os.Setenv(constants.ENV_PREFIX+"_"+"LOG-LEVEL", "error")
defer os.Unsetenv(constants.ENV_PREFIX + "_" + "LOG-LEVEL")
err := os.Setenv(constants.ENV_PREFIX+"_"+"LOG_LEVEL", "error")
defer os.Unsetenv(constants.ENV_PREFIX + "_" + "LOG_LEVEL")
require.NoError(t, err)
assert.Equal(t, "error", viper.GetString(LogLevelFlag.Name))
assert.Equal(t, "error", viper.GetString("LOG_LEVEL"))

// Test loading config from cobra flag
rootCmd := &cobra.Command{}
Expand Down

0 comments on commit 8f2f12a

Please sign in to comment.