-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapt_test.go
More file actions
1331 lines (1102 loc) · 40.2 KB
/
Copy pathadapt_test.go
File metadata and controls
1331 lines (1102 loc) · 40.2 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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ctxdep
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// Test types for adapter tests
type TestDatabase struct {
Name string
}
type TestUser struct {
ID string
Name string
Email string
}
type TestConfig struct {
APIKey string
}
// Adapter function types
type UserAdapter func(ctx context.Context, userID string) (*TestUser, error)
type UserAdapterNoError func(ctx context.Context, userID string) *TestUser
type ComplexAdapter func(ctx context.Context, name string, age int) (string, error)
// Test functions that will be wrapped as adapters
func lookupUser(ctx context.Context, db *TestDatabase, userID string) (*TestUser, error) {
if userID == "error" {
return nil, errors.New("user not found")
}
return &TestUser{
ID: userID,
Name: "Test User from " + db.Name,
Email: userID + "@example.com",
}, nil
}
func lookupUserNoError(ctx context.Context, db *TestDatabase, userID string) *TestUser {
return &TestUser{
ID: userID,
Name: "Test User from " + db.Name,
Email: userID + "@example.com",
}
}
func complexFunction(ctx context.Context, db *TestDatabase, config *TestConfig, name string, age int) (string, error) {
if age < 0 {
return "", errors.New("invalid age")
}
return db.Name + ":" + config.APIKey + ":" + name + ":" + string(rune(age)), nil
}
func TestAdapterBasic(t *testing.T) {
// Create a context with dependencies
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db, Adapt[UserAdapter](lookupUser))
// Get the adapter
adapter := Get[UserAdapter](ctx)
if adapter == nil {
t.Fatal("adapter should not be nil")
}
// Use the adapter
user, err := adapter(ctx, "user123")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if user.ID != "user123" {
t.Errorf("expected user ID 'user123', got '%s'", user.ID)
}
if user.Name != "Test User from TestDB" {
t.Errorf("expected user name 'Test User from TestDB', got '%s'", user.Name)
}
if user.Email != "user123@example.com" {
t.Errorf("expected email 'user123@example.com', got '%s'", user.Email)
}
}
func TestAdapterWithError(t *testing.T) {
// Create a context with dependencies
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db, Adapt[UserAdapter](lookupUser))
// Get the adapter
adapter := Get[UserAdapter](ctx)
// Use the adapter with error case
user, err := adapter(ctx, "error")
if err == nil {
t.Fatal("expected error, got nil")
}
if err.Error() != "user not found" {
t.Errorf("expected error 'user not found', got '%v'", err)
}
if user != nil {
t.Error("expected nil user on error")
}
}
func TestAdapterNoError(t *testing.T) {
// Create a context with dependencies
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db, Adapt[UserAdapterNoError](lookupUserNoError))
// Get the adapter
adapter := Get[UserAdapterNoError](ctx)
// Use the adapter
user := adapter(ctx, "user456")
if user == nil {
t.Fatal("user should not be nil")
}
if user.ID != "user456" {
t.Errorf("expected user ID 'user456', got '%s'", user.ID)
}
}
func TestAdapterMultipleDependencies(t *testing.T) {
// Create a context with multiple dependencies
db := &TestDatabase{Name: "TestDB"}
config := &TestConfig{APIKey: "secret123"}
ctx := NewDependencyContext(context.Background(), db, config, Adapt[ComplexAdapter](complexFunction))
// Get the adapter
adapter := Get[ComplexAdapter](ctx)
// Use the adapter
result, err := adapter(ctx, "John", 30)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expected := "TestDB:secret123:John:" + string(rune(30))
if result != expected {
t.Errorf("expected '%s', got '%s'", expected, result)
}
}
func TestAdapterMissingDependency(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic for missing dependency")
}
}()
// Create a context without the required database dependency
_ = NewDependencyContext(context.Background(), Adapt[UserAdapter](lookupUser))
// This should panic during initialization
}
func TestAdapterInvalidTargetType(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic for invalid target type")
}
}()
// Try to create an adapter with non-function target type
type NotAFunction struct{}
Adapt[NotAFunction](lookupUser)
}
func TestAdapterInvalidFunction(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic for invalid function")
}
}()
// Try to create an adapter with non-function argument
Adapt[UserAdapter]("not a function")
}
func TestAdapterParameterMismatch(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic for parameter mismatch")
}
}()
// Wrong adapter type - expects different parameters
type WrongAdapter func(ctx context.Context, userID string, extra int) (*TestUser, error)
db := &TestDatabase{Name: "TestDB"}
_ = NewDependencyContext(context.Background(), db, Adapt[WrongAdapter](lookupUser))
}
func TestAdapterReturnMismatch(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic for return mismatch")
}
}()
// Wrong adapter type - expects different return types
type WrongAdapter func(ctx context.Context, userID string) (string, error)
Adapt[WrongAdapter](lookupUser)
}
func TestAdapterWithOptionalDependency(t *testing.T) {
// Test that adapter validates missing dependencies at initialization
defer func() {
if r := recover(); r == nil {
t.Error("expected panic when adapter has unresolvable dependencies")
}
}()
// Function that requires a dependency not in context
fn := func(ctx context.Context, missing *TestConfig, id string) (*TestUser, error) {
return &TestUser{ID: id}, nil
}
type TestAdapter func(ctx context.Context, id string) (*TestUser, error)
// This should panic because TestConfig is not available
ctx := NewDependencyContext(context.Background(), Adapt[TestAdapter](fn))
_ = ctx
}
func TestAdapterContextUpdate(t *testing.T) {
// Test that adapter uses dependencies from creation time, not from the provided context
db := &TestDatabase{Name: "OriginalDB"}
ctx := NewDependencyContext(context.Background(), db, Adapt[UserAdapter](lookupUser))
adapter := Get[UserAdapter](ctx)
// Create a new context with updated database
newDB := &TestDatabase{Name: "UpdatedDB"}
newCtx := NewDependencyContext(ctx, newDB, WithOverrides())
// Use adapter with new context
user, err := adapter(newCtx, "user789")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Should use the original database from when adapter was created
if user.Name != "Test User from OriginalDB" {
t.Errorf("expected user from OriginalDB, got '%s'", user.Name)
}
}
func TestAdapterNoContextParameter(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic for adapter without context parameter")
}
}()
// Adapter target requires context but original function doesn't have it
noCtxFunc := func(db *TestDatabase, userID string) (*TestUser, error) {
return &TestUser{ID: userID}, nil
}
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db, Adapt[UserAdapter](noCtxFunc))
adapter := Get[UserAdapter](ctx)
// This should panic when trying to call the adapter
_, _ = adapter(ctx, "test")
}
func TestAdapterAllDependenciesFromContext(t *testing.T) {
// Test function where all non-context parameters come from context
type SimpleAdapter func(ctx context.Context) (*TestUser, error)
fn := func(ctx context.Context, db *TestDatabase, config *TestConfig) (*TestUser, error) {
return &TestUser{
ID: config.APIKey,
Name: db.Name,
Email: "test@example.com",
}, nil
}
db := &TestDatabase{Name: "TestDB"}
config := &TestConfig{APIKey: "key123"}
ctx := NewDependencyContext(context.Background(), db, config, Adapt[SimpleAdapter](fn))
adapter := Get[SimpleAdapter](ctx)
user, err := adapter(ctx)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if user.ID != "key123" {
t.Errorf("expected user ID 'key123', got '%s'", user.ID)
}
if user.Name != "TestDB" {
t.Errorf("expected user name 'TestDB', got '%s'", user.Name)
}
}
func TestAdapterConcurrent(t *testing.T) {
// Test concurrent adapter usage
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db, Adapt[UserAdapter](lookupUser))
adapter := Get[UserAdapter](ctx)
// Run multiple goroutines using the adapter
done := make(chan bool, 10)
for i := 0; i < 10; i++ {
go func(id int) {
userID := "user" + string(rune('0'+id))
user, err := adapter(ctx, userID)
if err != nil {
t.Errorf("unexpected error in goroutine %d: %v", id, err)
}
if user.ID != userID {
t.Errorf("expected user ID '%s', got '%s'", userID, user.ID)
}
done <- true
}(i)
}
// Wait for all goroutines
for i := 0; i < 10; i++ {
<-done
}
}
func TestAdapterStatus(t *testing.T) {
// Create a context with an adapter
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db, Adapt[UserAdapter](lookupUser))
status := Status(ctx)
// Check that it shows as an adapter
if !strings.Contains(status, "ctxdep.UserAdapter - adapter wrapping:") {
t.Error("Adapter should show as 'adapter wrapping:' in status")
}
// Check that it shows the wrapped function signature
if !strings.Contains(status, "(context.Context, *ctxdep.TestDatabase, string) *ctxdep.TestUser, error") {
t.Error("Status should show the original function signature")
}
}
func TestAdapterAnonymousType(t *testing.T) {
// Test using an anonymous function type for an adapter
db := &TestDatabase{Name: "TestDB"}
// Instead of using a named type like UserAdapter, use anonymous func type
ctx := NewDependencyContext(context.Background(), db,
Adapt[func(ctx context.Context, userID string) (*TestUser, error)](lookupUser))
// Try to get it with the same anonymous type
adapter := Get[func(ctx context.Context, userID string) (*TestUser, error)](ctx)
// Use the adapter
user, err := adapter(ctx, "user123")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if user.ID != "user123" {
t.Errorf("expected user ID 'user123', got '%s'", user.ID)
}
if user.Name != "Test User from TestDB" {
t.Errorf("expected user name 'Test User from TestDB', got '%s'", user.Name)
}
}
func TestAdapterAnonymousTypeMismatch(t *testing.T) {
// Test what happens when anonymous function types have different signatures
db := &TestDatabase{Name: "TestDB"}
// Register with one anonymous type
ctx := NewDependencyContext(context.Background(), db,
Adapt[func(ctx context.Context, userID string) (*TestUser, error)](lookupUser))
// Try to get with a different signature (int instead of string)
defer func() {
if r := recover(); r == nil {
t.Error("expected panic when signatures don't match")
}
}()
// This should panic because the signatures are different
_ = Get[func(context.Context, int) (*TestUser, error)](ctx)
}
func TestAdapterAnonymousWithOptional(t *testing.T) {
// Test GetOptional with anonymous function types
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db,
Adapt[func(ctx context.Context, userID string) (*TestUser, error)](lookupUser))
// Try to get with exact same type - parameter names don't matter
adapter1, found1 := GetOptional[func(ctx context.Context, userID string) (*TestUser, error)](ctx)
if !found1 {
t.Error("should find adapter with exact type match")
}
if adapter1 == nil {
t.Error("adapter should not be nil")
}
// Try to get with same signature but different parameter names - should work
adapter2, found2 := GetOptional[func(context.Context, string) (*TestUser, error)](ctx)
if !found2 {
t.Error("should find adapter with same signature (parameter names ignored)")
}
if adapter2 == nil {
t.Error("adapter should not be nil")
}
// Try to get with different signature - should not find
adapter3, found3 := GetOptional[func(context.Context, int) (*TestUser, error)](ctx)
if found3 {
t.Error("should not find adapter with different signature")
}
if adapter3 != nil {
t.Error("adapter should be nil when not found")
}
}
func TestAdapterAnonymousStatus(t *testing.T) {
// Test how Status displays anonymous function types
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db,
Adapt[func(ctx context.Context, userID string) (*TestUser, error)](lookupUser))
status := Status(ctx)
t.Logf("Status with anonymous function type:\n%s", status)
// Check that status includes the anonymous function type
if !strings.Contains(status, "func(context.Context, string) (*ctxdep.TestUser, error)") {
t.Error("Status should include the anonymous function type")
}
// Check that it shows as an adapter
if !strings.Contains(status, "adapter wrapping:") {
t.Error("Should show as adapter in status")
}
}
func TestAdapterAnonymousMultiple(t *testing.T) {
// Test multiple anonymous function types in same context
db := &TestDatabase{Name: "TestDB"}
config := &TestConfig{APIKey: "secret"}
// Create two different anonymous function types with different signatures
ctx := NewDependencyContext(context.Background(), db, config,
Adapt[func(ctx context.Context, userID string) (*TestUser, error)](lookupUser),
Adapt[func(ctx context.Context, op string, val int) (string, error)](complexFunction))
// Get the first adapter
userAdapter := Get[func(ctx context.Context, userID string) (*TestUser, error)](ctx)
user, err := userAdapter(ctx, "test-user")
if err != nil {
t.Fatalf("unexpected error from user adapter: %v", err)
}
if user.ID != "test-user" {
t.Errorf("expected user ID 'test-user', got '%s'", user.ID)
}
// Get the second adapter
complexAdapter := Get[func(ctx context.Context, op string, val int) (string, error)](ctx)
result, err := complexAdapter(ctx, "test", 42)
if err != nil {
t.Fatalf("unexpected error from complex adapter: %v", err)
}
expected := "TestDB:secret:test:" + string(rune(42))
if result != expected {
t.Errorf("expected '%s', got '%s'", expected, result)
}
}
func TestAdapterAnonymousNestedContext(t *testing.T) {
// Test anonymous function types with nested contexts
db := &TestDatabase{Name: "ParentDB"}
// Parent context with anonymous adapter
parentCtx := NewDependencyContext(context.Background(), db,
Adapt[func(ctx context.Context, userID string) (*TestUser, error)](lookupUser))
// Child context trying to override (should not work due to security)
newDB := &TestDatabase{Name: "ChildDB"}
childCtx := NewDependencyContext(parentCtx, newDB, WithOverrides())
// Get adapter from child context
adapter := Get[func(ctx context.Context, userID string) (*TestUser, error)](childCtx)
// Should use parent's database
user, err := adapter(childCtx, "nested-user")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if user.Name != "Test User from ParentDB" {
t.Errorf("expected user from ParentDB, got '%s'", user.Name)
}
}
func TestAdapterAnonymousTypeAliases(t *testing.T) {
// Test behavior with type aliases
type MyUserFunc = func(ctx context.Context, userID string) (*TestUser, error)
db := &TestDatabase{Name: "TestDB"}
// Register with type alias
ctx := NewDependencyContext(context.Background(), db, Adapt[MyUserFunc](lookupUser))
// Get with type alias - should work
adapter1 := Get[MyUserFunc](ctx)
user1, err := adapter1(ctx, "alias-user")
if err != nil {
t.Fatalf("unexpected error with type alias: %v", err)
}
if user1.ID != "alias-user" {
t.Errorf("expected user ID 'alias-user', got '%s'", user1.ID)
}
// Get with expanded type - should also work since it's an alias
adapter2 := Get[func(ctx context.Context, userID string) (*TestUser, error)](ctx)
user2, err := adapter2(ctx, "expanded-user")
if err != nil {
t.Fatalf("unexpected error with expanded type: %v", err)
}
if user2.ID != "expanded-user" {
t.Errorf("expected user ID 'expanded-user', got '%s'", user2.ID)
}
}
func TestRegularAnonymousFunctions(t *testing.T) {
// Test what happens with regular (non-adapter) anonymous function dependencies
// Create an anonymous function
myFunc := func(x int) string {
return fmt.Sprintf("value: %d", x)
}
// Store it as a dependency
ctx := NewDependencyContext(context.Background(), &myFunc)
// Get it back
fn := Get[*func(int) string](ctx)
result := (*fn)(42)
if result != "value: 42" {
t.Errorf("expected 'value: 42', got '%s'", result)
}
// Check status
status := Status(ctx)
t.Logf("Status with regular anonymous function:\n%s", status)
if !strings.Contains(status, "*func(int) string") {
t.Error("Status should show pointer to anonymous function type")
}
if !strings.Contains(status, "direct value set") {
t.Error("Should show as direct value, not adapter")
}
}
func TestAnonymousFunctionComparison(t *testing.T) {
// Document the difference between regular functions and adapters with anonymous types
db := &TestDatabase{Name: "TestDB"}
// Regular anonymous function (stored as pointer)
regularFunc := func(ctx context.Context, userID string) (*TestUser, error) {
return &TestUser{ID: userID, Name: "Regular"}, nil
}
ctx := NewDependencyContext(context.Background(),
db,
®ularFunc, // Regular function stored as pointer
Adapt[func(context.Context, string) (*TestUser, error)](lookupUser), // Adapter
)
// Get regular function
regular := Get[*func(context.Context, string) (*TestUser, error)](ctx)
user1, _ := (*regular)(context.Background(), "reg")
if user1.Name != "Regular" {
t.Errorf("expected 'Regular', got '%s'", user1.Name)
}
// Get adapter function (not a pointer)
adapter := Get[func(context.Context, string) (*TestUser, error)](ctx)
user2, _ := adapter(ctx, "fact")
if user2.Name != "Test User from TestDB" {
t.Errorf("expected 'Test User from TestDB', got '%s'", user2.Name)
}
// Show status difference
status := Status(ctx)
t.Logf("Status comparison:\n%s", status)
}
// Test adapter error handling when dependencies can't be resolved at runtime
func TestAdapterDependencyResolutionError(t *testing.T) {
// Create a context with a generator that fails
brokenGen := func(ctx context.Context) (*TestDatabase, error) {
return nil, errors.New("database connection failed")
}
// Create context with the broken generator and an adapter that depends on it
ctx := NewDependencyContext(context.Background(), brokenGen, Adapt[UserAdapter](lookupUser))
// Get the adapter
adapter := Get[UserAdapter](ctx)
// Try to use the adapter - this should trigger the error handling path
// because the TestDatabase dependency will fail to resolve
user, err := adapter(ctx, "test-user")
// Should get an error, not panic
if err == nil {
t.Error("expected error when dependency resolution fails")
}
if user != nil {
t.Error("expected nil user when error occurs")
}
// The error should be about dependency resolution
if !contains(err.Error(), "error running generator") {
t.Errorf("unexpected error: %v", err)
}
}
// Test adapter that doesn't return an error
func TestAdapterDependencyResolutionErrorNoErrorReturn(t *testing.T) {
// Create a function that doesn't return an error
noErrorFunc := func(ctx context.Context, db *TestDatabase, userID string) *TestUser {
return &TestUser{ID: userID, Name: db.Name}
}
type NoErrorAdapter func(ctx context.Context, userID string) *TestUser
// Create a failing generator
brokenGen := func(ctx context.Context) (*TestDatabase, error) {
return nil, errors.New("database unavailable")
}
ctx := NewDependencyContext(context.Background(), brokenGen, Adapt[NoErrorAdapter](noErrorFunc))
// Get the adapter
adapter := Get[NoErrorAdapter](ctx)
// Try to use the adapter - should panic since the adapter doesn't return error
defer func() {
if r := recover(); r == nil {
t.Error("expected panic when adapter without error return can't resolve dependencies")
} else {
// Verify the panic message
if msg, ok := r.(string); ok {
if !contains(msg, "failed to resolve dependency for adapter") {
t.Errorf("unexpected panic message: %s", msg)
}
}
}
}()
// This should panic
_ = adapter(ctx, "test-user")
}
// Test adapter with multiple return values including error
func TestAdapterMultipleReturnsWithError(t *testing.T) {
// Create a function that returns multiple values plus error
multiReturnFunc := func(ctx context.Context, db *TestDatabase, userID string) (*TestUser, string, error) {
if db == nil {
return nil, "", errors.New("database is nil")
}
user := &TestUser{ID: userID, Name: db.Name}
return user, "success", nil
}
type MultiReturnAdapter func(ctx context.Context, userID string) (*TestUser, string, error)
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db, Adapt[MultiReturnAdapter](multiReturnFunc))
// Get the adapter
adapter := Get[MultiReturnAdapter](ctx)
// Test successful case
user, status, err := adapter(ctx, "user1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if user == nil || user.ID != "user1" {
t.Error("expected valid user")
}
if status != "success" {
t.Errorf("expected 'success', got '%s'", status)
}
// Test error case with missing dependency
// Create a context with failing generator for the database
failingDB := func(ctx context.Context) (*TestDatabase, error) {
return nil, errors.New("db connection failed")
}
errorCtx := NewDependencyContext(context.Background(), failingDB, Adapt[MultiReturnAdapter](multiReturnFunc))
errorAdapter := Get[MultiReturnAdapter](errorCtx)
user2, status2, err2 := errorAdapter(errorCtx, "user2")
// Should return zero values for non-error returns and the error
if err2 == nil {
t.Error("expected error when dependency missing")
}
if user2 != nil {
t.Error("expected nil user on error")
}
if status2 != "" {
t.Errorf("expected empty string on error, got '%s'", status2)
}
}
// Test adapter with complex return types
func TestAdapterComplexReturnTypes(t *testing.T) {
type Result struct {
Data string
Count int
}
// Function that returns struct, pointer, and error
complexFunc := func(ctx context.Context, db *TestDatabase, input string) (Result, *TestUser, error) {
result := Result{Data: input, Count: len(input)}
user := &TestUser{ID: input, Name: db.Name}
return result, user, nil
}
type ComplexAdapter func(ctx context.Context, input string) (Result, *TestUser, error)
// Create context with failing database generator
failingDB := func(ctx context.Context) (*TestDatabase, error) {
return nil, errors.New("database error")
}
ctx := NewDependencyContext(context.Background(), failingDB, Adapt[ComplexAdapter](complexFunc))
adapter := Get[ComplexAdapter](ctx)
// Test with the adapter - should fail to resolve database
result, user, err := adapter(ctx, "test")
// Should get error and zero values
if err == nil {
t.Error("expected error with missing dependency")
}
if result.Data != "" || result.Count != 0 {
t.Errorf("expected zero Result, got %+v", result)
}
if user != nil {
t.Error("expected nil *TestUser")
}
}
// Test nested dependency resolution failure
func TestAdapterNestedDependencyFailure(t *testing.T) {
// Create a chain of dependencies where one fails
type Service struct {
Name string
}
// Generator that fails
failingGen := func(ctx context.Context) (*Service, error) {
return nil, errors.New("service unavailable")
}
// Function that depends on Service
funcNeedsService := func(ctx context.Context, svc *Service, db *TestDatabase, id string) (*TestUser, error) {
return &TestUser{ID: id, Name: svc.Name + ":" + db.Name}, nil
}
type ServiceAdapter func(ctx context.Context, id string) (*TestUser, error)
db := &TestDatabase{Name: "TestDB"}
ctx := NewDependencyContext(context.Background(), db, failingGen, Adapt[ServiceAdapter](funcNeedsService))
adapter := Get[ServiceAdapter](ctx)
// Should fail when trying to resolve Service dependency
user, err := adapter(ctx, "test-id")
if err == nil {
t.Error("expected error when nested dependency fails")
}
if user != nil {
t.Error("expected nil user on error")
}
// Verify error mentions the dependency resolution
if !contains(err.Error(), "error running generator") {
t.Errorf("unexpected error message: %v", err)
}
}
// Test adapter that only returns an error
func TestAdapterOnlyErrorReturn(t *testing.T) {
// Function that only returns error
validateFunc := func(ctx context.Context, db *TestDatabase, input string) error {
if db == nil {
return errors.New("database required")
}
if input == "" {
return errors.New("input required")
}
return nil
}
type ValidatorAdapter func(ctx context.Context, input string) error
// Test with failing database
failingDB := func(ctx context.Context) (*TestDatabase, error) {
return nil, errors.New("db unavailable")
}
ctx := NewDependencyContext(context.Background(), failingDB, Adapt[ValidatorAdapter](validateFunc))
adapter := Get[ValidatorAdapter](ctx)
// Should return the dependency resolution error
err := adapter(ctx, "valid-input")
if err == nil {
t.Error("expected error when dependency fails")
}
if !contains(err.Error(), "error running generator") {
t.Errorf("unexpected error: %v", err)
}
}
// Test adapter with non-pointer return types
func TestAdapterValueReturnTypes(t *testing.T) {
// Function that returns values, not pointers
calcFunc := func(ctx context.Context, db *TestDatabase, x int) (int, bool, error) {
if db == nil {
return 0, false, errors.New("need database")
}
return x * 2, true, nil
}
type CalcAdapter func(ctx context.Context, x int) (int, bool, error)
// Test with failing dependency
failingDB := func(ctx context.Context) (*TestDatabase, error) {
return nil, errors.New("calculation database offline")
}
ctx := NewDependencyContext(context.Background(), failingDB, Adapt[CalcAdapter](calcFunc))
adapter := Get[CalcAdapter](ctx)
// Should return zero values and error
result, ok, err := adapter(ctx, 21)
if err == nil {
t.Error("expected error")
}
if result != 0 {
t.Errorf("expected 0, got %d", result)
}
if ok {
t.Error("expected false for bool return")
}
}
// Helper function since strings.Contains isn't imported
func contains(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
// Test that adapter dependencies are not resolved until the adapter is called
func TestAdapterLazyDependencyResolution(t *testing.T) {
// Counter to track when the database generator is called
var dbGeneratorCalled int32
// Create a generator that tracks when it's called
dbGenerator := func(ctx context.Context) (*TestDatabase, error) {
atomic.AddInt32(&dbGeneratorCalled, 1)
return &TestDatabase{Name: "GeneratedDB"}, nil
}
// Create context with the tracking generator and an adapter
ctx := NewDependencyContext(context.Background(), dbGenerator, Adapt[UserAdapter](lookupUser))
// At this point, the database generator should NOT have been called
if atomic.LoadInt32(&dbGeneratorCalled) != 0 {
t.Error("database generator was called during context creation")
}
// Get the adapter - this should also NOT trigger the generator
adapter := Get[UserAdapter](ctx)
if atomic.LoadInt32(&dbGeneratorCalled) != 0 {
t.Error("database generator was called when getting the adapter")
}
// Now call the adapter - this SHOULD trigger the generator
user, err := adapter(ctx, "lazy-user")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Verify the generator was called exactly once
if calls := atomic.LoadInt32(&dbGeneratorCalled); calls != 1 {
t.Errorf("expected database generator to be called once, was called %d times", calls)
}
// Verify the result uses the generated database
if user.Name != "Test User from GeneratedDB" {
t.Errorf("expected user from GeneratedDB, got '%s'", user.Name)
}
// Call the adapter again - generator should not be called again (cached)
user2, err := adapter(ctx, "another-user")
if err != nil {
t.Fatalf("unexpected error on second call: %v", err)
}
// Generator should still have been called only once
if calls := atomic.LoadInt32(&dbGeneratorCalled); calls != 1 {
t.Errorf("expected database generator to be called once total, was called %d times", calls)
}
if user2.Name != "Test User from GeneratedDB" {
t.Errorf("expected user from GeneratedDB on second call, got '%s'", user2.Name)
}
}
// Test with multiple adapters sharing lazy dependencies
func TestAdapterLazyMultipleAdapters(t *testing.T) {
var dbCalls int32
var configCalls int32
dbGen := func(ctx context.Context) (*TestDatabase, error) {
atomic.AddInt32(&dbCalls, 1)
return &TestDatabase{Name: "LazyDB"}, nil
}
configGen := func(ctx context.Context) (*TestConfig, error) {
atomic.AddInt32(&configCalls, 1)
return &TestConfig{APIKey: "lazy-key"}, nil
}
// Create context with generators and multiple adapters
ctx := NewDependencyContext(context.Background(),
dbGen,
configGen,
Adapt[UserAdapter](lookupUser),
Adapt[ComplexAdapter](complexFunction),
)
// No generators should be called yet
if atomic.LoadInt32(&dbCalls) != 0 || atomic.LoadInt32(&configCalls) != 0 {
t.Error("generators called during context creation")
}
// Get both adapters
userAdapter := Get[UserAdapter](ctx)
complexAdapter := Get[ComplexAdapter](ctx)
// Still no generators should be called
if atomic.LoadInt32(&dbCalls) != 0 || atomic.LoadInt32(&configCalls) != 0 {
t.Error("generators called when getting adapters")
}
// Call user adapter - should only trigger DB generator
_, err := userAdapter(ctx, "user1")
if err != nil {
t.Fatalf("error calling user adapter: %v", err)
}
if dbCalls := atomic.LoadInt32(&dbCalls); dbCalls != 1 {
t.Errorf("expected DB generator called once, was called %d times", dbCalls)
}
if configCalls := atomic.LoadInt32(&configCalls); configCalls != 0 {
t.Errorf("expected config generator not called, was called %d times", configCalls)
}
// Call complex adapter - should trigger config generator but not DB again
result, err := complexAdapter(ctx, "test", 42)
if err != nil {
t.Fatalf("error calling complex adapter: %v", err)
}
if dbCalls := atomic.LoadInt32(&dbCalls); dbCalls != 1 {
t.Errorf("expected DB generator still called once, was called %d times", dbCalls)
}
if configCalls := atomic.LoadInt32(&configCalls); configCalls != 1 {
t.Errorf("expected config generator called once, was called %d times", configCalls)
}
expected := "LazyDB:lazy-key:test:" + string(rune(42))
if result != expected {
t.Errorf("expected '%s', got '%s'", expected, result)
}
}