-
-
Notifications
You must be signed in to change notification settings - Fork 271
/
issue52_test.go
113 lines (91 loc) · 2.38 KB
/
issue52_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package mergo_test
import (
"reflect"
"testing"
"time"
"dario.cat/mergo"
)
type structWithTime struct {
Birth time.Time
}
type timeTransfomer struct {
overwrite bool
}
func (t timeTransfomer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
if typ == reflect.TypeOf(time.Time{}) {
return func(dst, src reflect.Value) error {
if dst.CanSet() {
if t.overwrite {
isZero := src.MethodByName("IsZero")
result := isZero.Call([]reflect.Value{})
if !result[0].Bool() {
dst.Set(src)
}
} else {
isZero := dst.MethodByName("IsZero")
result := isZero.Call([]reflect.Value{})
if result[0].Bool() {
dst.Set(src)
}
}
}
return nil
}
}
return nil
}
func TestOverwriteZeroSrcTime(t *testing.T) {
now := time.Now()
dst := structWithTime{now}
src := structWithTime{}
if err := mergo.MergeWithOverwrite(&dst, src); err != nil {
t.FailNow()
}
if !dst.Birth.IsZero() {
t.Errorf("dst should have been overwritten: dst.Birth(%v) != now(%v)", dst.Birth, now)
}
}
func TestOverwriteZeroSrcTimeWithTransformer(t *testing.T) {
now := time.Now()
dst := structWithTime{now}
src := structWithTime{}
if err := mergo.MergeWithOverwrite(&dst, src, mergo.WithTransformers(timeTransfomer{true})); err != nil {
t.FailNow()
}
if dst.Birth.IsZero() {
t.Errorf("dst should not have been overwritten: dst.Birth(%v) != now(%v)", dst.Birth, now)
}
}
func TestOverwriteZeroDstTime(t *testing.T) {
now := time.Now()
dst := structWithTime{}
src := structWithTime{now}
if err := mergo.MergeWithOverwrite(&dst, src); err != nil {
t.FailNow()
}
if dst.Birth.IsZero() {
t.Errorf("dst should have been overwritten: dst.Birth(%v) != zero(%v)", dst.Birth, time.Time{})
}
}
func TestZeroDstTime(t *testing.T) {
now := time.Now()
dst := structWithTime{}
src := structWithTime{now}
if err := mergo.Merge(&dst, src); err != nil {
t.FailNow()
}
if !dst.Birth.IsZero() {
t.Errorf("dst should not have been overwritten: dst.Birth(%v) != zero(%v)", dst.Birth, time.Time{})
}
}
func TestZeroDstTimeWithTransformer(t *testing.T) {
now := time.Now()
dst := structWithTime{}
src := structWithTime{now}
if err := mergo.Merge(&dst, src, mergo.WithTransformers(timeTransfomer{})); err != nil {
t.FailNow()
}
if dst.Birth.IsZero() {
t.Errorf("dst should have been overwritten: dst.Birth(%v) != now(%v)", dst.Birth, now)
}
}