diff --git a/cli/config/config.go b/cli/config/config.go index 5ea2d92693..952f6e71f4 100644 --- a/cli/config/config.go +++ b/cli/config/config.go @@ -35,6 +35,13 @@ var ( configDir string ) +// resetConfigDir is used in testing to reset the "configDir" package variable +// and its sync.Once to force re-lookup between tests. +func resetConfigDir() { + configDir = "" + initConfigDir = new(sync.Once) +} + // Dir returns the directory the configuration file is stored in func Dir() string { initConfigDir.Do(func() { @@ -53,6 +60,8 @@ func ContextStoreDir() string { // SetDir sets the directory the configuration file is stored in func SetDir(dir string) { + // trigger the sync.Once to synchronise with Dir() + initConfigDir.Do(func() {}) configDir = filepath.Clean(dir) } diff --git a/cli/config/config_test.go b/cli/config/config_test.go index 33c9b83177..0efd675b38 100644 --- a/cli/config/config_test.go +++ b/cli/config/config_test.go @@ -382,3 +382,12 @@ func TestConfigPath(t *testing.T) { SetDir(oldDir) } + +// TestSetDir verifies that Dir() does not overwrite the value set through +// SetDir() if it has not been run before. +func TestSetDir(t *testing.T) { + const expected = "my_config_dir" + resetConfigDir() + SetDir(expected) + assert.Check(t, is.Equal(Dir(), expected)) +}