-
Notifications
You must be signed in to change notification settings - Fork 4
/
registry_test.go
339 lines (294 loc) · 11.9 KB
/
registry_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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
* SPDX-FileCopyrightText: Copyright (c) 2003 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gontainer
import (
"context"
"errors"
"fmt"
"reflect"
"sync/atomic"
"testing"
"time"
)
// TestRegistryRegisterFactory tests corresponding registry method.
func TestRegistryRegisterFactory(t *testing.T) {
fun := func(a, b, c string) (int, bool, error) {
return 1, true, nil
}
ctx := context.Background()
opts := WithMetadata("test", func() {})
factory := NewFactory(fun, opts)
registry := ®istry{}
equal(t, registry.registerFactory(ctx, factory), nil)
equal(t, registry.factories, []*Factory{factory})
equal(t, factory.factoryFunc == nil, false)
equal(t, factory.factoryLoaded, true)
}
// TestRegistryValidateFactories tests corresponding registry method.
func TestRegistryValidateFactories(t *testing.T) {
tests := []struct {
name string
factories []*Factory
wantErr func(t *testing.T, err error)
}{
{
name: "NoValidationErrors",
factories: []*Factory{
NewFactory(func(bool) (int, error) { return 1, nil }),
NewFactory(func(string) (bool, error) { return true, nil }),
NewFactory(func() (string, error) { return "s", nil }),
},
wantErr: func(t *testing.T, err error) {
equal(t, err, nil)
},
},
{
name: "ServiceNotResolvedError",
factories: []*Factory{
NewFactory(func(bool) error { return nil }),
NewFactory(func(string) error { return nil }),
},
wantErr: func(t *testing.T, err error) {
equal(t, errors.Is(err, ErrServiceNotResolved), true)
unwrap, ok := err.(interface{ Unwrap() []error })
equal(t, ok, true)
errs := unwrap.Unwrap()
equal(t, len(errs), 2)
equal(t, errors.Is(errs[0], ErrServiceNotResolved), true)
equal(t, errs[0].Error(), "failed to validate argument 'bool' (index 0) "+
"of factory 'Factory[func(bool) error]' from 'github.com/NVIDIA/gontainer': "+
"service not resolved")
equal(t, errors.Is(errs[1], ErrServiceNotResolved), true)
equal(t, errs[1].Error(), "failed to validate argument 'string' (index 0) "+
"of factory 'Factory[func(string) error]' from 'github.com/NVIDIA/gontainer': "+
"service not resolved")
},
},
{
name: "ServiceDuplicatedError",
factories: []*Factory{
NewFactory(func() (string, error) { return "s1", nil }),
NewFactory(func() (string, error) { return "s2", nil }),
},
wantErr: func(t *testing.T, err error) {
equal(t, errors.Is(err, ErrServiceDuplicated), true)
unwrap, ok := err.(interface{ Unwrap() []error })
equal(t, ok, true)
errs := unwrap.Unwrap()
equal(t, len(errs), 2)
equal(t, errors.Is(errs[0], ErrServiceDuplicated), true)
equal(t, errs[0].Error(), "failed to validate output 'string' (index 0) "+
"of factory 'Factory[func() (string, error)]' from 'github.com/NVIDIA/gontainer': "+
"service duplicated")
equal(t, errors.Is(errs[1], ErrServiceDuplicated), true)
equal(t, errs[1].Error(), "failed to validate output 'string' (index 0) "+
"of factory 'Factory[func() (string, error)]' from 'github.com/NVIDIA/gontainer': "+
"service duplicated")
},
},
{
name: "CircularDependencyErrors",
factories: []*Factory{
NewFactory(func(bool) (int, error) { return 1, nil }),
NewFactory(func(string) (bool, error) { return true, nil }),
NewFactory(func(int) (string, error) { return "s", nil }),
},
wantErr: func(t *testing.T, err error) {
equal(t, errors.Is(err, ErrCircularDependency), true)
unwrap, ok := err.(interface{ Unwrap() []error })
equal(t, ok, true)
errs := unwrap.Unwrap()
equal(t, len(errs), 3)
equal(t, errors.Is(errs[0], ErrCircularDependency), true)
equal(t, errs[0].Error(), "failed to validate factory 'Factory[func(bool) (int, error)]' "+
"from 'github.com/NVIDIA/gontainer': circular dependency")
equal(t, errors.Is(errs[1], ErrCircularDependency), true)
equal(t, errs[1].Error(), "failed to validate factory 'Factory[func(string) (bool, error)]' "+
"from 'github.com/NVIDIA/gontainer': circular dependency")
equal(t, errors.Is(errs[2], ErrCircularDependency), true)
equal(t, errs[2].Error(), "failed to validate factory 'Factory[func(int) (string, error)]' "+
"from 'github.com/NVIDIA/gontainer': circular dependency")
},
},
{
name: "ComplexErrors",
factories: []*Factory{
NewFactory(func(struct{ X int }) string { return "s1" }), // not resolved, duplicate
NewFactory(func(ctx context.Context) (string, error) { return "s2", nil }), // duplicate
NewFactory(func(bool) (int, error) { return 1, nil }), // cycle
NewFactory(func(int) (bool, string) { return true, "s3" }), // cycle, duplicate
},
wantErr: func(t *testing.T, err error) {
equal(t, errors.Is(err, ErrServiceNotResolved), true)
equal(t, errors.Is(err, ErrServiceDuplicated), true)
equal(t, errors.Is(err, ErrCircularDependency), true)
unwrap, ok := err.(interface{ Unwrap() []error })
equal(t, ok, true)
errs := unwrap.Unwrap()
equal(t, len(errs), 6)
equal(t, errors.Is(errs[0], ErrServiceNotResolved), true)
equal(t, errs[0].Error(), "failed to validate argument 'struct { X int }' (index 0) "+
"of factory 'Factory[func(struct { X int }) string]' from 'github.com/NVIDIA/gontainer': "+
"service not resolved")
equal(t, errors.Is(errs[1], ErrServiceDuplicated), true)
equal(t, errs[1].Error(), "failed to validate output 'string' (index 0) "+
"of factory 'Factory[func(struct { X int }) string]' from 'github.com/NVIDIA/gontainer': "+
"service duplicated")
equal(t, errors.Is(errs[2], ErrServiceDuplicated), true)
equal(t, errs[2].Error(), "failed to validate output 'string' (index 0) "+
"of factory 'Factory[func(context.Context) (string, error)]' from 'github.com/NVIDIA/gontainer': "+
"service duplicated")
equal(t, errors.Is(errs[3], ErrServiceDuplicated), true)
equal(t, errs[3].Error(), "failed to validate output 'string' (index 1) "+
"of factory 'Factory[func(int) (bool, string)]' from 'github.com/NVIDIA/gontainer': "+
"service duplicated")
equal(t, errors.Is(errs[4], ErrCircularDependency), true)
equal(t, errs[4].Error(), "failed to validate factory 'Factory[func(bool) (int, error)]' "+
"from 'github.com/NVIDIA/gontainer': circular dependency")
equal(t, errors.Is(errs[5], ErrCircularDependency), true)
equal(t, errs[5].Error(), "failed to validate factory 'Factory[func(int) (bool, string)]' "+
"from 'github.com/NVIDIA/gontainer': circular dependency")
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
registry := ®istry{}
for _, factory := range tt.factories {
equal(t, registry.registerFactory(ctx, factory), nil)
}
tt.wantErr(t, registry.validateFactories())
})
}
}
// TestRegistryProduceServices tests corresponding registry method.
func TestRegistryProduceServices(t *testing.T) {
ctx := context.Background()
factory := NewFactory(func() bool { return true })
registry := ®istry{}
equal(t, registry.registerFactory(ctx, factory), nil)
equal(t, registry.produceServices(), nil)
equal(t, factory.factorySpawned, true)
result := factory.factoryOutValues[0]
equal(t, result.Interface(), true)
}
// TestRegistryProduceWithErrors tests corresponding registry method.
func TestRegistryProduceWithErrors(t *testing.T) {
registry := ®istry{}
equal(t, registry.registerFactory(context.Background(), NewFactory(func() (bool, error) {
return false, errors.New("failed to create new service")
})), nil)
err := registry.produceServices()
equal(t, err != nil, true)
equal(t, fmt.Sprint(err), `failed to spawn services of `+
`'Factory[func() (bool, error)]' from 'github.com/NVIDIA/gontainer': `+
`factory returned error: failed to create new service`)
}
// TestRegistryCloseServices tests corresponding registry method.
func TestRegistryCloseServices(t *testing.T) {
funcStarted := atomic.Bool{}
funcClosed := atomic.Bool{}
factory := NewFactory(func(ctx context.Context) any {
return func() error {
funcStarted.Store(true)
<-ctx.Done()
funcClosed.Store(true)
return nil
}
})
ctx := context.Background()
registry := ®istry{}
equal(t, registry.registerFactory(ctx, factory), nil)
equal(t, registry.produceServices(), nil)
equal(t, factory.factorySpawned, true)
// Let factory function start executing in the background.
time.Sleep(time.Millisecond)
equal(t, funcStarted.Load(), true)
equal(t, funcClosed.Load(), false)
equal(t, registry.closeServices(), nil)
equal(t, funcStarted.Load(), true)
equal(t, funcClosed.Load(), true)
}
// TestRegistryCloseWithError tests corresponding registry method.
func TestRegistryCloseWithError(t *testing.T) {
ctx := context.Background()
registry := ®istry{}
equal(t, registry.registerFactory(ctx, NewFactory(func(ctx context.Context) any {
return func() error { return errors.New("failed to close 1") }
})), nil)
equal(t, registry.registerFactory(ctx, NewFactory(func() any {
return func() error { return errors.New("failed to close 2") }
})), nil)
equal(t, registry.produceServices(), nil)
err := registry.closeServices()
equal(t, err != nil, true)
equal(t, fmt.Sprint(err), `failed to close services: `+
`Factory[func() interface {}] from 'github.com/NVIDIA/gontainer': failed to close 2`+"\n"+
`Factory[func(context.Context) interface {}] from 'github.com/NVIDIA/gontainer': failed to close 1`)
}
// TestIsNonEmptyInterface tests checking of argument to be non-empty interface.
func TestIsNonEmptyInterface(t *testing.T) {
var t1 any
var t2 interface{}
var t3 struct{}
var t4 string
var t5 interface{ Close() error }
equal(t, isNonEmptyInterface(reflect.TypeOf(&t1).Elem()), false)
equal(t, isNonEmptyInterface(reflect.TypeOf(&t2).Elem()), false)
equal(t, isNonEmptyInterface(reflect.TypeOf(&t3).Elem()), false)
equal(t, isNonEmptyInterface(reflect.TypeOf(&t4).Elem()), false)
equal(t, isNonEmptyInterface(reflect.TypeOf(&t5).Elem()), true)
}
// TestIsEmptyInterface tests checking of argument to be empty interface.
func TestIsEmptyInterface(t *testing.T) {
var t1 any
var t2 interface{}
var t3 struct{}
var t4 string
var t5 interface{ Close() error }
equal(t, isEmptyInterface(reflect.TypeOf(&t1).Elem()), true)
equal(t, isEmptyInterface(reflect.TypeOf(&t2).Elem()), true)
equal(t, isEmptyInterface(reflect.TypeOf(&t3).Elem()), false)
equal(t, isEmptyInterface(reflect.TypeOf(&t4).Elem()), false)
equal(t, isEmptyInterface(reflect.TypeOf(&t5).Elem()), false)
}
// TestIsContextInterface tests checking of argument to be context.
func TestIsContextInterface(t *testing.T) {
var t1 any
var t2 interface{}
var t3 struct{}
var t4 string
var t5 context.Context
equal(t, isContextInterface(reflect.TypeOf(&t1).Elem()), false)
equal(t, isContextInterface(reflect.TypeOf(&t2).Elem()), false)
equal(t, isContextInterface(reflect.TypeOf(&t3).Elem()), false)
equal(t, isContextInterface(reflect.TypeOf(&t4).Elem()), false)
equal(t, isContextInterface(reflect.TypeOf(&t5).Elem()), true)
}
// TestWrapFactoryFunc tests wrapping of factory functions.
func TestWrapFactoryFunc(t *testing.T) {
var result = errors.New("test")
var svcfunc any = func() error {
return result
}
svcvalue := reflect.ValueOf(&svcfunc).Elem()
wrapper, err := wrapFactoryFunc(svcvalue)
equal(t, err, nil)
service := wrapper.Interface().(function)
equal(t, service.Close(), result)
}