-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinjector_test.go
More file actions
715 lines (650 loc) · 19.6 KB
/
injector_test.go
File metadata and controls
715 lines (650 loc) · 19.6 KB
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
package goinject
import (
"context"
"fmt"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
type Parent struct {
}
type Child struct {
parent *Parent
}
func TestShouldReturnFromProvider(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector(
Provide(func() *Parent { return &Parent{} }),
Provide(func(parent *Parent) *Child { return &Child{parent: parent} }),
)
assert.Nil(t, err)
ctx := context.Background()
var parent *Parent
err = injector.Invoke(ctx, func(p *Parent) {
parent = p
})
assert.Nil(t, err)
var child *Child
err = injector.Invoke(ctx, func(c *Child) {
child = c
})
assert.Nil(t, err)
assert.Same(t, parent, child.parent)
})
}
func TestProvideShouldAcceptErrorReturnProviders(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector(
Provide(func() (*Parent, error) { return &Parent{}, nil }, In(PerLookUp)),
Provide(func(_ *Parent) (*Child, error) { return nil, fmt.Errorf("failed to create child") }, In(PerLookUp)),
)
assert.Nil(t, err)
ctx := context.Background()
t.Run("And return type if no error", func(t *testing.T) {
err = injector.Invoke(ctx, func(parent *Parent) {
assert.NotNil(t, parent)
})
assert.Nil(t, err)
})
t.Run("And return error otherwise", func(t *testing.T) {
err = injector.Invoke(ctx, func(_ *Child) {
assert.Fail(t, "should not be reached")
})
assert.ErrorContains(t, err, "failed to create child")
})
})
}
func TestUseUnknownScopeShouldReturnError(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector(
Provide(func() *Parent { return &Parent{} }, In("unknown")),
)
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(_ *Parent) {
assert.Fail(t, "should not be reached")
})
assert.ErrorContains(t, err, "unknown scope \"unknown\" for binding")
})
}
type TestInvokeParamOptional struct {
Params
ParentA *Parent `inject:", optional"`
ParentB *Parent `inject:"B"`
}
func TestInvokeWithOptional(t *testing.T) {
assert.NotPanics(t, func() {
t.Run("using param struct argument", func(t *testing.T) {
injector, err := NewInjector(
Provide(func() *Parent {
return &Parent{}
}, Named("B")),
)
assert.Nil(t, err)
var parentA *Parent
var parentB *Parent
ctx := context.Background()
err = injector.Invoke(ctx, func(param TestInvokeParamOptional) {
parentA = param.ParentA
parentB = param.ParentB
})
assert.Nil(t, err)
assert.Nil(t, parentA)
assert.NotNil(t, parentB)
})
t.Run("using param pointer argument", func(t *testing.T) {
injector, err := NewInjector(
Provide(func() *Parent {
return &Parent{}
}, Named("B")),
)
assert.Nil(t, err)
var parentA *Parent
var parentB *Parent
ctx := context.Background()
err = injector.Invoke(ctx, func(param *TestInvokeParamOptional) {
parentA = param.ParentA
parentB = param.ParentB
})
assert.Nil(t, err)
assert.Nil(t, parentA)
assert.NotNil(t, parentB)
})
})
}
type Color struct {
name string
}
type TestInvokeParamAnnotated struct {
Params
Color *Color `inject:"red"`
}
func TestInvokeWithAnnotation(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector(
Provide(func() *Color { return &Color{name: "red"} }, Named("red")),
Provide(func() *Color { return &Color{name: "blue"} }, Named("blue")),
)
assert.Nil(t, err)
var color *Color
ctx := context.Background()
err = injector.Invoke(ctx, func(param TestInvokeParamAnnotated) {
color = param.Color
})
assert.NotNil(t, color)
assert.Equal(t, "red", color.name)
assert.Nil(t, err)
})
}
func TestInvokeShouldReturnErrorIfExpectedSingleBindingButMultipleFound(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector(
Provide(func() *Color { return &Color{name: "blue"} }),
Provide(func() *Color { return &Color{name: "red"} }),
)
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(_ *Color) {
assert.Fail(t, "should not be reached")
})
assert.NotNil(t, err)
// verify error tree contains an injection error
var expectedErrorType *injectionError
assert.ErrorAs(t, err, &expectedErrorType)
assert.Equal(t,
"failed to call invokation function: failed to resolve"+
" function argument #0: Got error while resolving type *goinject.Color"+
" (with annotation \"\"):\nfound multiple bindings expected one",
err.Error())
})
}
type Red *Color
type Blue *Color
func TestInvokeUsingTypeDefinition(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector(
Provide(func() *Color { return &Color{name: "blue"} }, As(Type[Blue]())),
Provide(func() *Color { return &Color{name: "red"} }, As(Type[Red]())),
)
assert.Nil(t, err)
var color Red
ctx := context.Background()
err = injector.Invoke(ctx, func(c Red) {
color = c
})
assert.NotNil(t, color)
assert.Equal(t, "red", color.name)
assert.Nil(t, err)
})
}
func TestInstallModuleShouldInstallBindingsOnce(t *testing.T) {
assert.NotPanics(t, func() {
subModule := Module("sub", Provide(func() *Parent {
return &Parent{}
}, Named("parent-in-sub")))
parentModuleA := Module("parent-a", subModule)
parentModuleB := Module("parent-b", subModule)
injector, err := NewInjector(
parentModuleA,
parentModuleB,
)
assert.Nil(t, err)
assert.NotNil(t, injector)
assert.Equal(t, 1, len(injector.bindings[reflect.TypeFor[*Parent]()]))
assert.Equal(t, 2, len(injector.bindings)) // we add a binding for *Injector
})
}
type Shape interface {
Name() string
}
type Rectangle struct {
}
func (r *Rectangle) Name() string {
return "rectangle"
}
type Square struct {
}
func (s *Square) Name() string {
return "square"
}
func TestBindToInterface(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector(
Provide(func() *Rectangle {
return &Rectangle{}
}, As(Type[Shape]())),
)
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(s Shape) {
assert.IsType(t, &Rectangle{}, s)
})
assert.Nil(t, err)
})
}
func TestInjectorShouldBeProvided(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector()
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(i *Injector) {
assert.Same(t, i, injector)
})
assert.Nil(t, err)
})
}
type WithRefCount struct {
refCount int
}
func TestInjectorShutdownShouldShutdownSingletonScope(t *testing.T) {
assert.NotPanics(t, func() {
refCount := 0
injector, err := NewInjector(
Provide(func() *WithRefCount {
res := &WithRefCount{refCount: refCount}
refCount++
return res
}, WithDestroy(func(_ *WithRefCount) {
refCount--
}), In(Singleton)),
)
assert.Nil(t, err)
ctx := context.Background()
// singleton should be created eagerly
assert.Equal(t, 1, refCount)
err = injector.Invoke(ctx, func(c *WithRefCount) {
assert.Equal(t, 1, refCount)
assert.Equal(t, 0, c.refCount)
})
assert.Nil(t, err)
assert.Equal(t, 1, refCount)
injector.Shutdown()
assert.Equal(t, 0, refCount)
assert.Equal(t, 0, len(injector.bindings))
})
}
func TestNewInjectorShouldReturnErrorIfEagerlyCreatedSingletonReturnError(t *testing.T) {
returnedErr := fmt.Errorf("provider error")
assert.NotPanics(t, func() {
_, err := NewInjector(
Provide(func() (*WithRefCount, error) {
return nil, returnedErr
}),
)
assert.ErrorIs(t, err, returnedErr)
assert.Equal(t, "failed to get singleton instance: provider for type \"*goinject.WithRefCount\" "+
"returned error: provider error", err.Error())
})
}
type MultiBindOptionalInvokeParams struct {
Params
Shapes []Shape `inject:",optional"`
}
func TestMultiBind(t *testing.T) {
t.Run("Using multiple interface implementation", func(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector(
Provide(func() *Rectangle {
return &Rectangle{}
}, As(Type[Shape]())),
Provide(func() *Square {
return &Square{}
}, As(Type[Shape]())),
)
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(shapes []Shape) {
var names []string
for _, shape := range shapes {
names = append(names, shape.Name())
}
assert.Contains(t, names, "square")
assert.Contains(t, names, "rectangle")
})
assert.Nil(t, err)
})
})
t.Run("Should not throw error if not found and optional", func(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector()
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(params MultiBindOptionalInvokeParams) {
assert.Empty(t, params.Shapes)
})
assert.Nil(t, err)
})
})
t.Run("Should throw error if not found and not optional", func(t *testing.T) {
assert.NotPanics(t, func() {
injector, err := NewInjector()
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(_ []Shape) {
assert.Fail(t, "should not be reached")
})
assert.NotNil(t, err)
var expectedErrorType *injectionError
assert.ErrorAs(t, err, &expectedErrorType)
assert.Equal(t, "failed to call invokation function: failed to resolve function argument #0: "+
"Got error while resolving type goinject.Shape (with annotation \"\"):\n"+
"did not found binding, expected at least one", err.Error())
})
})
}
type WithProvider struct {
provider Provider[*WithRefCount]
}
type WithProviderParam struct {
Params
Provider Provider[*WithRefCount] `inject:",optional"`
}
func TestProvider(t *testing.T) {
assert.NotPanics(t, func() {
t.Run("Get from provider should re-ask scope (with per-lookup)", func(t *testing.T) {
refCount := 0
injector, rootError := NewInjector(
Provide(func() *WithRefCount {
res := &WithRefCount{refCount: refCount}
refCount++
return res
}, In(PerLookUp)),
Provide(func(p Provider[*WithRefCount]) *WithProvider {
return &WithProvider{
provider: p,
}
}),
)
assert.Nil(t, rootError)
ctx := context.Background()
rootError = injector.Invoke(ctx, func(w *WithProvider) {
ref1, err := w.provider(ctx)
assert.Nil(t, err)
ref2, err := w.provider(ctx)
assert.Nil(t, err)
assert.NotEqual(t, ref2, ref1)
assert.Equal(t, 0, ref1.refCount)
assert.Equal(t, 1, ref2.refCount)
})
assert.Nil(t, rootError)
})
t.Run("Get from provider should re-ask scope (with singleton)", func(t *testing.T) {
refCount := 0
injector, rootError := NewInjector(
Provide(func() *WithRefCount {
res := &WithRefCount{refCount: refCount}
refCount++
return res
}, In(Singleton)),
Provide(func(p Provider[*WithRefCount]) *WithProvider {
return &WithProvider{
provider: p,
}
}),
)
assert.Nil(t, rootError)
ctx := context.Background()
rootError = injector.Invoke(ctx, func(w *WithProvider) {
ref1, err := w.provider(ctx)
assert.Nil(t, err)
ref2, err := w.provider(ctx)
assert.Nil(t, err)
assert.Same(t, ref2, ref1)
})
assert.Nil(t, rootError)
})
t.Run("Provider with optional should return zero value if not present", func(t *testing.T) {
injector, rootError := NewInjector()
assert.Nil(t, rootError)
ctx := context.Background()
rootError = injector.Invoke(ctx, func(w WithProviderParam) {
ref, err := w.Provider(ctx)
assert.Nil(t, err)
assert.Nil(t, ref)
})
assert.Nil(t, rootError)
})
t.Run("Provider should return error", func(t *testing.T) {
injector, rootError := NewInjector(
Provide(func() (*WithRefCount, error) {
return nil, fmt.Errorf("test error")
}, In(PerLookUp)),
Provide(func(p Provider[*WithRefCount]) *WithProvider {
return &WithProvider{
provider: p,
}
}, In(PerLookUp)),
)
assert.Nil(t, rootError)
ctx := context.Background()
rootError = injector.Invoke(ctx, func(w *WithProvider) {
ref, err := w.provider(ctx)
assert.Nil(t, ref)
assert.NotNil(t, err)
assert.Equal(t, "provider for type \"*goinject.WithRefCount\" returned error: test error", err.Error())
})
assert.Nil(t, rootError)
})
})
}
func TestConditional(t *testing.T) {
t.Run("Test conditional env var should not register binding if no match", func(t *testing.T) {
t.Setenv("TEST", "CASE-KO")
injector, err := NewInjector(
When(OnEnvironmentVariable("TEST", "CASE-OK", false),
Provide(func() (*Parent, error) { return &Parent{}, nil }),
),
)
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(_ *Parent) {
assert.Fail(t, "inaccessible")
})
assert.NotNil(t, err)
var expectedErrorType *injectionError
assert.ErrorAs(t, err, &expectedErrorType)
assert.Equal(t,
"failed to call invokation function: failed to resolve function argument #0: "+
"Got error while resolving type *goinject.Parent (with annotation \"\"):\ndid not found binding, "+
"expected one",
err.Error(),
)
})
t.Run("Test conditional env var should register binding if match", func(t *testing.T) {
t.Setenv("TEST", "CASE-OK")
injector, err := NewInjector(
When(OnEnvironmentVariable("TEST", "CASE-OK", false),
Provide(func() (*Parent, error) { return &Parent{}, nil }),
),
)
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(parent *Parent) {
assert.NotNil(t, parent)
})
assert.Nil(t, err)
})
t.Run("Test conditional env var should register binding if no match but match missing", func(t *testing.T) {
injector, err := NewInjector(
When(OnEnvironmentVariable("TEST", "CASE-OO", true),
Provide(func() (*Parent, error) { return &Parent{}, nil }),
),
)
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func(parent *Parent) {
assert.NotNil(t, parent)
})
assert.Nil(t, err)
})
t.Run("Test When should return binding configuration errors", func(t *testing.T) {
_, err := NewInjector(
When(OnEnvironmentVariable("TEST", "CASE-OK", true),
Provide(nil),
),
)
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t, "cannot accept nil provider", err.Error())
})
}
func TestInvokeError(t *testing.T) {
t.Run("Invoke should not accept nil", func(t *testing.T) {
injector, err := NewInjector()
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, nil)
assert.NotNil(t, err)
assert.IsType(t, err, &invalidInputError{})
assert.Equal(t, "can't invoke on nil", err.Error())
})
t.Run("Invoke should only accept function", func(t *testing.T) {
injector, err := NewInjector()
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, true)
assert.NotNil(t, err)
assert.IsType(t, err, &invalidInputError{})
assert.Equal(t, "can't invoke non-function true (type bool)", err.Error())
})
t.Run("Invoke should only accept function returning error", func(t *testing.T) {
injector, err := NewInjector()
assert.Nil(t, err)
ctx := context.Background()
err = injector.Invoke(ctx, func() *Parent { return nil })
assert.NotNil(t, err)
assert.IsType(t, err, &invalidInputError{})
assert.Equal(t, "can't invoke on function whose return type is not error or no return type", err.Error())
})
t.Run("Invoke should return error if function return error", func(t *testing.T) {
injector, err := NewInjector()
assert.Nil(t, err)
ctx := context.Background()
invokationFnReturnedError := fmt.Errorf("returned error")
err = injector.Invoke(ctx, func() error { return invokationFnReturnedError })
assert.NotNil(t, err)
assert.ErrorIs(t, err, invokationFnReturnedError)
})
}
func TestInjectorConfigurationError(t *testing.T) {
t.Run("Provide cannot accept nil", func(t *testing.T) {
_, err := NewInjector(
Provide(nil))
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t, "cannot accept nil provider", err.Error())
})
t.Run("Provider should use function as argument", func(t *testing.T) {
_, err := NewInjector(
Provide(true))
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t, "provider argument should be a function", err.Error())
})
t.Run("Provider function should return an instance", func(t *testing.T) {
_, err := NewInjector(
Provide(func() {}))
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t, "expected a function that return an instance and optionally an error", err.Error())
})
t.Run("Provider function cannot return multiple types (except error)", func(t *testing.T) {
_, err := NewInjector(
Provide(func() (*Parent, *Child) {
return &Parent{}, &Child{}
}))
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t, "second return type of provider should be an error", err.Error())
})
t.Run("Module should return nested errors", func(t *testing.T) {
_, err := NewInjector(
Module("test.Module",
Provide(nil)),
)
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t, "error while installing module test.Module:\ncannot accept nil provider", err.Error())
})
t.Run("As provider annotation should raise error if not assignable", func(t *testing.T) {
_, err := NewInjector(
Provide(func() *Parent {
return &Parent{}
}, As(Type[*Child]())),
)
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t,
"got error while configuring provider for provided type *goinject.Parent:\ncannot assign "+
"*goinject.Parent to *goinject.Child as specified in As argument",
err.Error(),
)
})
t.Run("WithDestroy should raise an error if not a function", func(t *testing.T) {
_, err := NewInjector(
Provide(func() *Parent {
return &Parent{}
}, WithDestroy(true)),
)
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t,
"got error while configuring provider for provided type *goinject.Parent:\nargument of WithDestroy"+
" must be a function with one argument returning void",
err.Error(),
)
})
t.Run("WithDestroy should raise an error if not a function of provided type", func(t *testing.T) {
_, err := NewInjector(
Provide(func() *Parent {
return &Parent{}
}, WithDestroy(func(_ *Child) {})),
)
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t,
"got error while configuring provider for provided type *goinject.Parent:\nargument of WithDestroy"+
" must be a function with one argument returning void",
err.Error(),
)
})
t.Run("WithDestroy should raise an error if not a void function of provided type", func(t *testing.T) {
_, err := NewInjector(
Provide(func() *Parent {
return &Parent{}
}, WithDestroy(func(_ *Parent) error {
return nil
})),
)
assert.NotNil(t, err)
assert.IsType(t, err, &injectorConfigurationError{})
assert.Equal(t,
"got error while configuring provider for provided type *goinject.Parent:\nargument of WithDestroy "+
"must be a function with one argument returning void", err.Error(),
)
})
}
func TestNewInjectorShouldIgnoreMultipleBindings(t *testing.T) {
provider := Provide(func() int { return 32 })
inj, err := NewInjector(
provider,
provider,
)
assert.Nil(t, err)
err = inj.Invoke(context.Background(), func(val int) {
assert.Equal(t, 32, val)
})
assert.Nil(t, err)
}
func TestNewInjectorShouldIgnoreMultipleBindingsInDifferentModules(t *testing.T) {
sharedModule := Module("shared", Provide(func() int { return 32 }))
inj, err := NewInjector(
Module("module-A", sharedModule),
Module("module-B", sharedModule),
)
assert.Nil(t, err)
err = inj.Invoke(context.Background(), func(val int) {
assert.Equal(t, 32, val)
})
assert.Nil(t, err)
}