Debian Codegraph @

wrapper_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 "testing"
8
9 "github.com/huandu/go-assert"
10 )
11
12 type testType struct {
13 Foo string
14 Bar map[string]interface{}
15 Player []float64
16 }
17
18 type testSimple struct {
19 Foo int
20 Bar string
21 }
22
23 func TestWrap(t *testing.T) {
24 a := assert.New(t)
25 a.Equal(Wrap(nil), nil)
26
27 orig := &testType{
28 Foo: "abcd",
29 Bar: map[string]interface{}{
30 "def": 123,
31 "ghi": 78.9,
32 },
33 Player: []float64{
34 12.3, 45.6, -78.9,
35 },
36 }
37 wrapped := Wrap(orig).(*testType)
38 a.Use(&orig, &wrapped)
39
40 a.Equal(orig, wrapped)
41 a.Equal(Wrap(wrapped), wrapped)
42
43 wrapped.Foo = "xyz"
44 wrapped.Bar["ghi"] = 98.7
45 wrapped.Player[1] = 65.4
46
47 a.Equal(orig.Foo, "abcd")
48 a.Equal(orig.Bar["ghi"], 78.9)
49 a.Equal(orig.Player[1], 45.6)
50
51 actual := Unwrap(wrapped).(*testType)
52 a.Assert(orig == actual)
53 }
54
55 func TestWrapScalarPtr(t *testing.T) {
56 a := assert.New(t)
57 i := 123
58 c := &i
59 v := Wrap(c).(*int)
60 orig := Unwrap(v).(*int)
61 a.Use(&a, &i, &c, &v)
62
63 a.Assert(*v == *c)
64 a.Assert(orig == c)
65 }
66
67 func TestWrapNonePtr(t *testing.T) {
68 a := assert.New(t)
69 cases := []interface{}{
70 123, nil, "abcd", []string{"ghi"}, map[string]int{"xyz": 123},
71 }
72
73 for _, c := range cases {
74 v := Wrap(c)
75 a.Equal(c, v)
76 }
77 }
78
79 func TestUnwrapValueWhichIsNotWrapped(t *testing.T) {
80 a := assert.New(t)
81 s := &testType{
82 Foo: "abcd",
83 Bar: map[string]interface{}{
84 "def": 123,
85 "ghi": 78.9,
86 },
87 Player: []float64{
88 12.3, 45.6, -78.9,
89 },
90 }
91 v := Unwrap(s).(*testType)
92 v.Foo = "xyz"
93
94 a.Equal(s, v)
95 }
96
97 func TestUnwrapPlainValueWhichIsNotWrapped(t *testing.T) {
98 a := assert.New(t)
99 i := 0
100 cases := []interface{}{
101 123, "abc", nil, &i,
102 }
103
104 for _, c := range cases {
105 v := Unwrap(c)
106
107 a.Equal(c, v)
108
109 old := c
110 Undo(c)
111
112 a.Equal(c, old)
113 }
114 }
115
116 func TestUndo(t *testing.T) {
117 a := assert.New(t)
118 orig := &testType{
119 Foo: "abcd",
120 Bar: map[string]interface{}{
121 "def": 123,
122 "ghi": 78.9,
123 },
124 Player: []float64{
125 12.3, 45.6, -78.9,
126 },
127 }
128 wrapped := Wrap(orig).(*testType)
129 a.Use(&orig, &wrapped)
130
131 wrapped.Foo = "xyz"
132 wrapped.Bar["ghi"] = 98.7
133 wrapped.Player[1] = 65.4
134
135 a.Equal(orig.Foo, "abcd")
136 a.Equal(orig.Bar["ghi"], 78.9)
137 a.Equal(orig.Player[1], 45.6)
138
139 Undo(wrapped)
140 a.Equal(orig, wrapped)
141 }