-
Notifications
You must be signed in to change notification settings - Fork 1
/
deepcopy_test.go
156 lines (139 loc) · 2.63 KB
/
deepcopy_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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package deepcopy
import (
"testing"
"github.com/stretchr/testify/assert"
)
type testCase struct {
need interface{}
got interface{}
}
// 最大深度
func Test_MaxDepth(t *testing.T) {
type depth struct {
First string
Data struct {
Result string
}
Err struct {
ErrMsg struct {
Message string
}
}
}
src := depth{}
src.First = "first"
src.Data.Result = "test"
src.Err.ErrMsg.Message = "good"
for _, tc := range []testCase{
func() testCase {
d := depth{}
err := Copy(&d, &src).MaxDepth(2).Do()
assert.NoError(t, err)
if err != nil {
return testCase{}
}
need := depth{}
need.First = "first"
need.Data.Result = "test"
return testCase{got: d, need: need}
}(),
func() testCase {
d := depth{}
Copy(&d, &src).MaxDepth(1).Do()
need := depth{}
need.First = "first"
return testCase{got: d, need: need}
}(),
func() testCase {
d := depth{}
Copy(&d, &src).MaxDepth(3).Do()
need := depth{}
need.First = "first"
need.Data.Result = "test"
need.Err.ErrMsg.Message = "good"
return testCase{got: d, need: need}
}(),
} {
assert.Equal(t, tc.need, tc.got)
}
}
// 测试设置tag的情况
func Test_TagName(t *testing.T) {
type tagName struct {
First string `copy:"first"`
Data struct {
Result string
}
}
src := tagName{}
src.First = "first"
src.Data.Result = "test"
for _, tc := range []testCase{
func() testCase {
d := tagName{}
Copy(&d, &src).RegisterTagName("copy").Do()
need := tagName{}
need.First = "first"
return testCase{got: d, need: need}
}(),
} {
assert.Equal(t, tc.need, tc.got)
}
}
// 下面的test case 确保不panic
func Test_Special(t *testing.T) {
for _, tc := range []testCase{
func() testCase {
// src有的字段, dst里面没有
type src struct {
Sex string
}
type dst struct {
ID string
}
d := dst{}
s := src{Sex: "m"}
Copy(&d, &s).Do()
return testCase{got: d, need: d}
}(),
func() testCase {
// 同样的字段不同数据类型,不拷贝
type src struct {
Sex string
}
type dst struct {
Sex int
}
d := dst{}
s := src{Sex: "m"}
Copy(&d, &s).Do()
return testCase{got: d, need: d}
}(),
func() testCase {
Copy(new(int), nil).Do()
return testCase{got: true, need: true}
}(),
} {
assert.Equal(t, tc.need, tc.got)
}
}
// 测试循环引用
/*
func Test_Cycle(t *testing.T) {
for _, e := range []error{
func() error {
type src2 struct {
P1 *src2
ID string
}
// p1指向自己,构造一个环
s := src2{}
s.P1 = &s
d := src2{}
return Copy(&d, &s).Do()
}(),
} {
assert.Error(t, e)
}
}
*/