This repository was archived by the owner on Aug 13, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplan_test.go
More file actions
973 lines (869 loc) · 25.2 KB
/
Copy pathplan_test.go
File metadata and controls
973 lines (869 loc) · 25.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
package plan_test
import (
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"strings"
"testing"
"github.com/mickamy/injector/internal/diag"
"github.com/mickamy/injector/internal/ir"
"github.com/mickamy/injector/internal/packages"
"github.com/mickamy/injector/internal/plan"
"github.com/mickamy/injector/internal/scan"
)
func TestBuild_SimpleChain(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type User struct{}
func NewDB() *DB { return nil }
func NewUser(db *DB) *User { return nil }
type Container struct {
User *User ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if got, want := p.ConstructorName, "NewContainer"; got != want {
t.Errorf("ConstructorName = %q, want %q", got, want)
}
if len(p.Steps) != 2 {
t.Fatalf("steps = %d, want 2", len(p.Steps))
}
if p.Steps[0].Provider == nil || p.Steps[0].Provider.FuncName != "NewDB" {
t.Errorf("step[0] = %+v, want NewDB", p.Steps[0])
}
if p.Steps[1].Provider == nil || p.Steps[1].Provider.FuncName != "NewUser" {
t.Errorf("step[1] = %+v, want NewUser", p.Steps[1])
}
if len(p.Outputs) != 1 || p.Outputs[0].FieldName != "User" {
t.Errorf("outputs = %+v", p.Outputs)
}
if p.ReturnsError {
t.Errorf("ReturnsError = true, want false")
}
}
func TestBuild_WithErrorPropagates(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
func NewDB() (*DB, error) { return nil, nil }
type Container struct {
DB *DB ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if !p.ReturnsError {
t.Errorf("ReturnsError = false, want true")
}
}
func TestBuild_ArgInput(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type User struct{}
func NewUser(db *DB) *User { return nil }
type Container struct {
_ *DB ` + "`inject:\"arg\"`" + `
User *User ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if len(p.Inputs) != 1 || p.Inputs[0].Name != "db" {
t.Errorf("inputs = %+v", p.Inputs)
}
if p.Steps[0].Kind != plan.StepKindInput {
t.Errorf("step[0].Kind = %v, want StepKindInput", p.Steps[0].Kind)
}
}
func TestBuild_ArgWithCustomName(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
func NewUserish(db *DB) *DB { return nil }
type Container struct {
_ *DB ` + "`inject:\"arg=primary\"`" + `
DB *DB ` + "`inject:\"with=NewUserish\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if len(p.Inputs) != 1 || p.Inputs[0].Name != "primary" {
t.Errorf("inputs = %+v, want name=primary", p.Inputs)
}
}
func TestBuild_OverrideAmbiguous(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type User struct{}
func NewWriter() *DB { return nil }
func NewReader() *DB { return nil }
func NewUser(db *DB) *User { return nil }
type Container struct {
_ *DB ` + "`inject:\"with=NewWriter\"`" + `
User *User ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
var sawWriter bool
for _, s := range p.Steps {
if s.Provider == nil {
continue
}
switch s.Provider.FuncName {
case "NewWriter":
sawWriter = true
case "NewReader":
t.Errorf("NewReader should not appear in the plan when override is NewWriter")
case "NewUser":
if !sawWriter {
t.Errorf("NewWriter must precede NewUser, got steps: %+v", p.Steps)
}
}
}
if !sawWriter {
t.Errorf("expected NewWriter step, got %+v", p.Steps)
}
}
func TestBuild_FieldBoundStepUsesFieldName(t *testing.T) {
t.Parallel()
// `Tx Transactor inject:""` should produce a variable named after the
// destination field — "tx" — rather than the function ("new") or the
// result type ("transactor").
src := `package test
type Transactor struct{}
func New() Transactor { return Transactor{} }
type Container struct {
Tx Transactor ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if len(p.Steps) != 1 {
t.Fatalf("steps = %d, want 1", len(p.Steps))
}
if got, want := p.Steps[0].VarName, "tx"; got != want {
t.Errorf("var name = %q, want %q", got, want)
}
}
func TestBuild_IntermediateStepUsesResultType(t *testing.T) {
t.Parallel()
// `New() *Foo` consumed transitively by `Make` (whose result is the
// container's field) is an intermediate step with no field name to
// borrow from. It should fall back to the result type — "foo" — not
// the function name.
src := `package test
type Foo struct{}
type Bar struct{}
func New() *Foo { return nil }
func Make(f *Foo) *Bar { return nil }
type Container struct {
Bar *Bar ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
var fooStep, barStep plan.Step
for _, s := range p.Steps {
switch {
case s.Provider != nil && s.Provider.FuncName == "New":
fooStep = s
case s.Provider != nil && s.Provider.FuncName == "Make":
barStep = s
}
}
if got, want := fooStep.VarName, "foo"; got != want {
t.Errorf("intermediate var name = %q, want %q", got, want)
}
if got, want := barStep.VarName, "bar"; got != want {
t.Errorf("field-bound var name = %q, want %q", got, want)
}
}
func TestBuild_FieldNameSwapNoUnnecessarySuffix(t *testing.T) {
t.Parallel()
// Two steps want to swap names: step A holds "foo" (result type Foo)
// and is bound to a "Db" field (wants "db"), while step B holds "db"
// (result type Db) and is bound to a "Foo" field (wants "foo"). The
// rename pass must vacate both old names before picking the new ones
// so each side gets its preferred name without a `_2` suffix.
src := `package test
type Foo struct{}
type Db struct{}
func NewFoo() Foo { return Foo{} }
func NewDb() Db { return Db{} }
type Container struct {
Db Foo ` + "`inject:\"\"`" + `
Foo Db ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
bindings := map[string]string{}
for _, o := range p.Outputs {
bindings[o.FieldName] = p.Steps[o.StepIndex].VarName
}
if got, want := bindings["Db"], "db"; got != want {
t.Errorf("field Db var = %q, want %q (swap should not force a suffix)", got, want)
}
if got, want := bindings["Foo"], "foo"; got != want {
t.Errorf("field Foo var = %q, want %q (swap should not force a suffix)", got, want)
}
}
func TestBuild_TypeAliasResultDerivesAliasName(t *testing.T) {
t.Parallel()
// A provider returning a type alias used to fall through deriveInputName's
// *types.Named check (alias is *types.Alias in Go 1.22+), leaving the
// variable to fall back to the function name. After types.Unalias is
// applied inside deriveInputName, the alias's target name flows through.
src := `package test
type Real struct{}
type Alias = Real
func New() Alias { return Alias{} }
type Container struct {
V Alias ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
// Steps are: one provider step (New). It's field-bound to V → renamed
// to lowerFirst("V") = "v". The interesting check is the intermediate
// case: if no field were attached, we'd want "real" not "new" / "arg".
// Reuse the existing intermediate-naming test shape:
src2 := `package test
type Real struct{}
type Alias = Real
type Wrap struct{}
func New() Alias { return Alias{} }
func Wrapper(a Alias) Wrap { return Wrap{} }
type Container struct {
W Wrap ` + "`inject:\"\"`" + `
}
`
p2, _ := mustBuild(t, src2, "Container", plan.Options{})
var aliasStep plan.Step
for _, s := range p2.Steps {
if s.Provider != nil && s.Provider.FuncName == "New" {
aliasStep = s
break
}
}
if got, want := aliasStep.VarName, "real"; got != want {
t.Errorf("alias intermediate var = %q, want %q (Unalias should resolve to Real)", got, want)
}
// Sanity: the field-bound case in p (V Alias) lands on "v" through
// the rename pass.
if p.Outputs[0].FieldName != "V" || p.Steps[p.Outputs[0].StepIndex].VarName != "v" {
t.Errorf("field-bound alias did not land on field name; outputs=%+v steps=%+v",
p.Outputs, p.Steps)
}
}
func TestBuild_SharedStepDoesNotLeakCandidate(t *testing.T) {
t.Parallel()
// Two container fields share the same provider step (both want *DB).
// The naive rename pass would queue the step twice — once with "db"
// and once with "backup" — and mark both names as used, forcing an
// unrelated step that wanted "backup" onto "backup2". The decided-
// once gate ensures only the first field name is queued.
src := `package test
type DB struct{}
type Backup struct{}
func NewDB() *DB { return nil }
func NewBackup() *Backup { return nil }
type Container struct {
DB *DB ` + "`inject:\"\"`" + `
Backup *Backup ` + "`inject:\"\"`" + `
Twin *DB ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
var backupVar string
for _, s := range p.Steps {
if s.Provider != nil && s.Provider.FuncName == "NewBackup" {
backupVar = s.VarName
break
}
}
if got, want := backupVar, "backup"; got != want {
t.Errorf("NewBackup var = %q, want %q (Twin sharing *DB must not leak the name)", got, want)
}
}
func TestBuild_SharedStepPreservesMatchingFieldName(t *testing.T) {
t.Parallel()
// Step's existing name "db" already matches field "DB"; another
// field "Backup" also binds to the same step. The first match
// should leave the variable alone instead of subsequently renaming
// it to "backup".
src := `package test
type DB struct{}
func NewDB() *DB { return nil }
type Container struct {
DB *DB ` + "`inject:\"\"`" + `
Backup *DB ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if len(p.Steps) != 1 {
t.Fatalf("steps = %d, want 1", len(p.Steps))
}
if got, want := p.Steps[0].VarName, "db"; got != want {
t.Errorf("shared-step var = %q, want %q (matching field name should win)", got, want)
}
}
func TestBuild_SelfGeneratedProviderIgnored(t *testing.T) {
t.Parallel()
// A `inject:"returns"` container whose previously generated
// constructor is now visible to the provider scan must not pick that
// constructor up as a candidate when resolving its own field, or it
// would loop forever. The unrelated, non-self provider remains usable.
src := `package test
type Greeter interface{ Greet() string }
type greeterImpl struct{}
func (greeterImpl) Greet() string { return "" }
func NewGreeterImpl() Greeter { return greeterImpl{} }
// Pretend this came from a previous generation of NewWrapper.
func NewWrapper() Greeter { return nil }
type wrapper struct {
service Greeter ` + "`inject:\"returns\"`" + `
}
`
p, ds := build(t, src, "wrapper", plan.Options{})
if diag.HasErrors(ds) {
t.Fatalf("expected the self provider NewWrapper to be filtered out, got %v", ds)
}
if len(p.Steps) != 1 || p.Steps[0].Provider == nil || p.Steps[0].Provider.FuncName != "NewGreeterImpl" {
t.Errorf("expected NewGreeterImpl to be the only provider step; got %+v", p.Steps)
}
}
func TestBuild_FieldNameTakenForcesSuffix(t *testing.T) {
t.Parallel()
// An intermediate step's natural name ("tx", from result type Tx)
// already occupies that slot, then a field-bound step (field "Tx",
// holding a different type) tries to claim "tx" too. The field-bound
// step should cascade to "tx2" — the simple-cascade behavior chosen
// in option A.
src := `package test
type Tx struct{}
type Other struct{}
func NewTx() Tx { return Tx{} }
func NewOther(Tx) Other { return Other{} }
type Container struct {
Tx Other ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
var intermediate, fieldBound plan.Step
for _, s := range p.Steps {
switch {
case s.Provider != nil && s.Provider.FuncName == "NewTx":
intermediate = s
case s.Provider != nil && s.Provider.FuncName == "NewOther":
fieldBound = s
}
}
if got, want := intermediate.VarName, "tx"; got != want {
t.Errorf("intermediate var = %q, want %q", got, want)
}
if got, want := fieldBound.VarName, "tx2"; got != want {
t.Errorf("field-bound var = %q, want %q (cascade)", got, want)
}
}
func TestBuild_NonBlankWithActsAsOverride(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type User struct{}
func NewWriter() *DB { return nil }
func NewReader() *DB { return nil }
func NewUser(db *DB) *User { return nil }
type Container struct {
DB *DB ` + "`inject:\"with=NewWriter\"`" + `
User *User ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
for _, s := range p.Steps {
if s.Provider != nil && s.Provider.FuncName == "NewReader" {
t.Errorf("NewReader must not appear when DB is pinned to NewWriter; steps=%+v", p.Steps)
}
}
var hasDBOutput, hasUserOutput bool
for _, o := range p.Outputs {
switch o.FieldName {
case "DB":
hasDBOutput = true
case "User":
hasUserOutput = true
}
}
if !hasDBOutput || !hasUserOutput {
t.Errorf("expected both DB and User outputs, got %+v", p.Outputs)
}
}
func TestBuild_NonBlankWithConflictingProviders(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
func NewWriter() *DB { return nil }
func NewReader() *DB { return nil }
type Container struct {
A *DB ` + "`inject:\"with=NewWriter\"`" + `
B *DB ` + "`inject:\"with=NewReader\"`" + `
}
`
_, ds := build(t, src, "Container", plan.Options{})
if !diag.HasErrors(ds) {
t.Fatalf("expected conflicting-providers diag, got %v", ds)
}
}
func TestBuild_AmbiguousProviderError(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
func NewWriter() *DB { return nil }
func NewReader() *DB { return nil }
type Container struct {
DB *DB ` + "`inject:\"\"`" + `
}
`
p, ds := build(t, src, "Container", plan.Options{})
if !diag.HasErrors(ds) {
t.Fatalf("expected ambiguity error, got plan=%+v diags=%v", p, ds)
}
}
func TestBuild_NoProviderError(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type Container struct {
DB *DB ` + "`inject:\"\"`" + `
}
`
p, ds := build(t, src, "Container", plan.Options{})
if !diag.HasErrors(ds) {
t.Fatalf("expected missing provider error, got plan=%+v diags=%v", p, ds)
}
}
func TestBuild_DirectiveReturnTypeOverridesPointer(t *testing.T) {
t.Parallel()
src := `package test
type Greeter interface{ Greet() string }
type greeterImpl struct{}
func (greeterImpl) Greet() string { return "" }
func NewImpl() *greeterImpl { return nil }
//injector:container returns=Greeter
type app struct {
G *greeterImpl ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "app", plan.Options{})
if p.ReturnType == nil {
t.Fatal("ReturnType is nil")
}
if got := plan.TypeString(p.ReturnType); got != "test.Greeter" {
t.Errorf("ReturnType = %s, want test.Greeter", got)
}
}
func TestBuild_TagReturnsSetsReturnType(t *testing.T) {
t.Parallel()
src := `package test
type Greeter interface{ Greet() string }
type greeterImpl struct{}
func (greeterImpl) Greet() string { return "" }
func NewImpl() *greeterImpl { return nil }
type app struct {
G *greeterImpl ` + "`inject:\"returns\"`" + `
}
`
p, _ := mustBuild(t, src, "app", plan.Options{})
if p.ReturnType == nil {
t.Fatal("ReturnType is nil")
}
if got := plan.TypeString(p.ReturnType); got != "*test.greeterImpl" {
t.Errorf("ReturnType = %s, want *test.greeterImpl", got)
}
if len(p.Outputs) != 1 || p.Outputs[0].FieldName != "G" {
t.Errorf("outputs = %+v", p.Outputs)
}
}
func TestBuild_DirectiveAndTagReturnsConflict(t *testing.T) {
t.Parallel()
src := `package test
type Greeter interface{ Greet() string }
type greeterImpl struct{}
func (greeterImpl) Greet() string { return "" }
func NewImpl() *greeterImpl { return nil }
//injector:container returns=Greeter
type app struct {
_ Greeter ` + "`inject:\"returns\"`" + `
G *greeterImpl ` + "`inject:\"\"`" + `
}
`
_, ds := build(t, src, "app", plan.Options{})
if !diag.HasErrors(ds) {
t.Fatalf("expected conflict error, got %v", ds)
}
}
func TestBuild_DuplicateArgName(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type Cache struct{}
type Container struct {
_ *DB ` + "`inject:\"arg=primary\"`" + `
_ *Cache ` + "`inject:\"arg=primary\"`" + `
DB *DB ` + "`inject:\"\"`" + `
}
`
_, ds := build(t, src, "Container", plan.Options{})
if !diag.HasErrors(ds) {
t.Fatalf("expected duplicate input name diagnostic, got %v", ds)
}
var found bool
for _, d := range ds {
if d.Severity == diag.SeverityError && strings.Contains(d.Message, "duplicate input name") {
found = true
break
}
}
if !found {
t.Errorf("expected diagnostic mentioning %q, got %v", "duplicate input name", ds)
}
}
func TestBuild_MustModes(t *testing.T) {
t.Parallel()
tests := []struct {
name string
src string
opts plan.Options
wantOn bool
}{
{
name: "no directive, cli off",
src: `package test
type Container struct { X X ` + "`inject:\"\"`" + ` }
type X struct{}
func NewX() X { return X{} }`,
opts: plan.Options{Must: false},
wantOn: false,
},
{
name: "no directive, cli on",
src: `package test
type Container struct { X X ` + "`inject:\"\"`" + ` }
type X struct{}
func NewX() X { return X{} }`,
opts: plan.Options{Must: true},
wantOn: true,
},
{
name: "directive must=true overrides cli off",
src: `package test
//injector:container must=true
type Container struct { X X ` + "`inject:\"\"`" + ` }
type X struct{}
func NewX() X { return X{} }`,
opts: plan.Options{Must: false},
wantOn: true,
},
{
name: "directive must=false overrides cli on",
src: `package test
//injector:container must=false
type Container struct { X X ` + "`inject:\"\"`" + ` }
type X struct{}
func NewX() X { return X{} }`,
opts: plan.Options{Must: true},
wantOn: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
p, _ := mustBuild(t, tt.src, "Container", tt.opts)
if p.EmitMust != tt.wantOn {
t.Errorf("EmitMust = %v, want %v", p.EmitMust, tt.wantOn)
}
})
}
}
func TestBuild_NonBlankArgIsStored(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type Container struct {
DB *DB ` + "`inject:\"arg\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if len(p.Inputs) != 1 || p.Inputs[0].Name != "db" {
t.Fatalf("inputs = %+v, want one named db", p.Inputs)
}
if len(p.Outputs) != 1 || p.Outputs[0].FieldName != "DB" {
t.Fatalf("outputs = %+v, want one for DB", p.Outputs)
}
if p.Steps[p.Outputs[0].StepIndex].Kind != plan.StepKindInput {
t.Errorf("expected stored arg output to point at an input step; got %+v",
p.Steps[p.Outputs[0].StepIndex])
}
}
func TestBuild_NonBlankArgWithCustomName(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type Container struct {
DB *DB ` + "`inject:\"arg=database\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if p.Inputs[0].Name != "database" {
t.Errorf("input name = %q, want database", p.Inputs[0].Name)
}
if p.Outputs[0].FieldName != "DB" {
t.Errorf("output field = %q, want DB", p.Outputs[0].FieldName)
}
}
func TestBuild_EmbedExposesFields(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type Repo struct{}
type Infra struct {
DB *DB
}
func NewRepo(db *DB) *Repo { return nil }
type Container struct {
_ *Infra ` + "`inject:\"embed\"`" + `
Repo *Repo ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if len(p.Inputs) != 1 || p.Inputs[0].Name != "infra" {
t.Fatalf("inputs = %+v, want one named infra", p.Inputs)
}
var foundEmbed, foundProvider bool
for _, s := range p.Steps {
switch s.Kind {
case plan.StepKindEmbedField:
foundEmbed = true
if s.EmbedFieldName != "DB" {
t.Errorf("embed field = %q, want DB", s.EmbedFieldName)
}
if s.InputIndex != 0 {
t.Errorf("embed input index = %d, want 0", s.InputIndex)
}
case plan.StepKindProvider:
foundProvider = true
case plan.StepKindInput:
// not relevant for this assertion
}
}
if !foundEmbed {
t.Errorf("no StepKindEmbedField step emitted; steps=%+v", p.Steps)
}
if !foundProvider {
t.Errorf("no provider step emitted")
}
}
func TestBuild_EmbedPromotedField(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type Repo struct{}
type Common struct{ DB *DB }
type Infra struct{ Common }
func NewRepo(db *DB) *Repo { return nil }
type Container struct {
_ *Infra ` + "`inject:\"embed\"`" + `
Repo *Repo ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
var embed plan.Step
for _, s := range p.Steps {
if s.Kind == plan.StepKindEmbedField {
embed = s
break
}
}
if embed.EmbedFieldName == "" {
t.Fatalf("no embed step found; steps=%+v", p.Steps)
}
if got, want := embed.EmbedFieldName, "Common.DB"; got != want {
t.Errorf("embed field name = %q, want %q", got, want)
}
if embed.VarName != "db" {
t.Errorf("embed var name = %q, want %q", embed.VarName, "db")
}
}
func TestBuild_EmbedShallowerShadowsDeeper(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type Repo struct{}
type Common struct{ DB *DB }
type Infra struct {
Common
DB *DB
}
func NewRepo(db *DB) *Repo { return nil }
type Container struct {
_ *Infra ` + "`inject:\"embed\"`" + `
Repo *Repo ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
for _, s := range p.Steps {
if s.Kind != plan.StepKindEmbedField {
continue
}
if s.EmbedFieldName != "DB" {
t.Errorf("embed field name = %q, want direct DB to shadow Common.DB", s.EmbedFieldName)
}
}
}
func TestBuild_EmbedAmbiguousAtSameDepth(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type Infra struct {
DB1 *DB
DB2 *DB
}
func NewRepo(db *DB) *DB { return nil }
type Container struct {
_ *Infra ` + "`inject:\"embed\"`" + `
DB *DB ` + "`inject:\"with=NewRepo\"`" + `
}
`
_, ds := build(t, src, "Container", plan.Options{})
if !diag.HasErrors(ds) {
t.Fatalf("expected ambiguity error for two *DB fields at same depth, got %v", ds)
}
}
func TestBuild_EmbedRejectsNonStruct(t *testing.T) {
t.Parallel()
src := `package test
type Greeter interface{ Greet() string }
type Container struct {
_ Greeter ` + "`inject:\"embed\"`" + `
}
`
_, ds := build(t, src, "Container", plan.Options{})
if !diag.HasErrors(ds) {
t.Fatalf("expected error diag, got %v", ds)
}
}
func TestBuild_EmbedAmbiguousAcrossEmbeds(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type A struct { DB *DB }
type B struct { DB *DB }
type Container struct {
_ *A ` + "`inject:\"embed\"`" + `
_ *B ` + "`inject:\"embed\"`" + `
}
`
_, ds := build(t, src, "Container", plan.Options{})
if !diag.HasErrors(ds) {
t.Fatalf("expected error diag for duplicate embed field type, got %v", ds)
}
}
func TestBuild_DirectArgWinsOverEmbed(t *testing.T) {
t.Parallel()
src := `package test
type DB struct{}
type Repo struct{}
type Infra struct { DB *DB }
func NewRepo(db *DB) *Repo { return nil }
type Container struct {
_ *Infra ` + "`inject:\"embed\"`" + `
_ *DB ` + "`inject:\"arg\"`" + `
Repo *Repo ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
for _, s := range p.Steps {
if s.Kind == plan.StepKindEmbedField {
t.Errorf("did not expect any embed step when direct arg matches; got %+v", s)
}
}
}
func TestBuild_TypeAliasResolves(t *testing.T) {
t.Parallel()
src := `package test
type Real struct{}
type Alias = Real
func NewAlias() Alias { return Alias{} }
type Container struct {
Field Alias ` + "`inject:\"\"`" + `
}
`
p, _ := mustBuild(t, src, "Container", plan.Options{})
if len(p.Steps) != 1 {
t.Fatalf("steps = %d, want 1", len(p.Steps))
}
if p.Steps[0].Provider == nil || p.Steps[0].Provider.FuncName != "NewAlias" {
t.Errorf("step[0] = %+v, want NewAlias", p.Steps[0])
}
}
// build runs scan + plan on src and returns the plan plus all diagnostics.
func build(t *testing.T, src, containerName string, opts plan.Options) (plan.Plan, []diag.Diag) {
t.Helper()
pkg := loadTestPackage(t, src)
cs, dsC := scan.Containers([]*packages.Package{pkg})
if diag.HasErrors(dsC) {
t.Fatalf("scan.Containers diags: %v", dsC)
}
ps, dsP := scan.Providers([]*packages.Package{pkg})
if diag.HasErrors(dsP) {
t.Fatalf("scan.Providers diags: %v", dsP)
}
var target ir.Container
for _, c := range cs {
if c.StructName == containerName {
target = c
break
}
}
if target.StructName == "" {
t.Fatalf("container %q not found in scan results", containerName)
}
idx := plan.NewIndex(ps)
pl, dsB := plan.Build(target, idx, opts)
return pl, dsB
}
// mustBuild is like build but fails the test if any error diagnostic is
// produced.
func mustBuild(t *testing.T, src, containerName string, opts plan.Options) (plan.Plan, []diag.Diag) {
t.Helper()
pl, ds := build(t, src, containerName, opts)
if diag.HasErrors(ds) {
t.Fatalf("Build returned errors: %v", ds)
}
return pl, ds
}
// loadTestPackage parses and type-checks a self-contained Go source string.
func loadTestPackage(t *testing.T, src string) *packages.Package {
t.Helper()
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "test.go", src, parser.ParseComments)
if err != nil {
t.Fatalf("parse: %v", err)
}
info := &types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
conf := &types.Config{Importer: importer.Default()}
pkg, err := conf.Check("test", fset, []*ast.File{f}, info)
if err != nil {
t.Fatalf("check: %v", err)
}
return &packages.Package{
PkgPath: "test",
Name: "test",
Syntax: []*ast.File{f},
Types: pkg,
TypesInfo: info,
Fset: fset,
}
}