Skip to content
This repository was archived by the owner on Jul 22, 2024. It is now read-only.

Commit 545fefd

Browse files
author
Pavel Ivanov
committed
new: test for calling DecodeHook when decoding map from struct
1 parent bf980b3 commit 545fefd

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

mapstructure_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"io"
66
"reflect"
77
"sort"
8+
"strconv"
89
"strings"
910
"testing"
1011
"time"
@@ -2732,6 +2733,50 @@ func TestDecoder_IgnoreUntaggedFields(t *testing.T) {
27322733
}
27332734
}
27342735

2736+
func TestDecodeStructToMap_DecodeHook(t *testing.T) {
2737+
t.Parallel()
2738+
2739+
input := struct {
2740+
Vstring string
2741+
Vint int
2742+
}{
2743+
"foo",
2744+
42,
2745+
}
2746+
2747+
decodeHook := func(f, t reflect.Type, v interface{}) (interface{}, error) {
2748+
if f.Kind() != reflect.Int {
2749+
return v, nil
2750+
}
2751+
val := strconv.FormatInt(int64(v.(int)), 10)
2752+
return val, nil
2753+
}
2754+
2755+
var result map[string]interface{}
2756+
config := &DecoderConfig{
2757+
DecodeHook: decodeHook,
2758+
Result: &result,
2759+
}
2760+
2761+
decoder, err := NewDecoder(config)
2762+
if err != nil {
2763+
t.Fatalf("err: %s", err)
2764+
}
2765+
2766+
err = decoder.Decode(input)
2767+
if err != nil {
2768+
t.Fatalf("got an err: %s", err)
2769+
}
2770+
2771+
expected := map[string]interface{}{
2772+
"Vstring": "foo",
2773+
"Vint": "42",
2774+
}
2775+
if !reflect.DeepEqual(result, expected) {
2776+
t.Errorf("Decode call result should be %#v, got %#v", expected, result)
2777+
}
2778+
}
2779+
27352780
func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) {
27362781
var result Slice
27372782
err := Decode(input, &result)

0 commit comments

Comments
 (0)