Repository navigation
Expand file tree
/
Copy pathservice_lazy_test.go
More file actions
907 lines (753 loc) · 27.1 KB
/
Copy pathservice_lazy_test.go
File metadata and controls
907 lines (753 loc) · 27.1 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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
package do
import (
"context"
"fmt"
"testing"
"time"
"github.com/samber/do/v2/stacktrace"
"github.com/stretchr/testify/assert"
)
type lazyTest struct {
foobar string
}
// Alias to HealthChecker.
// Used for testing interface implements interface.
type iTestHeathchecker interface {
HealthCheck() error
}
var _ Healthchecker = (*lazyTestHeathcheckerOK)(nil)
type lazyTestHeathcheckerOK struct {
foobar string
}
func (t *lazyTestHeathcheckerOK) HealthCheck() error {
return nil
}
var _ Healthchecker = (*lazyTestHeathcheckerKO)(nil)
type lazyTestHeathcheckerKO struct {
foobar string
}
func (t *lazyTestHeathcheckerKO) HealthCheck() error {
return assert.AnError
}
var _ HealthcheckerWithContext = (*lazyTestHeathcheckerKOCtx)(nil)
type lazyTestHeathcheckerKOCtx struct {
foobar string
}
func (t *lazyTestHeathcheckerKOCtx) HealthCheck(ctx context.Context) error {
return assert.AnError
}
var _ Healthchecker = (*lazyTestHeathcheckerOKTimeout)(nil)
type lazyTestHeathcheckerOKTimeout struct {
foobar string
}
func (t *lazyTestHeathcheckerOKTimeout) HealthCheck() error {
time.Sleep(20 * time.Millisecond)
return nil
}
var _ ShutdownerWithContextAndError = (*lazyTestShutdownerOK)(nil)
type lazyTestShutdownerOK struct {
foobar string
}
func (t *lazyTestShutdownerOK) Shutdown(ctx context.Context) error {
return nil
}
var _ ShutdownerWithError = (*lazyTestShutdownerKO)(nil)
type lazyTestShutdownerKO struct {
foobar string
}
func (t *lazyTestShutdownerKO) Shutdown() error {
return assert.AnError
}
var _ ShutdownerWithContextAndError = (*lazyTestShutdownerKOCtx)(nil)
type lazyTestShutdownerKOCtx struct {
foobar string
}
func (t *lazyTestShutdownerKOCtx) Shutdown(ctx context.Context) error {
return assert.AnError
}
// Test services for context value propagation in service lazy
type contextValueHealthcheckerLazy struct{}
func (c *contextValueHealthcheckerLazy) HealthCheck(ctx context.Context) error {
value := ctx.Value(ctxTestKey)
if value != "healthcheck-value" {
return fmt.Errorf("test-key not found or value is incorrect")
}
return nil
}
type contextValueShutdownerLazy struct{}
func (c *contextValueShutdownerLazy) Shutdown(ctx context.Context) error {
value := ctx.Value(ctxTestKey)
if value != "shutdown-value" {
return fmt.Errorf("test-key not found or value is incorrect")
}
return nil
}
func TestNewServiceLazy(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
// Test creating a lazy service with int provider
provider1 := func(i Injector) (int, error) {
return 42, nil
}
service1 := newServiceLazy("test-service-1", provider1)
is.NotNil(service1)
is.Equal("test-service-1", service1.getName())
is.Equal("int", service1.getTypeName())
is.Equal(ServiceTypeLazy, service1.getServiceType())
is.False(service1.built)
is.Equal(0, service1.instance) // Zero value for int
// Test creating a lazy service with struct provider
testStruct := lazyTest{foobar: "test"}
provider2 := func(i Injector) (lazyTest, error) {
return testStruct, nil
}
service2 := newServiceLazy("test-service-2", provider2)
is.NotNil(service2)
is.Equal("test-service-2", service2.getName())
is.Equal("github.com/samber/do/v2.lazyTest", service2.getTypeName())
is.Equal(ServiceTypeLazy, service2.getServiceType())
is.False(service2.built)
is.Equal(lazyTest{}, service2.instance) // Zero value for struct
// Test creating a lazy service with pointer provider
provider3 := func(i Injector) (*lazyTest, error) {
return &testStruct, nil
}
service3 := newServiceLazy("test-service-3", provider3)
is.NotNil(service3)
is.Equal("test-service-3", service3.getName())
is.Equal("*github.com/samber/do/v2.lazyTest", service3.getTypeName())
is.Equal(ServiceTypeLazy, service3.getServiceType())
// Test creating a lazy service with interface provider
provider4 := func(i Injector) (Healthchecker, error) {
return &lazyTestHeathcheckerOK{foobar: "health"}, nil
}
service4 := newServiceLazy("test-service-4", provider4)
is.NotNil(service4)
is.Equal("test-service-4", service4.getName())
is.Equal("github.com/samber/do/v2.Healthchecker", service4.getTypeName())
is.Equal(ServiceTypeLazy, service4.getServiceType())
// Test that services are not built initially
is.False(service1.built)
is.False(service2.built)
is.False(service3.built)
is.False(service4.built)
}
func TestServiceLazy_getName(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
test := lazyTest{foobar: "foobar"}
provider1 := func(i Injector) (int, error) {
return 42, nil
}
provider2 := func(i Injector) (lazyTest, error) {
return test, nil
}
service1 := newServiceLazy("foobar1", provider1)
is.Equal("foobar1", service1.getName())
service2 := newServiceLazy("foobar2", provider2)
is.Equal("foobar2", service2.getName())
}
func TestServiceLazy_getTypeName(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
test := lazyTest{foobar: "foobar"}
provider1 := func(i Injector) (int, error) {
return 42, nil
}
provider2 := func(i Injector) (lazyTest, error) {
return test, nil
}
service1 := newServiceLazy("foobar1", provider1)
is.Equal("int", service1.getTypeName())
service2 := newServiceLazy("foobar2", provider2)
is.Equal("github.com/samber/do/v2.lazyTest", service2.getTypeName())
}
func TestServiceLazy_getServiceType(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
test := lazyTest{foobar: "foobar"}
provider1 := func(i Injector) (int, error) {
return 42, nil
}
provider2 := func(i Injector) (lazyTest, error) {
return test, nil
}
service1 := newServiceLazy("foobar1", provider1)
is.Equal(ServiceTypeLazy, service1.getServiceType())
service2 := newServiceLazy("foobar2", provider2)
is.Equal(ServiceTypeLazy, service2.getServiceType())
}
func TestServiceLazy_getReflectType(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
test := lazyTest{foobar: "foobar"}
provider1 := func(i Injector) (int, error) {
return 42, nil
}
provider2 := func(i Injector) (lazyTest, error) {
return test, nil
}
provider3 := func(i Injector) (Healthchecker, error) {
return nil, nil
}
provider4 := func(i Injector) (*lazyTest, error) {
return &test, nil
}
service1 := newServiceLazy("foobar1", provider1)
is.Equal("int", service1.getReflectType().String())
service2 := newServiceLazy("foobar2", provider2)
is.Equal(pkgName+".lazyTest", service2.getReflectType().String())
service3 := newServiceLazy("foobar3", provider3)
is.Equal(pkgName+".Healthchecker", service3.getReflectType().String())
service4 := newServiceLazy("foobar1", provider4)
is.Equal("*"+pkgName+".lazyTest", service4.getReflectType().String())
}
func TestServiceLazy_getInstanceAny(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
test := lazyTest{foobar: "foobar"}
provider1 := func(i Injector) (int, error) {
return 42, nil
}
provider2 := func(i Injector) (lazyTest, error) {
return test, nil
}
provider3 := func(i Injector) (int, error) {
panic("error")
}
provider4 := func(i Injector) (int, error) {
panic(fmt.Errorf("error"))
}
provider5 := func(i Injector) (int, error) {
return 42, fmt.Errorf("error")
}
i := New()
// basic type
service1 := newServiceLazy("foobar", provider1)
instance1, err1 := service1.getInstanceAny(i)
is.NoError(err1)
is.Equal(42, instance1)
// struct
service2 := newServiceLazy("hello", provider2)
instance2, err2 := service2.getInstanceAny(i)
is.NoError(err2)
is.Equal(test, instance2)
// provider panics, but panic is catched by getInstanceAny
is.NotPanics(func() {
service3 := newServiceLazy("baz", provider3)
_, _ = service3.getInstanceAny(i)
})
// provider panics, but panic is catched by getInstanceAny
is.NotPanics(func() {
service4 := newServiceLazy("plop", provider4)
instance4, err4 := service4.getInstanceAny(i)
is.Error(err4)
is.Empty(instance4)
expected := fmt.Errorf("error")
is.Equal(expected, err4)
})
// provider returning error
is.NotPanics(func() {
service5 := newServiceLazy("plop", provider5)
instance5, err5 := service5.getInstanceAny(i)
is.Error(err5)
is.Empty(instance5)
expected := fmt.Errorf("error")
is.Equal(expected, err5)
})
}
func TestServiceLazy_getInstance(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
test := lazyTest{foobar: "foobar"}
provider1 := func(i Injector) (int, error) {
return 42, nil
}
provider2 := func(i Injector) (lazyTest, error) {
return test, nil
}
provider3 := func(i Injector) (int, error) {
panic("error")
}
provider4 := func(i Injector) (int, error) {
panic(fmt.Errorf("error"))
}
provider5 := func(i Injector) (int, error) {
return 42, fmt.Errorf("error")
}
i := New()
// basic type
service1 := newServiceLazy("foobar", provider1)
instance1, err1 := service1.getInstance(i)
is.NoError(err1)
is.Equal(42, instance1)
// struct
service2 := newServiceLazy("hello", provider2)
instance2, err2 := service2.getInstance(i)
is.NoError(err2)
is.Equal(test, instance2)
// provider panics, but panic is catched by getInstance
is.NotPanics(func() {
service3 := newServiceLazy("baz", provider3)
_, _ = service3.getInstance(i)
})
// provider panics, but panic is catched by getInstance
is.NotPanics(func() {
service4 := newServiceLazy("plop", provider4)
instance4, err4 := service4.getInstance(i)
is.Error(err4)
is.Empty(instance4)
expected := fmt.Errorf("error")
is.Equal(expected, err4)
})
// provider returning error
is.NotPanics(func() {
service5 := newServiceLazy("plop", provider5)
instance5, err5 := service5.getInstance(i)
is.Error(err5)
is.Empty(instance5)
expected := fmt.Errorf("error")
is.Equal(expected, err5)
})
}
func TestServiceLazy_build(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
test := lazyTest{foobar: "foobar"}
provider1 := func(i Injector) (int, error) {
return 42, nil
}
provider2 := func(i Injector) (lazyTest, error) {
return test, nil
}
provider3 := func(i Injector) (int, error) {
panic("error")
}
provider4 := func(i Injector) (int, error) {
panic(fmt.Errorf("error"))
}
provider5 := func(i Injector) (int, error) {
return 42, fmt.Errorf("error")
}
i := New()
// basic type
service1 := newServiceLazy("foobar", provider1)
is.False(service1.built)
is.Empty(service1.buildTime)
err1 := service1.build(i)
is.True(service1.built)
is.NotEmpty(service1.buildTime)
is.NoError(err1)
// struct
service2 := newServiceLazy("hello", provider2)
is.False(service2.built)
is.Empty(service2.buildTime)
err2 := service2.build(i)
is.True(service2.built)
is.NotEmpty(service2.buildTime)
is.NoError(err2)
// provider panics, but panic is catched by getInstance
is.NotPanics(func() {
service3 := newServiceLazy("baz", provider3)
is.False(service3.built)
is.Empty(service3.buildTime)
_ = service3.build(i)
is.False(service3.built)
is.Empty(service3.buildTime)
})
// provider panics, but panic is catched by getInstance
is.NotPanics(func() {
service4 := newServiceLazy("plop", provider4)
is.False(service4.built)
is.Empty(service4.buildTime)
err4 := service4.build(i)
is.False(service4.built)
is.Empty(service4.buildTime)
is.Error(err4)
is.Equal(fmt.Errorf("error"), err4)
})
// provider returning error
is.NotPanics(func() {
service5 := newServiceLazy("plop", provider5)
is.False(service5.built)
is.Empty(service5.buildTime)
err5 := service5.build(i)
is.False(service5.built)
is.Empty(service5.buildTime)
is.Error(err5)
is.Equal(fmt.Errorf("error"), err5)
})
}
func TestServiceLazy_isHealthchecker(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
// no healthcheck
service1 := newServiceLazy("foobar", func(i Injector) (lazyTest, error) {
return lazyTest{foobar: "foobar"}, nil
})
is.False(service1.isHealthchecker())
// healthcheck ok
service2 := newServiceLazy("foobar", func(i Injector) (*lazyTestHeathcheckerOK, error) {
return &lazyTestHeathcheckerOK{foobar: "foobar"}, nil
})
is.False(service2.isHealthchecker())
_, _ = service2.getInstance(nil)
is.True(service2.isHealthchecker())
// healthcheck ko
service3 := newServiceLazy("foobar", func(i Injector) (*lazyTestHeathcheckerKO, error) {
return &lazyTestHeathcheckerKO{foobar: "foobar"}, nil
})
is.False(service3.isHealthchecker())
_, _ = service3.getInstance(nil)
is.True(service3.isHealthchecker())
}
// @TODO: missing tests for context
func TestServiceLazy_healthcheck(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
ctx := context.Background()
// no healthcheck
service1 := newServiceLazy("foobar", func(i Injector) (lazyTest, error) {
return lazyTest{foobar: "foobar"}, nil
})
is.NoError(service1.healthcheck(ctx))
_, _ = service1.getInstance(nil)
is.NoError(service1.healthcheck(ctx))
// healthcheck ok
service2 := newServiceLazy("foobar", func(i Injector) (*lazyTestHeathcheckerOK, error) {
return &lazyTestHeathcheckerOK{foobar: "foobar"}, nil
})
is.NoError(service2.healthcheck(ctx))
_, _ = service2.getInstance(nil)
is.NoError(service2.healthcheck(ctx))
// healthcheck ko
service3 := newServiceLazy("foobar", func(i Injector) (*lazyTestHeathcheckerKO, error) {
return &lazyTestHeathcheckerKO{foobar: "foobar"}, nil
})
is.NoError(service3.healthcheck(ctx))
_, _ = service3.getInstance(nil)
is.Equal(assert.AnError, service3.healthcheck(ctx))
// Test with context scenarios
// Test with canceled context
canceledCtx, cancel := context.WithCancel(context.Background())
cancel()
service4 := newServiceLazy("foobar", func(i Injector) (*lazyTestHeathcheckerOK, error) {
return &lazyTestHeathcheckerOK{foobar: "foobar"}, nil
})
_, _ = service4.getInstance(nil)
err := service4.healthcheck(canceledCtx)
is.Error(err)
is.ErrorContains(err, "context canceled")
// Test with timeout context
timeoutCtx, cancel2 := context.WithTimeout(context.Background(), 1*time.Nanosecond)
defer cancel2()
time.Sleep(2 * time.Millisecond)
err2 := service4.healthcheck(timeoutCtx)
is.Error(err2)
is.ErrorContains(err2, "context deadline exceeded")
// Test with value context - verify context value is received
valueCtx := context.WithValue(context.Background(), ctxTestKey, "healthcheck-value")
serviceWithContext := newServiceLazy("foobar", func(i Injector) (*contextValueHealthcheckerLazy, error) {
return &contextValueHealthcheckerLazy{}, nil
})
_, _ = serviceWithContext.getInstance(nil)
err3 := serviceWithContext.healthcheck(valueCtx)
is.NoError(err3) // Should work normally when context value is correct
// Test with incorrect context value - verify context value is checked
incorrectValueCtx := context.WithValue(context.Background(), ctxTestKey, "wrong-value")
err4 := serviceWithContext.healthcheck(incorrectValueCtx)
is.Error(err4) // Should fail when context value is incorrect
is.ErrorContains(err4, "test-key not found or value is incorrect")
}
// @TODO: missing tests for context
func TestServiceLazy_isShutdowner(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
// no shutdown
service1 := newServiceLazy("foobar", func(i Injector) (lazyTest, error) {
return lazyTest{foobar: "foobar"}, nil
})
is.False(service1.isShutdowner())
// shutdown ok
service2 := newServiceLazy("foobar", func(i Injector) (*lazyTestShutdownerOK, error) {
return &lazyTestShutdownerOK{foobar: "foobar"}, nil
})
is.False(service2.isShutdowner())
_, _ = service2.getInstance(nil)
is.True(service2.isShutdowner())
// shutdown ko
service3 := newServiceLazy("foobar", func(i Injector) (*lazyTestShutdownerKO, error) {
return &lazyTestShutdownerKO{foobar: "foobar"}, nil
})
is.False(service3.isShutdowner())
_, _ = service3.getInstance(nil)
is.True(service3.isShutdowner())
}
// @TODO: missing tests for context
func TestServiceLazy_shutdown(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
ctx := context.Background()
// no shutdown
service1 := newServiceLazy("foobar", func(i Injector) (lazyTest, error) {
return lazyTest{foobar: "foobar"}, nil
})
is.False(service1.built)
is.NoError(service1.shutdown(ctx))
_, _ = service1.getInstance(nil)
is.True(service1.built)
is.NoError(service1.shutdown(ctx))
is.False(service1.built)
// shutdown ok
service2 := newServiceLazy("foobar", func(i Injector) (*lazyTestShutdownerOK, error) {
return &lazyTestShutdownerOK{foobar: "foobar"}, nil
})
is.False(service2.built)
is.NoError(service2.shutdown(ctx))
_, _ = service2.getInstance(nil)
is.True(service2.built)
is.NoError(service2.shutdown(ctx))
is.False(service2.built)
// shutdown ko
service3 := newServiceLazy("foobar", func(i Injector) (*lazyTestShutdownerKO, error) {
return &lazyTestShutdownerKO{foobar: "foobar"}, nil
})
is.False(service3.built)
is.NoError(service3.shutdown(ctx))
_, _ = service3.getInstance(nil)
is.True(service3.built)
is.Equal(assert.AnError, service3.shutdown(ctx))
is.False(service3.built)
// Test with context scenarios
// Test with canceled context
canceledCtx, cancel := context.WithCancel(context.Background())
cancel()
service4 := newServiceLazy("foobar", func(i Injector) (*lazyTestShutdownerOK, error) {
return &lazyTestShutdownerOK{foobar: "foobar"}, nil
})
_, _ = service4.getInstance(nil)
err := service4.shutdown(canceledCtx)
is.Error(err)
is.ErrorContains(err, "context canceled")
// Test with timeout context
timeoutCtx, cancel2 := context.WithTimeout(context.Background(), 1*time.Nanosecond)
defer cancel2()
time.Sleep(2 * time.Millisecond)
service5 := newServiceLazy("foobar", func(i Injector) (*lazyTestShutdownerOK, error) {
return &lazyTestShutdownerOK{foobar: "foobar"}, nil
})
_, _ = service5.getInstance(nil)
err2 := service5.shutdown(timeoutCtx)
is.Error(err2)
is.ErrorContains(err2, "context deadline exceeded")
// Test with value context - verify context value is received
valueCtx := context.WithValue(context.Background(), ctxTestKey, "shutdown-value")
serviceWithContext := newServiceLazy("foobar", func(i Injector) (*contextValueShutdownerLazy, error) {
return &contextValueShutdownerLazy{}, nil
})
_, _ = serviceWithContext.getInstance(nil)
err3 := serviceWithContext.shutdown(valueCtx)
is.NoError(err3) // Should work normally when context value is correct
// Test with incorrect context value - verify context value is checked
incorrectValueCtx := context.WithValue(context.Background(), ctxTestKey, "wrong-value")
serviceWithIncorrectContext := newServiceLazy("foobar", func(i Injector) (*contextValueShutdownerLazy, error) {
return &contextValueShutdownerLazy{}, nil
})
_, _ = serviceWithIncorrectContext.getInstance(nil)
err6 := serviceWithIncorrectContext.shutdown(incorrectValueCtx)
is.Error(err6) // Should fail when context value is incorrect
is.ErrorContains(err6, "test-key not found or value is incorrect")
// Test with non-shutdownable service (should return nil even with canceled context)
nonShutdownableService := newServiceLazy("foobar", func(i Injector) (int, error) {
return 42, nil
})
_, _ = nonShutdownableService.getInstance(nil)
err4 := nonShutdownableService.shutdown(canceledCtx)
is.NoError(err4) // Non-shutdownable services return nil regardless of context
// Test with service that implements ShutdownerWithError (should return context error when context is canceled)
errorService := newServiceLazy("foobar", func(i Injector) (*lazyTestShutdownerKO, error) {
return &lazyTestShutdownerKO{foobar: "foobar"}, nil
})
_, _ = errorService.getInstance(nil)
err5 := errorService.shutdown(canceledCtx)
is.Error(err5)
is.ErrorContains(err5, "context canceled") // Should return context error when context is canceled
}
func TestServiceLazy_clone(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
// initial
service1 := newServiceLazy("foobar", func(i Injector) (lazyTest, error) {
return lazyTest{foobar: "foobar"}, nil
})
is.Equal("foobar", service1.getName())
is.False(service1.built)
_, _ = service1.getInstance(nil)
is.True(service1.built)
// clone
service2, ok := service1.clone(nil).(*serviceLazy[lazyTest])
is.True(ok)
is.Equal("foobar", service2.getName())
is.Empty(service2.instance)
is.False(service2.built)
_, _ = service2.getInstance(nil)
is.NotEmpty(service2.instance)
is.True(service2.built)
// change initial and check clone
service1.name = "baz"
is.Equal("baz", service1.getName())
is.Equal("foobar", service2.getName())
}
func TestServiceLazy_source(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
// Create a service lazy
service := newServiceLazy("test-lazy", func(i Injector) (lazyTest, error) {
return lazyTest{foobar: "test-value"}, nil
})
// Test initial state - should have provider frame but no invocation frames
providerFrame, invocationFrames := service.source()
// Provider frame should be set (from newServiceLazy)
is.NotEmpty(providerFrame.File, "Provider frame should have a file")
is.Positive(providerFrame.Line, "Provider frame should have a line number")
// Initially no invocation frames
is.Empty(invocationFrames, "Should have no invocation frames initially")
// Test after getting instance (which should add invocation frames)
_, err := service.getInstance(nil)
is.NoError(err, "Should be able to get instance")
// Check source after invocation
providerFrame2, invocationFrames2 := service.source()
// Provider frame should remain the same
is.Equal(providerFrame, providerFrame2, "Provider frame should remain unchanged")
// Should now have invocation frames
is.NotEmpty(invocationFrames2, "Should have invocation frames after getInstance")
is.Len(invocationFrames2, 1, "Should have exactly one invocation frame")
// Test multiple invocations
_, err = service.getInstance(nil)
is.NoError(err)
_, invocationFrames3 := service.source()
is.Len(invocationFrames3, 1, "Should still have only one unique invocation frame (duplicates are ignored)")
// Test with different service types
service2 := newServiceLazy("healthchecker-lazy", func(i Injector) (*lazyTestHeathcheckerOK, error) {
return &lazyTestHeathcheckerOK{foobar: "healthchecker-value"}, nil
})
// Get instance multiple times
_, err = service2.getInstance(nil)
is.NoError(err)
_, err = service2.getInstance(nil)
is.NoError(err)
providerFrame3, invocationFrames4 := service2.source()
is.NotEmpty(providerFrame3.File, "Provider frame should be set")
is.Len(invocationFrames4, 1, "Should have one unique invocation frame")
// Test concurrent access to source method
done := make(chan bool, 10)
for i := 0; i < 10; i++ {
go func() {
_, _ = service.source()
done <- true
}()
}
// Wait for all goroutines to complete
for i := 0; i < 10; i++ {
<-done
}
// Source should still work correctly after concurrent access
providerFrame4, invocationFrames5 := service.source()
is.Equal(providerFrame, providerFrame4, "Provider frame should remain consistent under concurrent access")
is.Len(invocationFrames5, 1, "Invocation frames should remain consistent under concurrent access")
// Test that invocation frames are properly collected from different call sites
// Add a frame manually to simulate different call sites
service.mu.Lock()
service.invokationFrames[stacktrace.Frame{File: "different_file.go", Line: 42}] = struct{}{}
service.mu.Unlock()
_, invocationFrames6 := service.source()
is.Len(invocationFrames6, 2, "Should have two invocation frames after adding different call site")
// Verify the frames are different
frameFiles := make(map[string]bool)
for _, frame := range invocationFrames6 {
frameFiles[frame.File] = true
}
is.Len(frameFiles, 2, "Should have frames from two different files")
// Test with primitive types
intService := newServiceLazy("int-lazy", func(i Injector) (int, error) {
return 42, nil
})
_, err = intService.getInstance(nil)
is.NoError(err)
providerFrame5, invocationFrames7 := intService.source()
is.NotEmpty(providerFrame5.File, "Provider frame should be set for primitive types")
is.Len(invocationFrames7, 1, "Should have invocation frames for primitive types")
// Test that the returned frames are copies, not references
// This ensures thread safety
originalFrames := make([]stacktrace.Frame, len(invocationFrames6))
copy(originalFrames, invocationFrames6)
// Modify the service's internal frames
service.mu.Lock()
service.invokationFrames[stacktrace.Frame{File: "new_file.go", Line: 100}] = struct{}{}
service.mu.Unlock()
// Get frames again
_, invocationFrames8 := service.source()
// Original frames should not be affected
is.Len(originalFrames, 2, "Original frames should not be affected by internal changes")
is.Len(invocationFrames8, 3, "New frames should include the additional frame")
// Test that source works correctly after service is built and reset
// This tests the lazy service's unique behavior
_, err = service.getInstance(nil)
is.NoError(err)
is.True(service.built, "Service should be built")
providerFrame6, invocationFrames9 := service.source()
is.Equal(providerFrame, providerFrame6, "Provider frame should remain unchanged after build")
is.Len(invocationFrames9, 3, "Should have all invocation frames after build")
// Test with error provider
errorService := newServiceLazy("error-lazy", func(i Injector) (lazyTest, error) {
return lazyTest{}, assert.AnError
})
// Even with error, source should still work
providerFrame7, invocationFrames10 := errorService.source()
is.NotEmpty(providerFrame7.File, "Provider frame should be set even for error providers")
is.Empty(invocationFrames10, "Should have no invocation frames for error providers initially")
// After attempting to get instance (which fails), should still have invocation frames
// because the frame is collected before the error occurs
_, err = errorService.getInstance(nil)
is.Error(err, "Should get error from error provider")
_, invocationFrames11 := errorService.source()
is.NotEmpty(invocationFrames11, "Should have invocation frames even after error (frame collected before error)")
}
// Test context value propagation for service lazy
func TestServiceLazy_ContextValuePropagation(t *testing.T) {
t.Parallel()
testWithTimeout(t, 100*time.Millisecond)
is := assert.New(t)
// Create service lazy instances with providers that return context-aware services
healthcheckLazy := newServiceLazy("healthcheck-lazy", func(i Injector) (*contextValueHealthcheckerLazy, error) {
return &contextValueHealthcheckerLazy{}, nil
})
shutdownLazy := newServiceLazy("shutdown-lazy", func(i Injector) (*contextValueShutdownerLazy, error) {
return &contextValueShutdownerLazy{}, nil
})
// Test context value propagation for healthcheck
ctx1 := context.WithValue(context.Background(), ctxTestKey, "healthcheck-value")
err := healthcheckLazy.healthcheck(ctx1)
is.NoError(err)
// Test context value propagation for shutdown
ctx2 := context.WithValue(context.Background(), ctxTestKey, "shutdown-value")
err = shutdownLazy.shutdown(ctx2)
is.NoError(err)
// Test that lazy service properly delegates to the underlying instance
// The lazy service should not store context values itself, but pass them through
// to the underlying service instance created by the provider
}