-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructor_test.go
More file actions
868 lines (662 loc) · 22 KB
/
constructor_test.go
File metadata and controls
868 lines (662 loc) · 22 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
package vessel
import (
"errors"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Test types for constructor injection
type testDatabase struct {
connStr string
}
type testLogger struct {
level string
}
type testCache struct {
host string
}
type testUserService struct {
db *testDatabase
logger *testLogger
}
type testProductService struct {
db *testDatabase
cache *testCache
}
// Simple constructors
func newTestDatabase() *testDatabase {
return &testDatabase{connStr: "postgres://localhost/test"}
}
func newTestLogger() *testLogger {
return &testLogger{level: "info"}
}
func newTestCache() *testCache {
return &testCache{host: "localhost:6379"}
}
func newTestUserService(db *testDatabase, logger *testLogger) *testUserService {
return &testUserService{db: db, logger: logger}
}
func newTestUserServiceWithError(db *testDatabase) (*testUserService, error) {
if db == nil {
return nil, errors.New("database is required")
}
return &testUserService{db: db}, nil
}
// === Basic Constructor Tests ===
func TestProvideConstructor_Simple(t *testing.T) {
c := New()
err := Provide(c, newTestDatabase)
require.NoError(t, err)
db, err := Inject[*testDatabase](c)
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db.connStr)
}
func TestProvideConstructor_WithDependencies(t *testing.T) {
c := New()
// Register dependencies first
err := Provide(c, newTestDatabase)
require.NoError(t, err)
err = Provide(c, newTestLogger)
require.NoError(t, err)
// Register service that depends on them
err = Provide(c, newTestUserService)
require.NoError(t, err)
// Resolve
svc, err := Inject[*testUserService](c)
require.NoError(t, err)
assert.NotNil(t, svc.db)
assert.NotNil(t, svc.logger)
assert.Equal(t, "postgres://localhost/test", svc.db.connStr)
assert.Equal(t, "info", svc.logger.level)
}
func TestProvideConstructor_WithError(t *testing.T) {
c := New()
// Provide database
err := Provide(c, newTestDatabase)
require.NoError(t, err)
// Provide service that can error
err = Provide(c, newTestUserServiceWithError)
require.NoError(t, err)
// Resolve
svc, err := Inject[*testUserService](c)
require.NoError(t, err)
assert.NotNil(t, svc.db)
}
func TestProvideConstructor_ErrorReturned(t *testing.T) {
c := New()
// Constructor that always errors
err := Provide(c, func() (*testDatabase, error) {
return nil, errors.New("connection failed")
})
require.NoError(t, err)
// Resolution should fail
_, err = Inject[*testDatabase](c)
assert.Error(t, err)
assert.Contains(t, err.Error(), "connection failed")
}
func TestProvideConstructor_MissingDependency(t *testing.T) {
c := New()
// Register service without its dependencies
err := Provide(c, newTestUserService)
require.NoError(t, err)
// Resolution should fail
_, err = Inject[*testUserService](c)
assert.Error(t, err)
assert.Contains(t, err.Error(), "no provider")
}
func TestProvideConstructor_Singleton(t *testing.T) {
c := New()
callCount := 0
err := Provide(c, func() *testDatabase {
callCount++
return &testDatabase{connStr: "test"}
})
require.NoError(t, err)
// Resolve multiple times
db1, err := Inject[*testDatabase](c)
require.NoError(t, err)
db2, err := Inject[*testDatabase](c)
require.NoError(t, err)
// Should be same instance
assert.Same(t, db1, db2)
assert.Equal(t, 1, callCount)
}
func TestProvideConstructor_Transient(t *testing.T) {
c := New()
callCount := 0
err := Provide(c, func() *testDatabase {
callCount++
return &testDatabase{connStr: "test"}
}, AsTransient())
require.NoError(t, err)
// Resolve multiple times
db1, err := Inject[*testDatabase](c)
require.NoError(t, err)
db2, err := Inject[*testDatabase](c)
require.NoError(t, err)
// Should be different instances
assert.NotSame(t, db1, db2)
assert.Equal(t, 2, callCount)
}
// === Named Services Tests ===
func TestProvideConstructor_Named(t *testing.T) {
c := New()
// Primary database
err := Provide(c, func() *testDatabase {
return &testDatabase{connStr: "primary"}
}, WithName("primary"))
require.NoError(t, err)
// Replica database
err = Provide(c, func() *testDatabase {
return &testDatabase{connStr: "replica"}
}, WithName("replica"))
require.NoError(t, err)
// Resolve by name
primary, err := InjectNamed[*testDatabase](c, "primary")
require.NoError(t, err)
assert.Equal(t, "primary", primary.connStr)
replica, err := InjectNamed[*testDatabase](c, "replica")
require.NoError(t, err)
assert.Equal(t, "replica", replica.connStr)
}
func TestProvideConstructor_DuplicateType(t *testing.T) {
c := New()
err := Provide(c, newTestDatabase)
require.NoError(t, err)
// Should error on duplicate
err = Provide(c, newTestDatabase)
assert.Error(t, err)
assert.Contains(t, err.Error(), "already registered")
}
// === In Struct Tests ===
type testServiceParamsIn struct {
In
DB *testDatabase
Logger *testLogger
}
func newServiceWithIn(p testServiceParamsIn) *testUserService {
return &testUserService{db: p.DB, logger: p.Logger}
}
func TestProvideConstructor_InStruct(t *testing.T) {
c := New()
// Register dependencies
err := Provide(c, newTestDatabase)
require.NoError(t, err)
err = Provide(c, newTestLogger)
require.NoError(t, err)
// Register service with In struct
err = Provide(c, newServiceWithIn)
require.NoError(t, err)
// Resolve
svc, err := Inject[*testUserService](c)
require.NoError(t, err)
assert.NotNil(t, svc.db)
assert.NotNil(t, svc.logger)
}
type testOptionalParamsIn struct {
In
DB *testDatabase
Cache *testCache `optional:"true"`
}
func newServiceWithOptional(p testOptionalParamsIn) *testUserService {
return &testUserService{db: p.DB}
}
func TestProvideConstructor_InStruct_Optional(t *testing.T) {
c := New()
// Only register database, not cache
err := Provide(c, newTestDatabase)
require.NoError(t, err)
// Register service with optional dependency
err = Provide(c, newServiceWithOptional)
require.NoError(t, err)
// Resolve - should succeed even without cache
svc, err := Inject[*testUserService](c)
require.NoError(t, err)
assert.NotNil(t, svc.db)
}
type testNamedParamsIn struct {
In
Primary *testDatabase `name:"primary"`
Replica *testDatabase `name:"replica"`
}
type testMultiDBService struct {
primary *testDatabase
replica *testDatabase
}
func newMultiDBService(p testNamedParamsIn) *testMultiDBService {
return &testMultiDBService{primary: p.Primary, replica: p.Replica}
}
func TestProvideConstructor_InStruct_Named(t *testing.T) {
c := New()
// Register named databases
err := Provide(c, func() *testDatabase {
return &testDatabase{connStr: "primary"}
}, WithName("primary"))
require.NoError(t, err)
err = Provide(c, func() *testDatabase {
return &testDatabase{connStr: "replica"}
}, WithName("replica"))
require.NoError(t, err)
// Register service that depends on named services
err = Provide(c, newMultiDBService)
require.NoError(t, err)
// Resolve
svc, err := Inject[*testMultiDBService](c)
require.NoError(t, err)
assert.Equal(t, "primary", svc.primary.connStr)
assert.Equal(t, "replica", svc.replica.connStr)
}
// === Out Struct Tests ===
type testServicesOut struct {
Out
UserService *testUserService
ProductService *testProductService
}
func newTestServices(db *testDatabase, logger *testLogger, cache *testCache) testServicesOut {
return testServicesOut{
UserService: &testUserService{db: db, logger: logger},
ProductService: &testProductService{db: db, cache: cache},
}
}
func TestProvideConstructor_OutStruct(t *testing.T) {
c := New()
// Register dependencies
err := Provide(c, newTestDatabase)
require.NoError(t, err)
err = Provide(c, newTestLogger)
require.NoError(t, err)
err = Provide(c, newTestCache)
require.NoError(t, err)
// Register constructor that returns Out struct
err = Provide(c, newTestServices)
require.NoError(t, err)
// Resolve both services
userSvc, err := Inject[*testUserService](c)
require.NoError(t, err)
assert.NotNil(t, userSvc.db)
productSvc, err := Inject[*testProductService](c)
require.NoError(t, err)
assert.NotNil(t, productSvc.db)
}
// === Value Groups Tests ===
type testUserHandler struct{}
func (h *testUserHandler) Handle() string { return "user" }
type testProductHandler struct{}
func (h *testProductHandler) Handle() string { return "product" }
func TestProvideConstructor_Group(t *testing.T) {
c := New()
// Register handlers in a group
err := Provide(c, func() *testUserHandler {
return &testUserHandler{}
}, AsGroup("handlers"))
require.NoError(t, err)
err = Provide(c, func() *testProductHandler {
return &testProductHandler{}
}, AsGroup("handlers"))
require.NoError(t, err)
// Resolve group - get concrete types
impl, ok := c.(*containerImpl)
require.True(t, ok)
regs := impl.typeRegistry.getGroup("handlers")
assert.Len(t, regs, 2)
}
// === Has/HasNamed Tests ===
func TestHasType(t *testing.T) {
c := New()
assert.False(t, HasType[*testDatabase](c))
err := Provide(c, newTestDatabase)
require.NoError(t, err)
assert.True(t, HasType[*testDatabase](c))
}
func TestHasTypeNamed(t *testing.T) {
c := New()
assert.False(t, HasTypeNamed[*testDatabase](c, "primary"))
err := Provide(c, newTestDatabase, WithName("primary"))
require.NoError(t, err)
assert.True(t, HasTypeNamed[*testDatabase](c, "primary"))
assert.False(t, HasTypeNamed[*testDatabase](c, "replica"))
}
// === Must* Helpers Tests ===
func TestMustInjectType_Success(t *testing.T) {
c := New()
err := Provide(c, newTestDatabase)
require.NoError(t, err)
db := MustInject[*testDatabase](c)
assert.NotNil(t, db)
}
func TestMustInjectType_Panic(t *testing.T) {
c := New()
assert.Panics(t, func() {
MustInject[*testDatabase](c)
})
}
func TestMustInjectNamed_Success(t *testing.T) {
c := New()
err := Provide(c, newTestDatabase, WithName("primary"))
require.NoError(t, err)
db := MustInjectNamed[*testDatabase](c, "primary")
assert.NotNil(t, db)
}
func TestMustInjectNamed_Panic(t *testing.T) {
c := New()
assert.Panics(t, func() {
MustInjectNamed[*testDatabase](c, "nonexistent")
})
}
// === Circular Dependency Tests ===
type testCircularA struct {
B *testCircularB
}
type testCircularB struct {
A *testCircularA
}
func TestProvideConstructor_CircularDependency(t *testing.T) {
c := New()
// This creates a circular dependency: A -> B -> A
err := Provide(c, func(b *testCircularB) *testCircularA {
return &testCircularA{B: b}
})
require.NoError(t, err)
err = Provide(c, func(a *testCircularA) *testCircularB {
return &testCircularB{A: a}
})
require.NoError(t, err)
// Resolution should detect cycle
_, err = Inject[*testCircularA](c)
assert.Error(t, err)
assert.Contains(t, err.Error(), "circular")
}
// === Constructor Analysis Tests ===
func TestAnalyzeConstructor_NotAFunction(t *testing.T) {
_, err := analyzeConstructor("not a function")
assert.Error(t, err)
assert.Contains(t, err.Error(), "must be a function")
}
func TestAnalyzeConstructor_NoReturns(t *testing.T) {
_, err := analyzeConstructor(func() {})
assert.Error(t, err)
assert.Contains(t, err.Error(), "must return at least one")
}
func TestAnalyzeConstructor_ErrorNotLast(t *testing.T) {
//nolint:staticcheck // Testing that error-not-last is detected
_, err := analyzeConstructor(func() (error, *testDatabase) {
return nil, nil
})
assert.Error(t, err)
assert.Contains(t, err.Error(), "error must be the last")
}
func TestIsInStruct(t *testing.T) {
assert.True(t, isInStruct(reflect.TypeOf(testServiceParamsIn{})))
assert.True(t, isInStruct(reflect.TypeOf(&testServiceParamsIn{})))
assert.False(t, isInStruct(reflect.TypeOf(testDatabase{})))
assert.False(t, isInStruct(reflect.TypeOf("string")))
}
func TestIsOutStruct(t *testing.T) {
assert.True(t, isOutStruct(reflect.TypeOf(testServicesOut{})))
assert.True(t, isOutStruct(reflect.TypeOf(&testServicesOut{})))
assert.False(t, isOutStruct(reflect.TypeOf(testDatabase{})))
assert.False(t, isOutStruct(reflect.TypeOf("string")))
}
// === As Option Tests ===
type testReader interface {
Read() string
}
type testWriter interface {
Write(s string)
}
type testReadWriter struct{}
func (rw *testReadWriter) Read() string { return "data" }
func (rw *testReadWriter) Write(s string) {}
func TestProvideConstructor_As(t *testing.T) {
c := New()
err := Provide(c, func() *testReadWriter {
return &testReadWriter{}
}, As(new(testReader)))
require.NoError(t, err)
// Should be resolvable as interface
reader, err := Inject[testReader](c)
require.NoError(t, err)
assert.Equal(t, "data", reader.Read())
}
func TestWithAliases_MultipleNames(t *testing.T) {
c := New()
// Register with primary name and aliases
err := Provide(c, newTestDatabase, WithName("primary"), WithAliases("default", "main"))
require.NoError(t, err)
// Should be resolvable by primary name
db1, err := InjectNamed[*testDatabase](c, "primary")
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db1.connStr)
// Should be resolvable by first alias
db2, err := InjectNamed[*testDatabase](c, "default")
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db2.connStr)
// Should be resolvable by second alias
db3, err := InjectNamed[*testDatabase](c, "main")
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db3.connStr)
// All should be the same instance (singleton)
assert.Same(t, db1, db2)
assert.Same(t, db2, db3)
}
func TestWithAliases_EmptyStringForUnnamed(t *testing.T) {
c := New()
// Register with a name but also as unnamed (empty string alias)
err := Provide(c, newTestDatabase, WithName("named"), WithAliases(""))
require.NoError(t, err)
// Should be resolvable by name
db1, err := InjectNamed[*testDatabase](c, "named")
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db1.connStr)
// Should also be resolvable without name
db2, err := Inject[*testDatabase](c)
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db2.connStr)
// Should be the same instance
assert.Same(t, db1, db2)
}
func TestWithAliases_WithAsTypes(t *testing.T) {
c := New()
// Register with name, aliases, and additional interface types
err := Provide(c, func() *testReadWriter {
return &testReadWriter{}
}, WithName("rw"), WithAliases("default", ""), As(new(testReader), new(testWriter)))
require.NoError(t, err)
// Should be resolvable as concrete type by name
rw1, err := InjectNamed[*testReadWriter](c, "rw")
require.NoError(t, err)
// Should be resolvable as concrete type by alias
rw2, err := InjectNamed[*testReadWriter](c, "default")
require.NoError(t, err)
// Should be resolvable as concrete type without name
rw3, err := Inject[*testReadWriter](c)
require.NoError(t, err)
// Should be resolvable as interface by name
reader1, err := InjectNamed[testReader](c, "rw")
require.NoError(t, err)
// Should be resolvable as interface by alias
reader2, err := InjectNamed[testReader](c, "default")
require.NoError(t, err)
// Should be resolvable as interface without name
reader3, err := Inject[testReader](c)
require.NoError(t, err)
// All should be the same instance
assert.Same(t, rw1, rw2)
assert.Same(t, rw2, rw3)
assert.Same(t, rw1, reader1)
assert.Same(t, reader1, reader2)
assert.Same(t, reader2, reader3)
}
func TestWithAliases_ConflictDetection(t *testing.T) {
c := New()
// Register first database
err := Provide(c, newTestDatabase, WithName("primary"))
require.NoError(t, err)
// Try to register second database with same name - should fail
err = Provide(c, newTestDatabase, WithName("primary"))
assert.Error(t, err)
assert.Contains(t, err.Error(), "already registered")
// Try to register with alias that conflicts with existing named service
err = Provide(c, func() *testDatabase {
return &testDatabase{connStr: "different"}
}, WithName("secondary"), WithAliases("primary"))
assert.Error(t, err)
assert.Contains(t, err.Error(), "alias")
}
func TestWithAliases_TypePrimaryWithNamedAliases(t *testing.T) {
c := New()
// Register by type (unnamed) with named aliases - this is the main use case
err := Provide(c, newTestDatabase, WithAliases("manager", "db-manager", "primary"))
require.NoError(t, err)
// Should be resolvable by type (unnamed)
db1, err := Inject[*testDatabase](c)
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db1.connStr)
// Should be resolvable by first alias
db2, err := InjectNamed[*testDatabase](c, "manager")
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db2.connStr)
// Should be resolvable by second alias
db3, err := InjectNamed[*testDatabase](c, "db-manager")
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db3.connStr)
// Should be resolvable by third alias
db4, err := InjectNamed[*testDatabase](c, "primary")
require.NoError(t, err)
assert.Equal(t, "postgres://localhost/test", db4.connStr)
// All should be the same singleton instance
assert.Same(t, db1, db2)
assert.Same(t, db2, db3)
assert.Same(t, db3, db4)
}
func TestWithAliases_InterfacesWithTypeAndNamedAccess(t *testing.T) {
c := New()
// Register concrete type with interface, accessible by type and named aliases
err := Provide(c, func() *testReadWriter {
return &testReadWriter{}
}, As(new(testReader), new(testWriter)), WithAliases("rw", "reader-writer"))
require.NoError(t, err)
// Resolve concrete type unnamed
rw1, err := Inject[*testReadWriter](c)
require.NoError(t, err)
// Resolve concrete type by alias
rw2, err := InjectNamed[*testReadWriter](c, "rw")
require.NoError(t, err)
// Resolve interface type unnamed
reader1, err := Inject[testReader](c)
require.NoError(t, err)
// Resolve interface type by alias
reader2, err := InjectNamed[testReader](c, "reader-writer")
require.NoError(t, err)
// All should be the same instance
assert.Same(t, rw1, rw2)
assert.Same(t, rw1, reader1)
assert.Same(t, reader1, reader2)
}
// === WithEager Tests ===
func TestWithEager_InstantiatesImmediately(t *testing.T) {
c := New()
var constructorCalled bool
// Register with eager instantiation
err := Provide(c, func() *testDatabase {
constructorCalled = true
return &testDatabase{connStr: "postgres://localhost/test"}
}, WithEager())
require.NoError(t, err)
// Constructor should have been called during registration
assert.True(t, constructorCalled, "Constructor should be called immediately with WithEager()")
// Subsequent calls should return cached instance without calling constructor again
constructorCalled = false
db, err := Inject[*testDatabase](c)
require.NoError(t, err)
assert.False(t, constructorCalled, "Constructor should not be called again")
assert.Equal(t, "postgres://localhost/test", db.connStr)
}
func TestWithEager_FailsImmediately(t *testing.T) {
c := New()
// Register constructor that fails, with eager instantiation
err := Provide(c, func() (*testDatabase, error) {
return nil, errors.New("connection failed")
}, WithEager())
// Should fail immediately during registration
assert.Error(t, err)
assert.Contains(t, err.Error(), "eager instantiation failed")
assert.Contains(t, err.Error(), "connection failed")
}
func TestWithEager_WithDependencies(t *testing.T) {
c := New()
var dbConstructorCalled bool
var serviceConstructorCalled bool
// Register dependency first
err := Provide(c, func() *testDatabase {
dbConstructorCalled = true
return &testDatabase{connStr: "postgres://localhost/test"}
})
require.NoError(t, err)
assert.False(t, dbConstructorCalled, "DB constructor should not be called yet (lazy)")
// Register service with eager instantiation
err = Provide(c, func(db *testDatabase) *testUserService {
serviceConstructorCalled = true
return &testUserService{db: db}
}, WithEager())
require.NoError(t, err)
// Both constructors should have been called
assert.True(t, dbConstructorCalled, "DB constructor should be called (dependency)")
assert.True(t, serviceConstructorCalled, "Service constructor should be called (eager)")
// Subsequent resolution should use cached instances
dbConstructorCalled = false
serviceConstructorCalled = false
svc, err := Inject[*testUserService](c)
require.NoError(t, err)
assert.False(t, serviceConstructorCalled, "Service constructor should not be called again")
assert.NotNil(t, svc.db)
db, err := Inject[*testDatabase](c)
require.NoError(t, err)
assert.False(t, dbConstructorCalled, "DB constructor should not be called again")
assert.Same(t, svc.db, db, "Should be same cached instance")
}
func TestWithEager_WithAliases(t *testing.T) {
c := New()
var constructorCalled bool
// Register with both eager and aliases
err := Provide(c, func() *testDatabase {
constructorCalled = true
return &testDatabase{connStr: "postgres://localhost/test"}
}, WithEager(), WithAliases("db", "database"))
require.NoError(t, err)
// Constructor should have been called immediately
assert.True(t, constructorCalled, "Constructor should be called immediately")
// Reset flag
constructorCalled = false
// All access methods should return cached instance
db1, err := Inject[*testDatabase](c)
require.NoError(t, err)
assert.False(t, constructorCalled, "Constructor should not be called again")
db2, err := InjectNamed[*testDatabase](c, "db")
require.NoError(t, err)
assert.False(t, constructorCalled, "Constructor should not be called again")
db3, err := InjectNamed[*testDatabase](c, "database")
require.NoError(t, err)
assert.False(t, constructorCalled, "Constructor should not be called again")
// All should be same instance
assert.Same(t, db1, db2)
assert.Same(t, db2, db3)
}
func TestWithoutEager_LazyByDefault(t *testing.T) {
c := New()
var constructorCalled bool
// Register WITHOUT eager (default lazy behavior)
err := Provide(c, func() *testDatabase {
constructorCalled = true
return &testDatabase{connStr: "postgres://localhost/test"}
})
require.NoError(t, err)
// Constructor should NOT have been called during registration
assert.False(t, constructorCalled, "Constructor should not be called (lazy by default)")
// Constructor should be called on first resolution
db, err := Inject[*testDatabase](c)
require.NoError(t, err)
assert.True(t, constructorCalled, "Constructor should be called on first use")
assert.Equal(t, "postgres://localhost/test", db.connStr)
}