...

Source file src/github.com/imdario/mergo/merge_test.go

Documentation: github.com/imdario/mergo

     1  package mergo_test
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  
     7  	"github.com/imdario/mergo"
     8  )
     9  
    10  type transformer struct {
    11  	m map[reflect.Type]func(dst, src reflect.Value) error
    12  }
    13  
    14  func (s *transformer) Transformer(t reflect.Type) func(dst, src reflect.Value) error {
    15  	if fn, ok := s.m[t]; ok {
    16  		return fn
    17  	}
    18  	return nil
    19  }
    20  
    21  type foo struct {
    22  	Bar *bar
    23  	s   string
    24  }
    25  
    26  type bar struct {
    27  	s map[string]string
    28  	i int
    29  }
    30  
    31  func TestMergeWithTransformerNilStruct(t *testing.T) {
    32  	a := foo{s: "foo"}
    33  	b := foo{Bar: &bar{i: 2, s: map[string]string{"foo": "bar"}}}
    34  
    35  	if err := mergo.Merge(&a, &b, mergo.WithOverride, mergo.WithTransformers(&transformer{
    36  		m: map[reflect.Type]func(dst, src reflect.Value) error{
    37  			reflect.TypeOf(&bar{}): func(dst, src reflect.Value) error {
    38  				// Do sthg with Elem
    39  				t.Log(dst.Elem().FieldByName("i"))
    40  				t.Log(src.Elem())
    41  				return nil
    42  			},
    43  		},
    44  	})); err != nil {
    45  		t.Error(err)
    46  	}
    47  
    48  	if a.s != "foo" {
    49  		t.Errorf("b not merged in properly: a.s.Value(%s) != expected(%s)", a.s, "foo")
    50  	}
    51  
    52  	if a.Bar == nil {
    53  		t.Errorf("b not merged in properly: a.Bar shouldn't be nil")
    54  	}
    55  }
    56  
    57  func TestMergeNonPointer(t *testing.T) {
    58  	dst := bar{
    59  		i: 1,
    60  	}
    61  	src := bar{
    62  		i: 2,
    63  		s: map[string]string{
    64  			"a": "1",
    65  		},
    66  	}
    67  	want := mergo.ErrNonPointerArgument
    68  
    69  	if got := mergo.Merge(dst, src); got != want {
    70  		t.Errorf("want: %s, got: %s", want, got)
    71  	}
    72  }
    73  
    74  func TestMapNonPointer(t *testing.T) {
    75  	dst := make(map[string]bar)
    76  	src := map[string]bar{
    77  		"a": {
    78  			i: 2,
    79  			s: map[string]string{
    80  				"a": "1",
    81  			},
    82  		},
    83  	}
    84  	want := mergo.ErrNonPointerArgument
    85  	if got := mergo.Merge(dst, src); got != want {
    86  		t.Errorf("want: %s, got: %s", want, got)
    87  	}
    88  }
    89  

View as plain text