fix: merge missing struct keys inside UnmarshalExact

This commit is contained in:
Filip Krakowski 2023-12-06 22:20:47 +01:00 committed by Márk Sági-Kazár
parent f5fcb4a104
commit fb6eb1e8e9
2 changed files with 34 additions and 1 deletions

View file

@ -1179,7 +1179,14 @@ func (v *Viper) UnmarshalExact(rawVal any, opts ...DecoderConfigOption) error {
config := defaultDecoderConfig(rawVal, opts...)
config.ErrorUnused = true
return decode(v.AllSettings(), config)
// TODO: make this optional?
structKeys, err := v.decodeStructKeys(rawVal, opts...)
if err != nil {
return err
}
// TODO: struct keys should be enough?
return decode(v.getSettings(append(v.AllKeys(), structKeys...)), config)
}
// BindPFlags binds a full flag set to the configuration, using each flag's long

View file

@ -1052,6 +1052,32 @@ func TestUnmarshalWithAutomaticEnv(t *testing.T) {
assert.Error(t, err, "expected viper.Unmarshal to return error due to unset field 'FLAG'")
})
t.Run("Exact", func(t *testing.T) {
var config Configuration
v.Set("port", 1234)
if err := v.UnmarshalExact(&config); err != nil {
t.Fatalf("unable to decode into struct, %v", err)
}
assert.Equal(
t,
Configuration{
Name: "Steve",
Port: 1234,
Duration: time.Second + time.Millisecond,
Modes: []int{1, 2, 3},
Authentication: AuthConfig{
Secret: "42",
},
Storage: StorageConfig{
Size: 4096,
},
},
config,
)
})
}
func TestBindPFlags(t *testing.T) {