MCPcopy
hub / github.com/spf13/viper / TestUnmarshalWithDefaultDecodeHook

Function TestUnmarshalWithDefaultDecodeHook

viper_test.go:897–930  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

895}
896
897func TestUnmarshalWithDefaultDecodeHook(t *testing.T) {
898 opt := mapstructure.ComposeDecodeHookFunc(
899 mapstructure.StringToTimeDurationHookFunc(),
900 mapstructure.StringToSliceHookFunc(","),
901 // Custom Decode Hook Function
902 func(rf reflect.Kind, rt reflect.Kind, data any) (any, error) {
903 if rf != reflect.String || rt != reflect.Map {
904 return data, nil
905 }
906 m := map[string]string{}
907 raw := data.(string)
908 if raw == "" {
909 return m, nil
910 }
911 err := json.Unmarshal([]byte(raw), &m)
912 return m, err
913 },
914 )
915
916 v := NewWithOptions(WithDecodeHook(opt))
917 v.Set("credentials", "{\"foo\":\"bar\"}")
918
919 type config struct {
920 Credentials map[string]string
921 }
922
923 var C config
924
925 require.NoError(t, v.Unmarshal(&C), "unable to decode into struct")
926
927 assert.Equal(t, &config{
928 Credentials: map[string]string{"foo": "bar"},
929 }, &C)
930}
931
932func TestUnmarshalWithDecoderOptions(t *testing.T) {
933 v := New()

Callers

nothing calls this directly

Calls 4

NewWithOptionsFunction · 0.85
WithDecodeHookFunction · 0.85
UnmarshalMethod · 0.80
SetMethod · 0.45

Tested by

no test coverage detected