-
Notifications
You must be signed in to change notification settings - Fork 1
/
env.go
290 lines (244 loc) · 7.19 KB
/
env.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package envygo
import (
"fmt"
"reflect"
"sync"
"unsafe"
)
var registered []interface{}
// Introduce introduces (akin to registers) environments which are
// likely to be mocked in future using MockMany function
// Deprecated Introduce is being considered for deletion to
// reduce the footprint of the API
func Introduce(envs ...interface{}) {
registered = append(registered, envs...)
}
// MockMany is a convenience method for mocking many environments
// at once that were previously introduced using Introduce function.
// Each of the envs is matched to a previously introduced environment
// based on type commonality and the introduced environment is
// mocked using the passed environment.
// Deprecated MockMany is being considered for deletion to remove
// the linkage between Introduce and MockMany. It simplifies the
// API by reducing complexity and footprint both at the same time.
func MockMany(envs ...interface{}) func() {
var funcs []func()
for _, unknown := range envs {
unknownType := reflect.ValueOf(unknown).Type()
for _, known := range registered {
if reflect.ValueOf(known).Type() == unknownType {
funcs = append(funcs, Mock(known, unknown))
unknownType = nil
}
}
if unknownType != nil {
panic(fmt.Sprintf("Attempt to mock unregistered type via %v", unknown))
}
}
return func() {
Unmock(funcs...)
}
}
// Unmock is handy to invoke the return values of Mock family of methods
func Unmock(funcs ...func()) {
for _, function := range funcs {
if function != nil {
defer function()
}
}
}
func getNonExportedField(field reflect.Value) reflect.Value {
return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem()
}
type field struct {
name string
value interface{}
exported bool
}
// Locker function locks the interface old if lockUnlock value is true.
// It unlocks the locked interface old if the lockUnlock value is false
type Locker func(old interface{}, lockUnlock bool)
func toPairs(new interface{}, includeZeros bool) []field {
var fields []field = nil
valueOfNew := reflect.ValueOf(new).Elem()
typeOfNew := reflect.TypeOf(new).Elem()
for i := typeOfNew.NumField(); i > 0; {
i--
newField := valueOfNew.Field(i)
var value interface{}
exported := typeOfNew.Field(i).IsExported()
if exported {
value = newField.Interface()
} else {
value = getNonExportedField(newField).Interface()
}
if includeZeros || !isZero(reflect.ValueOf(value)) {
fields = append(fields, field{typeOfNew.Field(i).Name, value, exported})
}
}
return fields
}
// execute examines old to see if any of the fields defined
// in old can be used to lock the interface. If a qualified
// mutex is found in old, then it's locked before function
// is invoked. If the function panics, the mutex is unlocked
// right away. In all other cases it's caller's responsibility
// to invoke locker to unlock the mutex if one is there.
func execute(old interface{}, function func()) Locker {
locker := getMutex(reflect.ValueOf(old).Elem(), reflect.TypeOf(old).Elem())
if locker == nil {
function()
} else {
_panic := true
if locker != nil {
locker(old, true)
defer func() {
if _panic {
locker(old, false)
}
}()
}
function()
_panic = false
}
return locker
}
func getMutex(valueOf reflect.Value, typeOf reflect.Type) (locker Locker) {
defer func() {
if locker == nil {
locker = func(interface{}, bool) {}
}
}()
for i := typeOf.NumField(); i > 0; {
i--
oldField := typeOf.Field(i)
tag := oldField.Tag.Get("env")
if tag == "mutex" {
field := valueOf.Field(i)
if !oldField.IsExported() {
field = getNonExportedField(field)
}
switch oldField.Type.Kind() {
case reflect.Struct:
mutex := (*sync.Mutex)(unsafe.Pointer(field.UnsafeAddr()))
return func(old interface{}, lockUnlock bool) {
if lockUnlock {
mutex.Lock()
} else {
mutex.Unlock()
}
}
case reflect.Pointer:
mutex := field.Interface().(*sync.Mutex)
if mutex != nil {
return func(old interface{}, lock bool) {
if lock {
mutex.Lock()
} else {
mutex.Unlock()
}
}
}
case reflect.Func:
return field.Interface().(Locker)
default:
panic(`field marked "mutex" can either be a pointer to sync.Mutex or a "Locker" function`)
}
}
}
return nil
}
// Mock mocks the old environment using the values in the new environment
// If the type for old environment is identical to the type of the new environment
// then any attribute with value identical to default value for its type is
// not mocked. But if types are different then the attribute is mocked regardless
// of its value
func Mock(old interface{}, new interface{}) func() {
array := toPairs(new, reflect.TypeOf(new).Elem() != reflect.ValueOf(old).Elem().Type())
if array == nil {
return func() {}
}
locker := execute(old, func() { array = mockHelper(old, array) })
return func() {
defer locker(old, false)
mockHelper(old, array)
}
}
func mockHelper(old interface{}, fields []field) []field {
oldPtrVal := reflect.New(reflect.TypeOf(old))
oldPtrVal.Elem().Set(reflect.ValueOf(old))
valueOfOld := oldPtrVal.Elem().Elem()
for i, f := range fields {
fields[i].value = mockField(valueOfOld, f.name, f.value, f.exported)
}
return fields
}
func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Func, reflect.Map, reflect.Slice:
return v.IsNil()
case reflect.Array:
z := true
for i := 0; i < v.Len(); i++ {
z = z && isZero(v.Index(i))
}
return z
case reflect.Struct:
z := true
for i := 0; i < v.NumField(); i++ {
z = z && isZero(v.Field(i))
}
return z
}
// this takes care of the non-exported fields
return !v.IsValid() || v.IsZero()
}
// MockField replaces the value of the field identified by `name` with `value`
func MockField(old interface{}, name string, value any) func() {
typeOf := reflect.TypeOf(old).Elem()
if typeField, found := typeOf.FieldByName(name); found {
exported := typeField.IsExported()
valueOfOld := reflect.ValueOf(old).Elem()
locker := execute(old, func() {
value = mockField(valueOfOld, name, value, exported)
})
return func() {
defer locker(old, false)
mockField(valueOfOld, name, value, exported)
}
}
panic("no property with name " + name + " found")
}
// Fields allows specifying multiple mappings by using field names.
type Fields map[string]interface{}
// MockFields mocks many fields of the struct pointed to by old
func MockFields(old interface{}, fields Fields) func() {
var array []field
locker := execute(old, func() {
typeOf := reflect.TypeOf(old).Elem()
valueOfOld := reflect.ValueOf(old).Elem()
for name, value := range fields {
if typeField, found := typeOf.FieldByName(name); found {
exported := typeField.IsExported()
old := mockField(valueOfOld, name, value, exported)
array = append(array, field{name, old, exported})
}
}
})
if array == nil {
return func() {}
}
return func() {
defer locker(old, false)
mockHelper(old, array)
}
}
func mockField(valueOfOld reflect.Value, name string, new any, exported bool) interface{} {
field := valueOfOld.FieldByName(name)
if !exported {
field = getNonExportedField(field)
}
old := field.Interface()
field.Set(reflect.ValueOf(new))
return old
}