Debian Codegraph @

clone_common_test.go

raw
1 // Copyright 2019 Huan Du. All rights reserved.
2 // Licensed under the MIT license that can be found in the LICENSE file.
3
4 package clone
5
6 import (
7 "bytes"
8 "container/list"
9 "io"
10 "reflect"
11 "testing"
12 "unsafe"
13
14 "github.com/huandu/go-assert"
15 )
16
17 var testFuncMap = map[string]func(t *testing.T, allocator *Allocator){
18 "Basic Clone": testClone,
19 "Slowly linked list": testSlowlyLinkedList,
20 "Slowly cycle linked list": testSlowlyCycleLinkedList,
21 "Slowly fix invalid cycle pointers": testSlowlyFixInvalidCyclePointers,
22 "Slowly fix invalid linked pointers": testSlowlyFixInvalidLinkedPointers,
23 "Clone array": testCloneArray,
24 "Clone map": testCloneMap,
25 "Clone bytes buffer": testCloneBytesBuffer,
26 "Clone unexported fields": testCloneUnexportedFields,
27 "Clone unexported struct method": testCloneUnexportedStructMethod,
28 "Clone reflect type": testCloneReflectType,
29 }
30
31 type T struct {
32 Foo int
33 Bar map[string]interface{}
34 }
35
36 func testClone(t *testing.T, allocator *Allocator) {
37 arr := [4]string{"abc", "def", "ghi"}
38 ch := make(chan int, 2)
39 fn := func(int) {}
40 var it io.Writer = &bytes.Buffer{}
41 m := map[interface{}]string{
42 "abc": "efg",
43 123: "ghi",
44 }
45 slice := []string{"xyz", "opq"}
46 st := T{
47 Foo: 1234,
48 Bar: map[string]interface{}{
49 "abc": 123,
50 "def": "ghi",
51 },
52 }
53 ptr := &st
54 complex := []map[string][]*T{
55 {
56 "abc": {
57 {Foo: 456, Bar: map[string]interface{}{"abc": "def"}},
58 },
59 },
60 {
61 "def": {
62 {Foo: 987, Bar: map[string]interface{}{"abc": "def"}},
63 {Foo: 321, Bar: map[string]interface{}{"ghi": "xyz"}},
64 },
65 "ghi": {
66 {Foo: 654, Bar: map[string]interface{}{"def": "abc"}},
67 },
68 },
69 }
70 nested := func() interface{} {
71 var nested []map[string][]*T
72 var nestedPtr *T
73 var nestedIf interface{}
74 var nestedMap map[string]interface{}
75 nested = []map[string][]*T{
76 {
77 "abc": {
78 {Foo: 987, Bar: map[string]interface{}{"def": nil, "nil": nil}},
79 {Foo: 321, Bar: map[string]interface{}{"ghi": nil, "def": nil, "cba": nil}},
80 {Foo: 456},
81 nil,
82 },
83 },
84 }
85 nestedPtr = &T{
86 Foo: 654,
87 Bar: map[string]interface{}{
88 "xyz": nested,
89 "opq": nil,
90 },
91 }
92 nestedIf = map[string]interface{}{
93 "rst": nested,
94 }
95 nestedMap = map[string]interface{}{}
96
97 // Don't test it due to bug in Go.
98 // https://github.com/golang/go/issues/33907
99 //nestedMap["opq"] = nestedMap
100
101 nested[0]["abc"][0].Bar["def"] = nested
102 nested[0]["abc"][1].Bar["ghi"] = nestedPtr
103 nested[0]["abc"][1].Bar["def"] = nestedIf
104 nested[0]["abc"][1].Bar["cba"] = nested
105 nested[0]["abc"][2].Bar = nestedMap
106 nested[0]["abc"][3] = nestedPtr
107 nestedPtr.Bar["opq"] = nestedPtr
108 return nested
109 }()
110 var nilSlice []int
111 var nilChan chan bool
112 var nilPtr *float64
113 cases := []interface{}{
114 123, "abc", nil, true, testing.TB(nil),
115 arr, ch, fn, it, m, ptr, slice, st, nested,
116 complex, nilSlice, nilChan, nilPtr,
117 }
118
119 for _, c := range cases {
120 var v1, v2 interface{}
121
122 if reflect.DeepEqual(c, nested) {
123 // Clone doesn't work on nested data.
124 v1 = c
125 } else {
126 v1 = clone(allocator, c)
127 }
128
129 v2 = cloneSlowly(allocator, c)
130 deepEqual(t, c, v1)
131 deepEqual(t, c, v2)
132 }
133 }
134
135 func deepEqual(t *testing.T, expected, actual interface{}) {
136 a := assert.New(t)
137 a.Use(&expected, &actual)
138
139 val := reflect.ValueOf(actual)
140
141 // It's not possible to compare chan value.
142 if val.Kind() == reflect.Chan {
143 cval := reflect.ValueOf(expected)
144 a.Equal(cval.Type(), val.Type())
145 a.Equal(cval.Cap(), val.Cap())
146 return
147 }
148
149 if val.Kind() == reflect.Func {
150 // It's not possible to compare func value either.
151 cval := reflect.ValueOf(expected)
152 a.Assert(cval.Type() == val.Type())
153 return
154 }
155
156 a.Equal(actual, expected)
157 }
158
159 func testSlowlyLinkedList(t *testing.T, allocator *Allocator) {
160 a := assert.New(t)
161 l := list.New()
162 l.PushBack("v1")
163 l.PushBack("v2")
164 cloned := cloneSlowly(allocator, l).(*list.List)
165
166 a.Equal(l.Len(), cloned.Len())
167 a.Equal(l.Front().Value, cloned.Front().Value)
168 a.Equal(l.Back().Value, cloned.Back().Value)
169
170 // There must be only two elements in cloned.
171 a.Equal(cloned.Back(), cloned.Front().Next())
172 a.Equal(cloned.Back().Next(), nil)
173 }
174
175 type cycleLinkedList struct {
176 elems []*list.Element
177 elem *list.Element
178
179 list *list.List
180 }
181
182 func testSlowlyCycleLinkedList(t *testing.T, allocator *Allocator) {
183 a := assert.New(t)
184 l := list.New()
185 elem := l.PushBack("123")
186 cycle := &cycleLinkedList{
187 elems: []*list.Element{elem},
188 elem: elem,
189 list: l,
190 }
191 cloned := cloneSlowly(allocator, cycle).(*cycleLinkedList)
192
193 a.Equal(l.Len(), cloned.list.Len())
194 a.Equal(elem.Value, cloned.list.Front().Value)
195
196 // There must be only one element in cloned.
197 a.Equal(cloned.list.Front(), cloned.list.Back())
198 a.Equal(cloned.list.Front().Next(), nil)
199 a.Equal(cloned.list.Back().Next(), nil)
200 }
201
202 type cycleList struct {
203 root cycleElement
204 elem *cycleElement
205 }
206
207 type cycleElement struct {
208 next *cycleElement
209 list *cycleList
210 }
211
212 type cycleComplex struct {
213 ch chan bool
214 scalar int
215 scalarArray *[1]int
216 scalarSlice []string
217 scalarStruct *reflect.Value
218
219 _ []*cycleElement
220 _ map[*cycleElement]*cycleElement
221 _ interface{}
222
223 array [2]*cycleElement
224 slice []*cycleElement
225 iface1, iface2 interface{}
226 ptr1, ptr2 *cycleElement
227
228 scalarMap map[string]int
229 plainMap map[int]*cycleElement
230 simpleMap map[*cycleList]*cycleElement
231 complexMap map[*cycleElement]*cycleElement
232
233 pair cycleElementPair
234 pairValue interface{}
235
236 refSlice *[]*cycleElement
237 refComplexMap *map[*cycleElement]*cycleElement
238 }
239
240 type cycleElementPair struct {
241 elem1, elem2 *cycleElement
242 }
243
244 func makeCycleElement() *cycleElement {
245 list := &cycleList{}
246 elem := &cycleElement{
247 next: &list.root,
248 list: list,
249 }
250 list.root.next = elem
251 list.root.list = list
252 list.elem = elem
253 return &list.root
254 }
255
256 func (elem *cycleElement) validateCycle(t *testing.T) {
257 a := assert.New(t)
258
259 // elem is the &list.root.
260 a.Assert(elem == &elem.list.root)
261 a.Assert(elem.next == elem.list.elem)
262 a.Assert(elem.next.next == elem)
263 }
264
265 func testSlowlyFixInvalidCyclePointers(t *testing.T, allocator *Allocator) {
266 var scalarArray [1]int
267 scalarStruct := reflect.ValueOf(1)
268 value := &cycleComplex{
269 ch: make(chan bool),
270 scalar: 123,
271 scalarArray: &scalarArray,
272 scalarSlice: []string{"hello"},
273 scalarStruct: &scalarStruct,
274
275 array: [2]*cycleElement{makeCycleElement(), makeCycleElement()},
276 slice: []*cycleElement{makeCycleElement(), makeCycleElement()},
277 iface1: makeCycleElement(),
278 iface2: makeCycleElement(),
279 ptr1: makeCycleElement(),
280 ptr2: makeCycleElement(),
281
282 scalarMap: map[string]int{
283 "foo": 123,
284 },
285 plainMap: map[int]*cycleElement{
286 123: makeCycleElement(),
287 },
288 simpleMap: map[*cycleList]*cycleElement{
289 makeCycleElement().list: makeCycleElement(),
290 },
291 complexMap: map[*cycleElement]*cycleElement{
292 makeCycleElement(): makeCycleElement(),
293 },
294 }
295 value.refSlice = &value.slice
296 value.refComplexMap = &value.complexMap
297 cloned := cloneSlowly(allocator, value).(*cycleComplex)
298
299 cloned.array[0].validateCycle(t)
300 cloned.array[1].validateCycle(t)
301 cloned.slice[0].validateCycle(t)
302 cloned.slice[1].validateCycle(t)
303
304 cloned.iface1.(*cycleElement).validateCycle(t)
305 cloned.iface2.(*cycleElement).validateCycle(t)
306 cloned.ptr1.validateCycle(t)
307 cloned.ptr2.validateCycle(t)
308 cloned.plainMap[123].validateCycle(t)
309
310 for k, v := range cloned.simpleMap {
311 k.root.validateCycle(t)
312 k.elem.next.validateCycle(t)
313 v.validateCycle(t)
314 }
315
316 for k, v := range cloned.complexMap {
317 k.validateCycle(t)
318 v.validateCycle(t)
319 }
320
321 a := assert.New(t)
322 a.Assert(cloned.refSlice == &cloned.slice)
323 a.Assert(cloned.refComplexMap == &cloned.complexMap)
324 }
325
326 func makeLinkedElements() (elem1, elem2 *cycleElement) {
327 list := &cycleList{}
328 elem1 = &list.root
329 elem2 = &cycleElement{
330 next: &list.root,
331 list: list,
332 }
333 list.root.next = &cycleElement{}
334 list.elem = elem2
335
336 return
337 }
338
339 func (elem *cycleElement) validateLinked(t *testing.T) {
340 a := assert.New(t)
341
342 // elem is the elem2.
343 a.Assert(elem == elem.list.elem)
344 a.Assert(elem.next == &elem.list.root)
345 a.Assert(elem.next.next.next == nil)
346 }
347
348 func testSlowlyFixInvalidLinkedPointers(t *testing.T, allocator *Allocator) {
349 value := &cycleComplex{
350 array: func() (elems [2]*cycleElement) {
351 elems[0], elems[1] = makeLinkedElements()
352 return
353 }(),
354 slice: func() []*cycleElement {
355 elem1, elem2 := makeLinkedElements()
356 return []*cycleElement{elem1, elem2}
357 }(),
358
359 scalarMap: map[string]int{
360 "foo": 123,
361 },
362 plainMap: func() map[int]*cycleElement {
363 elem1, elem2 := makeLinkedElements()
364 return map[int]*cycleElement{
365 1: elem1,
366 2: elem2,
367 }
368 }(),
369 simpleMap: func() map[*cycleList]*cycleElement {
370 elem1, elem2 := makeLinkedElements()
371 return map[*cycleList]*cycleElement{
372 elem2.list: elem1,
373 }
374 }(),
375 complexMap: func() map[*cycleElement]*cycleElement {
376 elem1, elem2 := makeLinkedElements()
377 return map[*cycleElement]*cycleElement{
378 elem1: elem2,
379 }
380 }(),
381 }
382 value.refSlice = &value.slice
383 value.refComplexMap = &value.complexMap
384 value.iface1, value.iface2 = makeLinkedElements()
385 value.ptr1, value.ptr2 = makeLinkedElements()
386 value.pair.elem1, value.pair.elem2 = makeLinkedElements()
387 var pair cycleElementPair
388 pair.elem1, pair.elem2 = makeLinkedElements()
389 value.pairValue = pair
390 cloned := cloneSlowly(allocator, value).(*cycleComplex)
391
392 cloned.array[1].validateLinked(t)
393 cloned.slice[1].validateLinked(t)
394
395 cloned.iface2.(*cycleElement).validateLinked(t)
396 cloned.ptr2.validateLinked(t)
397 cloned.plainMap[2].validateLinked(t)
398
399 for k := range cloned.simpleMap {
400 k.elem.validateLinked(t)
401 }
402
403 for _, v := range cloned.complexMap {
404 v.validateLinked(t)
405 }
406
407 value.pair.elem2.validateLinked(t)
408 value.pairValue.(cycleElementPair).elem2.validateLinked(t)
409
410 a := assert.New(t)
411 a.Assert(cloned.refSlice == &cloned.slice)
412 a.Assert(cloned.refComplexMap == &cloned.complexMap)
413 }
414
415 func testCloneArray(t *testing.T, allocator *Allocator) {
416 a := assert.New(t)
417 arr := [2]*T{
418 {
419 Foo: 123,
420 Bar: map[string]interface{}{
421 "abc": 123,
422 },
423 },
424 {
425 Foo: 456,
426 Bar: map[string]interface{}{
427 "def": 456,
428 "ghi": 789,
429 },
430 },
431 }
432 cloned := clone(allocator, arr).([2]*T)
433 a.Use(&arr, &cloned)
434
435 a.Equal(arr, cloned)
436
437 // arr is not changed if cloned is mutated.
438 cloned[0].Foo = 987
439 cloned[1].Bar["ghi"] = 321
440 a.Equal(arr[0].Foo, 123)
441 a.Equal(arr[1].Bar["ghi"], 789)
442 }
443
444 func testCloneMap(t *testing.T, allocator *Allocator) {
445 a := assert.New(t)
446 m := map[string]*T{
447 "abc": {
448 Foo: 123,
449 Bar: map[string]interface{}{
450 "abc": 321,
451 },
452 },
453 "def": {
454 Foo: 456,
455 Bar: map[string]interface{}{
456 "def": 789,
457 },
458 },
459 }
460 cloned := clone(allocator, m).(map[string]*T)
461 a.Use(&m, &cloned)
462
463 a.Equal(m, cloned)
464
465 // m is not changed if cloned is mutated.
466 cloned["abc"].Foo = 321
467 cloned["def"].Bar["def"] = 987
468 a.Equal(m["abc"].Foo, 123)
469 a.Equal(m["def"].Bar["def"], 789)
470 }
471
472 func testCloneBytesBuffer(t *testing.T, allocator *Allocator) {
473 a := assert.New(t)
474 buf := &bytes.Buffer{}
475 buf.WriteString("Hello, world!")
476 dummy := make([]byte, len("Hello, "))
477 buf.Read(dummy)
478 cloned := clone(allocator, buf).(*bytes.Buffer)
479 a.Use(&buf, &cloned)
480
481 // Data must be cloned.
482 a.Equal(buf.Len(), cloned.Len())
483 a.Equal(buf.String(), cloned.String())
484
485 // Data must not share the same address.
486 from := buf.Bytes()
487 to := cloned.Bytes()
488 a.Assert(&from[0] != &to[0])
489
490 buf.WriteString("!!!!!")
491 a.NotEqual(buf.Len(), cloned.Len())
492 a.NotEqual(buf.String(), cloned.String())
493 }
494
495 type Simple struct {
496 Foo int
497 Bar string
498 }
499
500 type Unexported struct {
501 insider
502 }
503
504 type insider struct {
505 i int
506 i8 int8
507 i16 int16
508 i32 int32
509 i64 int64
510 u uint
511 u8 uint8
512 u16 uint16
513 u32 uint32
514 u64 uint64
515 uptr uintptr
516 b bool
517 s string
518 f32 float32
519 f64 float64
520 c64 complex64
521 c128 complex128
522 arr [4]string
523 arrPtr *[10]byte
524 ch chan bool
525 fn func(s string) string
526 method func([]byte) (int, error)
527 iface io.Writer
528 ifaceScalar io.Writer
529 _ interface{}
530 m map[string]interface{}
531 ptr *Unexported
532 _ *Unexported
533 slice []*Unexported
534 st Simple
535 unsafePointer unsafe.Pointer
536 t reflect.Type
537
538 Simple
539 }
540
541 type scalarWriter int8
542
543 func (scalarWriter) Write(p []byte) (n int, err error) { return }
544
545 func testCloneUnexportedFields(t *testing.T, allocator *Allocator) {
546 a := assert.New(t)
547 unexported := &Unexported{
548 insider: insider{
549 i: -1,
550 i8: -8,
551 i16: -16,
552 i32: -32,
553 i64: -64,
554 u: 1,
555 u8: 8,
556 u16: 16,
557 u32: 32,
558 u64: 64,
559 uptr: uintptr(0xDEADC0DE),
560 b: true,
561 s: "hello",
562 f32: 3.2,
563 f64: 6.4,
564 c64: complex(6, 4),
565 c128: complex(12, 8),
566 arr: [4]string{
567 "a", "b", "c", "d",
568 },
569 arrPtr: &[10]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
570 ch: make(chan bool, 5),
571 fn: func(s string) string {
572 return s + ", world!"
573 },
574 method: bytes.NewBufferString("method").Write,
575 iface: bytes.NewBufferString("interface"),
576 ifaceScalar: scalarWriter(123),
577 m: map[string]interface{}{
578 "key": "value",
579 },
580 unsafePointer: unsafe.Pointer(&Unexported{}),
581 st: Simple{
582 Foo: 123,
583 Bar: "bar1",
584 },
585 Simple: Simple{
586 Foo: 456,
587 Bar: "bar2",
588 },
589 t: reflect.TypeOf(&Simple{}),
590 },
591 }
592 unexported.m["loop"] = &unexported.m
593
594 // Make pointer cycles.
595 unexported.ptr = unexported
596 unexported.slice = []*Unexported{unexported}
597 cloned := cloneSlowly(allocator, unexported).(*Unexported)
598 a.Use(&unexported, &cloned)
599
600 // unsafe.Pointer is shadow copied.
601 a.Assert(cloned.unsafePointer == unexported.unsafePointer)
602 unexported.unsafePointer = nil
603 cloned.unsafePointer = nil
604
605 // chan cannot be compared, but its buffer can be verified.
606 a.Equal(cap(cloned.ch), cap(unexported.ch))
607 unexported.ch = nil
608 cloned.ch = nil
609
610 // fn cannot be compared, but it can be called.
611 a.Equal(cloned.fn("Hello"), unexported.fn("Hello"))
612 unexported.fn = nil
613 cloned.fn = nil
614
615 // method cannot be compared, but it can be called.
616 a.Assert(cloned.method != nil)
617 a.NilError(cloned.method([]byte("1234")))
618 unexported.method = nil
619 cloned.method = nil
620
621 // cloned.m["loop"] must be exactly the same map of cloned.m.
622 a.Assert(reflect.ValueOf(cloned.m["loop"]).Elem().Pointer() == reflect.ValueOf(cloned.m).Pointer())
623
624 // Don't test this map in reflect.DeepEqual due to bug in Go.
625 // https://github.com/golang/go/issues/33907
626 unexported.m["loop"] = nil
627 cloned.m["loop"] = nil
628
629 // reflect.Type should be copied by value.
630 a.Equal(reflect.ValueOf(cloned.t).Pointer(), reflect.ValueOf(unexported.t).Pointer())
631
632 // Finally, everything else should equal.
633 a.Equal(unexported, cloned)
634 }
635
636 func testCloneUnexportedStructMethod(t *testing.T, allocator *Allocator) {
637 a := assert.New(t)
638
639 // Another complex case: clone a struct and a map of struct instead of ptr to a struct.
640 st := insider{
641 m: map[string]interface{}{
642 "insider": insider{
643 method: bytes.NewBufferString("method").Write,
644 },
645 },
646 }
647 cloned := clone(allocator, st).(insider)
648 a.Use(&st, &cloned)
649
650 // For a struct copy, there is a tricky way to copy method. Test it.
651 a.Assert(cloned.m["insider"].(insider).method != nil)
652 n, err := cloned.m["insider"].(insider).method([]byte("1234"))
653 a.NilError(err)
654 a.Equal(n, 4)
655 }
656
657 func testCloneReflectType(t *testing.T, allocator *Allocator) {
658 a := assert.New(t)
659
660 // reflect.rtype should not be deeply cloned.
661 foo := reflect.TypeOf("foo")
662 cloned := clone(allocator, foo).(reflect.Type)
663 a.Use(&foo, &cloned)
664
665 from := reflect.ValueOf(foo)
666 to := reflect.ValueOf(cloned)
667
668 a.Assert(from.Pointer() == to.Pointer())
669 }