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

Commit 4ec29e7

Browse files
author
Pavel Ivanov
committed
new: test for calling DecodeHook when decoding map from struct
1 parent 3536a92 commit 4ec29e7

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
)
@@ -1915,6 +1916,50 @@ func TestWeakDecodeMetadata(t *testing.T) {
19151916
}
19161917
}
19171918

1919+
func TestDecodeStructToMap_DecodeHook(t *testing.T) {
1920+
t.Parallel()
1921+
1922+
input := struct {
1923+
Vstring string
1924+
Vint int
1925+
}{
1926+
"foo",
1927+
42,
1928+
}
1929+
1930+
decodeHook := func(f, t reflect.Type, v interface{}) (interface{}, error) {
1931+
if f.Kind() != reflect.Int {
1932+
return v, nil
1933+
}
1934+
val := strconv.FormatInt(int64(v.(int)), 10)
1935+
return val, nil
1936+
}
1937+
1938+
var result map[string]interface{}
1939+
config := &DecoderConfig{
1940+
DecodeHook: decodeHook,
1941+
Result: &result,
1942+
}
1943+
1944+
decoder, err := NewDecoder(config)
1945+
if err != nil {
1946+
t.Fatalf("err: %s", err)
1947+
}
1948+
1949+
err = decoder.Decode(input)
1950+
if err != nil {
1951+
t.Fatalf("got an err: %s", err)
1952+
}
1953+
1954+
expected := map[string]interface{}{
1955+
"Vstring": "foo",
1956+
"Vint": "42",
1957+
}
1958+
if !reflect.DeepEqual(result, expected) {
1959+
t.Errorf("Decode call result should be %#v, got %#v", expected, result)
1960+
}
1961+
}
1962+
19181963
func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) {
19191964
var result Slice
19201965
err := Decode(input, &result)

0 commit comments

Comments
 (0)