From 42406af56710fc34a8539e6688452bb7f9ea1a58 Mon Sep 17 00:00:00 2001 From: Albert Vaca Cintora Date: Tue, 19 Apr 2022 21:19:35 +0200 Subject: [PATCH] Make AllSettings include set-but-empty keys --- viper.go | 4 ++-- viper_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/viper.go b/viper.go index 82d415a..df6dbef 100644 --- a/viper.go +++ b/viper.go @@ -1825,8 +1825,8 @@ func (v *Viper) AllSettings() map[string]interface{} { for _, k := range v.AllKeys() { value := v.Get(k) if value == nil { - // should not happen, since AllKeys() returns only keys holding a value, - // check just in case anything changes + // Key set but empty, include it in the output as a null value + m[k] = nil continue } diff --git a/viper_test.go b/viper_test.go index 21efc4b..e37aa6e 100644 --- a/viper_test.go +++ b/viper_test.go @@ -1818,3 +1818,33 @@ func TestKnownKeys(t *testing.T) { t.Error("SetKnown didn't mark key as known") } } + +func TestEmptySection(t *testing.T) { + + var yamlWithEnvVars = ` +key: + subkey: +another_key: +` + + v := New() + initConfig(v, "yaml", yamlWithEnvVars) + v.SetKnown("is_known") + v.SetDefault("has_default", true) + + // AllKeys includes empty keys + keys := v.AllKeys() + assert.NotContains(t, keys, "key") // Only empty leaf nodes are returned + assert.Contains(t, keys, "key.subkey") + assert.Contains(t, keys, "another_key") + assert.NotContains(t, keys, "is_known") + assert.Contains(t, keys, "has_default") + + // AllSettings includes empty keys + vars := v.AllSettings() + assert.NotContains(t, vars, "key") // Only empty leaf nodes are returned + assert.Contains(t, vars, "key.subkey") + assert.Contains(t, vars, "another_key") + assert.NotContains(t, vars, "is_known") + assert.Contains(t, vars, "has_default") +}