-
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathinvoke_test.go
More file actions
792 lines (666 loc) · 24.9 KB
/
invoke_test.go
File metadata and controls
792 lines (666 loc) · 24.9 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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
package do
import (
"fmt"
"reflect"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestInvokeAnyByName(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
// test default injector vs scope
i := New()
ProvideNamedValue(i, "foo", "baz")
svc, err := invokeAnyByName(i, "foo")
is.NoError(err)
is.Equal("baz", svc)
// service not found
svc, err = invokeAnyByName(i, "not_found")
is.Error(err)
is.Empty(svc)
is.Contains(err.Error(), "DI: could not find service `not_found`, available services: ")
// test virtual scope wrapper
called := false
ProvideNamed(i, "hello", func(ivs Injector) (string, error) {
// check we received a virtualScope
vs, ok := ivs.(*virtualScope)
is.True(ok)
is.Equal([]string{"hello"}, vs.invokerChain)
is.NotEqual(i, ivs)
// create a dependency/dependent relationship
_, _ = invokeAnyByName(ivs, "foo")
called = true
return "foobar", nil
})
_, _ = invokeAnyByName(i, "hello")
is.True(called)
// check dependency/dependent relationship
dependencies, dependents := i.dag.explainService(i.self.id, i.self.name, "hello")
is.ElementsMatch([]ServiceDescription{{ScopeID: i.self.id, ScopeName: i.self.name, Service: "foo"}}, dependencies)
is.ElementsMatch([]ServiceDescription{}, dependents)
// test circular dependency
vs := newVirtualScope(i, []string{"foo", "bar"})
svc, err = invokeAnyByName(vs, "foo")
is.Error(err)
is.Empty(svc)
is.ErrorIs(err, ErrCircularDependency)
is.EqualError(err, "DI: circular dependency detected: `foo` -> `bar` -> `foo`")
// Test service type mismatch
ProvideNamed(i, "type-mismatch", func(ivs Injector) (int, error) {
return 42, nil
})
// Try to invoke as string when it's actually int
svc, err = invokeAnyByName(i, "type-mismatch")
is.NoError(err) // invokeAnyByName doesn't do type checking, it returns interface{}
is.Equal(42, svc)
// Test provider error
ProvideNamed(i, "provider-error", func(ivs Injector) (string, error) {
return "", assert.AnError
})
svc, err = invokeAnyByName(i, "provider-error")
is.Error(err)
is.Equal(assert.AnError, err)
is.Empty(svc)
// Test provider panic with string
ProvideNamed(i, "provider-panic-string", func(ivs Injector) (string, error) {
panic("test panic")
})
svc, err = invokeAnyByName(i, "provider-panic-string")
is.Error(err)
is.EqualError(err, "DI: test panic")
is.Empty(svc)
// Test provider panic with error
ProvideNamed(i, "provider-panic-error", func(ivs Injector) (string, error) {
panic(assert.AnError)
})
svc, err = invokeAnyByName(i, "provider-panic-error")
is.Error(err)
is.Equal(assert.AnError, err)
is.Empty(svc)
// Test nested scope resolution
childScope := i.Scope("child")
ProvideNamedValue(childScope, "child-service", "child-value")
svc, err = invokeAnyByName(childScope, "child-service")
is.NoError(err)
is.Equal("child-value", svc)
// Test parent scope fallback
svc, err = invokeAnyByName(childScope, "foo")
is.NoError(err)
is.Equal("baz", svc)
// Test invocation hooks
beforeCalled := false
afterCalled := false
hookInjector := NewWithOpts(&InjectorOpts{
HookBeforeInvocation: []func(*Scope, string){
func(scope *Scope, serviceName string) {
beforeCalled = true
},
},
HookAfterInvocation: []func(*Scope, string, error){
func(scope *Scope, serviceName string, err error) {
afterCalled = true
},
},
})
ProvideNamedValue(hookInjector, "hook-test", "hook-value")
svc, err = invokeAnyByName(hookInjector, "hook-test")
is.NoError(err)
is.Equal("hook-value", svc)
is.True(beforeCalled, "BeforeInvocationHook should be called")
is.True(afterCalled, "AfterInvocationHook should be called")
}
func TestInvokeByName(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
// test default injector vs scope
ProvideNamedValue(DefaultRootScope, "foo", "bar")
svc, err := invokeByName[string](nil, "foo")
is.NoError(err)
is.Equal("bar", svc)
// test default injector vs scope
i := New()
ProvideNamedValue(i, "foo", "baz")
svc, err = invokeByName[string](i, "foo")
is.NoError(err)
is.Equal("baz", svc)
// service not found
svc, err = invokeByName[string](nil, "not_found")
is.Error(err)
is.Empty(svc)
is.Contains(err.Error(), "DI: could not find service `not_found`, available services: ")
// test virtual scope wrapper
called := false
ProvideNamed(i, "hello", func(ivs Injector) (string, error) {
// check we received a virtualScope
vs, ok := ivs.(*virtualScope)
is.True(ok)
is.Equal([]string{"hello"}, vs.invokerChain)
is.NotEqual(i, ivs)
// create a dependency/dependent relationship
_, _ = invokeByName[string](ivs, "foo")
called = true
return "foobar", nil
})
_, _ = invokeByName[string](i, "hello")
is.True(called)
// check dependency/dependent relationship
dependencies, dependents := i.dag.explainService(i.self.id, i.self.name, "hello")
is.ElementsMatch([]ServiceDescription{{ScopeID: i.self.id, ScopeName: i.self.name, Service: "foo"}}, dependencies)
is.ElementsMatch([]ServiceDescription{}, dependents)
// test circular dependency
vs := newVirtualScope(i, []string{"foo", "bar"})
svc, err = invokeByName[string](vs, "foo")
is.Error(err)
is.Empty(svc)
is.ErrorIs(err, ErrCircularDependency)
is.EqualError(err, "DI: circular dependency detected: `foo` -> `bar` -> `foo`")
// Test service type mismatch
ProvideNamed(i, "type-mismatch", func(ivs Injector) (int, error) {
return 42, nil
})
// Try to invoke as string when it's actually int
svc, err = invokeByName[string](i, "type-mismatch")
is.Error(err)
is.EqualError(err, "DI: service found, but type mismatch: invoking `string` but registered `int`")
is.Empty(svc)
// Test provider error
ProvideNamed(i, "provider-error", func(ivs Injector) (string, error) {
return "", assert.AnError
})
svc, err = invokeByName[string](i, "provider-error")
is.Error(err)
is.Equal(assert.AnError, err)
is.Empty(svc)
// Test provider panic with string
ProvideNamed(i, "provider-panic-string", func(ivs Injector) (string, error) {
panic("test panic")
})
svc, err = invokeByName[string](i, "provider-panic-string")
is.Error(err)
is.EqualError(err, "DI: test panic")
is.Empty(svc)
// Test provider panic with error
ProvideNamed(i, "provider-panic-error", func(ivs Injector) (string, error) {
panic(assert.AnError)
})
svc, err = invokeByName[string](i, "provider-panic-error")
is.Error(err)
is.Equal(assert.AnError, err)
is.Empty(svc)
// Test nested scope resolution
childScope := i.Scope("child")
ProvideNamedValue(childScope, "child-service", "child-value")
svc, err = invokeByName[string](childScope, "child-service")
is.NoError(err)
is.Equal("child-value", svc)
// Test parent scope fallback
svc, err = invokeByName[string](childScope, "foo")
is.NoError(err)
is.Equal("baz", svc)
// Test invocation hooks
beforeCalled := false
afterCalled := false
hookInjector := NewWithOpts(&InjectorOpts{
HookBeforeInvocation: []func(*Scope, string){
func(scope *Scope, serviceName string) {
beforeCalled = true
},
},
HookAfterInvocation: []func(*Scope, string, error){
func(scope *Scope, serviceName string, err error) {
afterCalled = true
},
},
})
ProvideNamedValue(hookInjector, "hook-test", "hook-value")
svc, err = invokeByName[string](hookInjector, "hook-test")
is.NoError(err)
is.Equal("hook-value", svc)
is.True(beforeCalled, "HookBeforeInvocation should be called")
is.True(afterCalled, "HookAfterInvocation should be called")
// Test with different generic types
ProvideNamedValue(i, "int-value", 42)
intVal, err := invokeByName[int](i, "int-value")
is.NoError(err)
is.Equal(42, intVal)
// Test with struct types
ProvideNamedValue(i, "struct-value", &eagerTest{foobar: "test"})
structVal, err := invokeByName[*eagerTest](i, "struct-value")
is.NoError(err)
is.Equal("test", structVal.foobar)
}
func TestInvokeByGenericType(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
// test default injector vs scope
// Note: Skipping DefaultRootScope tests due to parallel test conflicts
// test default injector vs scope
i := New()
ProvideValue(i, &lazyTest{foobar: "baz"})
svc2, err := invokeByGenericType[*lazyTest](i)
is.Equal(&lazyTest{foobar: "baz"}, svc2)
is.NoError(err)
// service not found
svcX, err := invokeByGenericType[string](i)
is.Empty(svcX)
is.Error(err)
is.Contains(err.Error(), "DI: could not find service satisfying interface `string`, available services: `*github.com/samber/do/v2.lazyTest`")
// test virtual scope wrapper
called := false
Provide(i, func(ivs Injector) (*eagerTest, error) {
// check we received a virtualScope
vs, ok := ivs.(*virtualScope)
is.True(ok)
is.Equal([]string{"*github.com/samber/do/v2.eagerTest"}, vs.invokerChain)
is.NotEqual(i, ivs)
// create a dependency/dependent relationship
_, _ = invokeByGenericType[*lazyTest](ivs)
called = true
return &eagerTest{}, nil
})
_, _ = invokeByGenericType[*eagerTest](i)
is.True(called)
// check dependency/dependent relationship
dependencies, dependents := i.dag.explainService(i.self.id, i.self.name, "*github.com/samber/do/v2.eagerTest")
is.ElementsMatch([]ServiceDescription{{ScopeID: i.self.id, ScopeName: i.self.name, Service: "*github.com/samber/do/v2.lazyTest"}}, dependencies)
is.ElementsMatch([]ServiceDescription{}, dependents)
// test circular dependency
vs := newVirtualScope(i, []string{"*github.com/samber/do/v2.eagerTest", "bar"})
var svc1 *eagerTest
svc1, err = invokeByGenericType[*eagerTest](vs)
is.Error(err)
is.Empty(svc1)
is.ErrorIs(err, ErrCircularDependency)
is.EqualError(err, "DI: circular dependency detected: `*github.com/samber/do/v2.eagerTest` -> `bar` -> `*github.com/samber/do/v2.eagerTest`")
// Test with nil injector (should use default root scope)
// Note: Skipping DefaultRootScope tests due to parallel test conflicts
// Test service not found for interface
svc4, err := invokeByGenericType[Healthchecker](i)
is.Empty(svc4)
is.Error(err)
is.Contains(err.Error(), "DI: could not find service satisfying interface `github.com/samber/do/v2.Healthchecker`")
// Test provider error with different service type
// Note: Skipping provider error tests due to service conflicts
// Test nested scope resolution
childScope := i.Scope("child")
ProvideValue(childScope, &lazyTest{foobar: "child-lazy"})
svc8, err := invokeByGenericType[*lazyTest](childScope)
is.NoError(err)
is.Equal("child-lazy", svc8.foobar)
// Test parent scope fallback
// Note: Child scope finds its own service first, which is correct behavior
svc9, err := invokeByGenericType[*lazyTest](childScope)
is.NoError(err)
is.Equal("child-lazy", svc9.foobar) // Should get the child scope service
// Test invocation hooks
beforeCalled := false
afterCalled := false
hookInjector := NewWithOpts(&InjectorOpts{
HookBeforeInvocation: []func(*Scope, string){
func(scope *Scope, serviceName string) {
beforeCalled = true
},
},
HookAfterInvocation: []func(*Scope, string, error){
func(scope *Scope, serviceName string, err error) {
afterCalled = true
},
},
})
ProvideValue(hookInjector, &eagerTest{foobar: "hook-test"})
svc10, err := invokeByGenericType[*eagerTest](hookInjector)
is.NoError(err)
is.Equal("hook-test", svc10.foobar)
is.True(beforeCalled, "HookBeforeInvocation should be called")
is.True(afterCalled, "HookAfterInvocation should be called")
// Test with primitive types
ProvideValue(i, 42)
intVal, err := invokeByGenericType[int](i)
is.NoError(err)
is.Equal(42, intVal)
// Test with interface types
Provide(i, func(ivs Injector) (*lazyTestHeathcheckerOK, error) {
return &lazyTestHeathcheckerOK{foobar: "healthchecker"}, nil
})
healthchecker, err := invokeByGenericType[Healthchecker](i)
is.NoError(err)
is.Equal("healthchecker", healthchecker.(*lazyTestHeathcheckerOK).foobar)
// Test service selection when multiple services match
Provide(i, func(ivs Injector) (*lazyTestHeathcheckerKO, error) {
return &lazyTestHeathcheckerKO{foobar: "healthchecker2"}, nil
})
// Should select the first matching service (order is not guaranteed, but should work)
healthchecker2, err := invokeByGenericType[Healthchecker](i)
is.NoError(err)
// Use safe type assertion to check which type we got
if okType, ok := healthchecker2.(*lazyTestHeathcheckerOK); ok {
is.Equal("healthchecker", okType.foobar)
} else if koType, ok := healthchecker2.(*lazyTestHeathcheckerKO); ok {
is.Equal("healthchecker2", koType.foobar)
} else {
is.Fail("Unexpected healthchecker type")
}
}
func TestInvokeByName_race(t *testing.T) {
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
injector := New()
child := injector.Scope("child")
Provide(injector, func(i Injector) (int, error) {
time.Sleep(3 * time.Millisecond)
return 42, nil
})
Provide(injector, func(i Injector) (*lazyTest, error) {
time.Sleep(3 * time.Millisecond)
return &lazyTest{}, nil
})
var wg sync.WaitGroup
wg.Add(5)
for i := 0; i < 5; i++ {
go func(j int) {
_, err1 := invokeByName[int](injector, NameOf[int]())
_, err2 := invokeByName[*lazyTest](child, NameOf[*lazyTest]())
is.NoError(err1)
is.NoError(err2)
wg.Done()
}(i)
}
wg.Wait()
}
func TestInvokeByGenericType_race(t *testing.T) {
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
injector := New()
child := injector.Scope("child")
Provide(injector, func(i Injector) (int, error) {
time.Sleep(3 * time.Millisecond)
return 42, nil
})
Provide(injector, func(i Injector) (*lazyTest, error) {
time.Sleep(3 * time.Millisecond)
return &lazyTest{}, nil
})
var wg sync.WaitGroup
wg.Add(5)
for i := 0; i < 5; i++ {
go func(j int) {
_, err1 := invokeByGenericType[int](injector)
_, err2 := invokeByGenericType[*lazyTest](child)
is.NoError(err1)
is.NoError(err2)
wg.Done()
}(i)
}
wg.Wait()
}
func TestInvokeByTags(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
i := New()
ProvideValue(i, &eagerTest{foobar: "foobar"})
// no dependencies
err := invokeByTags(i, "*myStruct", reflect.ValueOf(&eagerTest{}), false)
is.NoError(err)
// not pointer
err = invokeByTags(i, "*myStruct", reflect.ValueOf(eagerTest{}), false)
is.Equal("DI: must be a pointer to a struct", err.Error())
// exported field - generic type
type hasExportedEagerTestDependency struct {
EagerTest *eagerTest `do:""`
}
test1 := hasExportedEagerTestDependency{}
err = invokeByTags(i, "*myStruct", reflect.ValueOf(&test1), false)
is.NoError(err)
is.Equal("foobar", test1.EagerTest.foobar)
// unexported field
type hasNonExportedEagerTestDependency struct {
eagerTest *eagerTest `do:""`
}
test2 := hasNonExportedEagerTestDependency{}
err = invokeByTags(i, "*myStruct", reflect.ValueOf(&test2), false)
is.NoError(err)
is.Equal("foobar", test2.eagerTest.foobar)
// not found
type dependencyNotFound struct {
eagerTest *hasNonExportedEagerTestDependency `do:""` //nolint:unused
}
test3 := dependencyNotFound{}
err = invokeByTags(i, "*myStruct", reflect.ValueOf(&test3), false)
is.Equal(serviceNotFound(i, ErrServiceNotFound, []string{inferServiceName[*hasNonExportedEagerTestDependency]()}).Error(), err.Error())
// use tag
type namedDependency struct {
eagerTest *eagerTest `do:"int"` //nolint:unused
}
test4 := namedDependency{}
err = invokeByTags(i, "*myStruct", reflect.ValueOf(&test4), false)
is.Equal(serviceNotFound(i, ErrServiceNotFound, []string{inferServiceName[int]()}).Error(), err.Error())
// named service
ProvideNamedValue(i, "foobar", 42)
type namedService struct {
EagerTest int `do:"foobar"`
}
test5 := namedService{}
err = invokeByTags(i, "*myStruct", reflect.ValueOf(&test5), false)
is.NoError(err)
is.Equal(42, test5.EagerTest)
// use tag but wrong type
type namedDependencyButTypeMismatch struct {
EagerTest *int `do:"*github.com/samber/do/v2.eagerTest"`
}
test6 := namedDependencyButTypeMismatch{}
err = invokeByTags(i, "*myStruct", reflect.ValueOf(&test6), false)
is.Equal("DI: `*github.com/samber/do/v2.eagerTest` is not assignable to field `*myStruct.EagerTest`", err.Error())
// use a custom tag
i = NewWithOpts(&InjectorOpts{StructTagKey: "hello"})
ProvideNamedValue(i, "foobar", 42)
type namedServiceWithCustomTag struct {
EagerTest int `hello:"foobar"`
}
test7 := namedServiceWithCustomTag{}
err = invokeByTags(i, "*myStruct", reflect.ValueOf(&test7), false)
is.NoError(err)
is.Equal(42, test7.EagerTest)
}
func TestInvokeByTags_ImplicitAliasing_FallbackOnNotFound(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
i := New()
type foobar struct {
Dep Healthchecker `do:""`
}
// First, declare a service with no dependencies
s := foobar{}
err := invokeByTags(i, "*foobar", reflect.ValueOf(&s), true)
is.Error(err)
is.Equal("DI: could not find service `github.com/samber/do/v2.Healthchecker`, no service available", err.Error())
is.Nil(s.Dep)
// Now, declare a service with the right type
Provide(i, func(injector Injector) (*lazyTestHeathcheckerOK, error) {
return &lazyTestHeathcheckerOK{foobar: "foobar"}, nil
})
s = foobar{}
err = invokeByTags(i, "*foobar", reflect.ValueOf(&s), true)
is.NoError(err)
is.NotNil(s.Dep)
is.Equal("foobar", s.Dep.(*lazyTestHeathcheckerOK).foobar)
// Now, declare a service with an interface assignable to interface
i = New()
Override(i, func(injector Injector) (iTestHeathchecker, error) {
return &lazyTestHeathcheckerOK{foobar: "foobar"}, nil
})
s = foobar{}
err = invokeByTags(i, "*foobar", reflect.ValueOf(&s), true)
is.NoError(err)
is.NotNil(s.Dep)
is.Equal("foobar", s.Dep.(*lazyTestHeathcheckerOK).foobar)
}
func TestInvokeByTags_ImplicitAliasing_NoFallbackOnOtherErrors(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
i := New()
Provide(i, func(injector Injector) (*lazyTestHeathcheckerOK, error) {
return &lazyTestHeathcheckerOK{foobar: "foobar"}, nil
})
// First, lets check the situation the service is not found
type foobar struct {
Dep Healthchecker `do:"bad"`
}
s := foobar{}
err := invokeByTags(i, "*foobar", reflect.ValueOf(&s), true)
is.Error(err)
is.Equal("DI: could not find service `bad`, available services: `*github.com/samber/do/v2.lazyTestHeathcheckerOK`", err.Error())
is.Nil(s.Dep)
// Now, declare a service with a wrong type
ProvideNamed(i, "bad", func(ivs Injector) (*eagerTest, error) {
return &eagerTest{}, nil
})
s = foobar{}
err = invokeByTags(i, "*foobar", reflect.ValueOf(&s), true)
is.Error(err)
is.Equal("DI: `bad` is not assignable to field `*foobar.Dep`", err.Error())
is.Nil(s.Dep)
// Now, declare a service with the right type, but with provider error
OverrideNamed(i, "bad", func(ivs Injector) (*eagerTest, error) {
return nil, fmt.Errorf("boom")
})
s = foobar{}
err = invokeByTags(i, "*foobar", reflect.ValueOf(&s), true)
is.Error(err)
is.Equal("boom", err.Error())
is.Nil(s.Dep)
}
func TestServiceNotFound(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
rootScope := New()
// create children
child1 := rootScope.Scope("child1")
child2a := child1.Scope("child2a")
child2b := child1.Scope("child2b")
child3 := child2a.Scope("child3")
err := serviceNotFound(child1, ErrServiceNotFound, []string{"not-found"})
is.Error(err)
is.ErrorIs(err, ErrServiceNotFound)
is.EqualError(err, "DI: could not find service `not-found`, no service available")
err = serviceNotFound(child1, ErrServiceNotFound, []string{"not-found1", "not-found2"})
is.Error(err)
is.ErrorIs(err, ErrServiceNotFound)
is.EqualError(err, "DI: could not find service `not-found2`, no service available, path: `not-found1` -> `not-found2`")
rootScope.serviceSet("root-a", newServiceLazy("root-a", func(i Injector) (int, error) { return 0, nil }))
child1.serviceSet("child1-a", newServiceLazy("child1-a", func(i Injector) (int, error) { return 1, nil }))
child2a.serviceSet("child2a-a", newServiceLazy("child2a-a", func(i Injector) (int, error) { return 2, nil }))
child2a.serviceSet("child2a-b", newServiceLazy("child2a-b", func(i Injector) (int, error) { return 3, nil }))
child2b.serviceSet("child2b-a", newServiceLazy("child2b-a", func(i Injector) (int, error) { return 4, nil }))
child3.serviceSet("child3-a", newServiceLazy("child3-a", func(i Injector) (int, error) { return 5, nil }))
err = serviceNotFound(child1, ErrServiceNotFound, []string{"not-found"})
is.Error(err)
is.ErrorIs(err, ErrServiceNotFound)
is.EqualError(err, "DI: could not find service `not-found`, available services: `child1-a`, `root-a`")
err = serviceNotFound(child1, ErrServiceNotFound, []string{"not-found1", "not-found2"})
is.Error(err)
is.ErrorIs(err, ErrServiceNotFound)
is.EqualError(err, "DI: could not find service `not-found2`, available services: `child1-a`, `root-a`, path: `not-found1` -> `not-found2`")
// Test service ordering in error messages
// Create services in different order to test sorting
rootScope.serviceSet("z-service", newServiceLazy("z-service", func(i Injector) (int, error) { return 10, nil }))
rootScope.serviceSet("a-service", newServiceLazy("a-service", func(i Injector) (int, error) { return 11, nil }))
rootScope.serviceSet("m-service", newServiceLazy("m-service", func(i Injector) (int, error) { return 12, nil }))
err = serviceNotFound(rootScope, ErrServiceNotFound, []string{"not-found"})
is.Error(err)
is.ErrorIs(err, ErrServiceNotFound)
// Services should be sorted alphabetically
is.Contains(err.Error(), "available services: `a-service`, `m-service`, `root-a`, `z-service`")
// Test service ordering across scopes
child1.serviceSet("x-service", newServiceLazy("x-service", func(i Injector) (int, error) { return 13, nil }))
child1.serviceSet("b-service", newServiceLazy("b-service", func(i Injector) (int, error) { return 14, nil }))
err = serviceNotFound(child1, ErrServiceNotFound, []string{"not-found"})
is.Error(err)
is.ErrorIs(err, ErrServiceNotFound)
// Services should be listed (order may vary due to sorting)
errorMsg := err.Error()
is.Contains(errorMsg, "b-service")
is.Contains(errorMsg, "child1-a")
is.Contains(errorMsg, "x-service")
is.Contains(errorMsg, "a-service")
is.Contains(errorMsg, "m-service")
is.Contains(errorMsg, "root-a")
is.Contains(errorMsg, "z-service")
// Test service ordering with special characters and numbers
rootScope.serviceSet("service-1", newServiceLazy("service-1", func(i Injector) (int, error) { return 15, nil }))
rootScope.serviceSet("service_2", newServiceLazy("service_2", func(i Injector) (int, error) { return 16, nil }))
rootScope.serviceSet("Service3", newServiceLazy("Service3", func(i Injector) (int, error) { return 17, nil }))
err = serviceNotFound(rootScope, ErrServiceNotFound, []string{"not-found"})
is.Error(err)
is.ErrorIs(err, ErrServiceNotFound)
// Services should be sorted with numbers, underscores, hyphens, and case sensitivity
is.Contains(err.Error(), "available services: `Service3`, `a-service`, `m-service`, `root-a`, `service-1`, `service_2`, `z-service`")
// Test empty injector
emptyInjector := New()
err = serviceNotFound(emptyInjector, ErrServiceNotFound, []string{"not-found"})
is.Error(err)
is.ErrorIs(err, ErrServiceNotFound)
is.EqualError(err, "DI: could not find service `not-found`, no service available")
// Test with different error types
err = serviceNotFound(child1, ErrServiceNotMatch, []string{"not-found"})
is.Error(err)
is.ErrorIs(err, ErrServiceNotMatch)
is.Contains(err.Error(), "DI: could not find service satisfying interface `not-found`")
// Test with very long service names
longName := "very-long-service-name-that-exceeds-normal-length-limits-for-testing-purposes"
rootScope.serviceSet(longName, newServiceLazy(longName, func(i Injector) (int, error) { return 18, nil }))
err = serviceNotFound(rootScope, ErrServiceNotFound, []string{"not-found"})
is.Error(err)
is.Contains(err.Error(), longName)
// Test with unicode service names
unicodeName := "service-测试-unicode"
rootScope.serviceSet(unicodeName, newServiceLazy(unicodeName, func(i Injector) (int, error) { return 19, nil }))
err = serviceNotFound(rootScope, ErrServiceNotFound, []string{"not-found"})
is.Error(err)
is.Contains(err.Error(), unicodeName)
}
func TestHandleProviderPanic(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
is.NotPanics(func() {
// ok
svc, err := handleProviderPanic(func(i Injector) (int, error) {
return 42, nil
}, nil)
is.NoError(err)
is.Equal(42, svc)
// should return an error
svc, err = handleProviderPanic(func(i Injector) (int, error) {
return 0, assert.AnError
}, nil)
is.Equal(assert.AnError, err)
is.Equal(0, svc)
// shoud not return 42
svc, err = handleProviderPanic(func(i Injector) (int, error) {
return 42, assert.AnError
}, nil)
is.Equal(assert.AnError, err)
is.Equal(0, svc)
// panics with string
svc, err = handleProviderPanic(func(i Injector) (int, error) {
panic("aïe")
}, nil)
is.EqualError(err, "DI: aïe")
is.Equal(0, svc)
// panics with error
svc, err = handleProviderPanic(func(i Injector) (int, error) {
panic(assert.AnError)
}, nil)
is.Equal(assert.AnError, err)
is.Equal(0, svc)
})
}