From a37bbb84b7a9ba0cd347bbe1e3612cc3e7b7585b Mon Sep 17 00:00:00 2001 From: Denis Manente Date: Tue, 20 Oct 2020 19:24:14 +0200 Subject: [PATCH] provide test case for #167 --- issue170_test.go | 64 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 issue170_test.go diff --git a/issue170_test.go b/issue170_test.go new file mode 100644 index 0000000..718ba8c --- /dev/null +++ b/issue170_test.go @@ -0,0 +1,64 @@ +package mergo_test + +import ( + "fmt" + "reflect" + "testing" + + "github.com/imdario/mergo" +) + +// This test has been stripped to minimally reproduce the core issue of #170. Consider the playground link for an in-depth analysis. + +type Issue170A struct{} + +type Issue170InMap struct { + As []*Issue170A +} + +type Issue170ValueMap struct { + InMap map[string]Issue170InMap +} + +type Issue170Transformer struct{} + +func (t Issue170Transformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { + switch typ { + case reflect.TypeOf([]*Issue170A{}): + return t.transform + } + + return nil +} + +func (t Issue170Transformer) transform(dst, src reflect.Value) error { + if !dst.CanSet() { + return fmt.Errorf("dst.CanSet() is false, so we're unable to Set() the new value later") + } + + dstReal := dst.Interface().([]*Issue170A) + dst.Set(reflect.ValueOf(dstReal)) + + return nil +} + +var Issue170TestData = []struct { + Dst Issue170ValueMap + Src Issue170ValueMap +}{ + { + // Each As must have at least an element + Dst: Issue170ValueMap{InMap: map[string]Issue170InMap{"foo": {As: []*Issue170A{{}}}}}, + Src: Issue170ValueMap{InMap: map[string]Issue170InMap{"foo": {As: []*Issue170A{{}}}}}, + }, +} + +func TestIssue170MapWithValue(t *testing.T) { + // And additionally should not panic with every test case + for _, data := range Issue170TestData { + err := mergo.Merge(&data.Dst, data.Src, mergo.WithTransformers(Issue170Transformer{})) + if err != nil { + t.Errorf("Error while merging %s", err) + } + } +}