Skip to content

Commit c8f963c

Browse files
authored
Allow using dig.As with dig.Group (#375)
This PR adds the ability to use dig.As with dig.Group. When dig.As is used with dig.Group, the value produced by the constructor will be provided to the specified group as the type specified by dig.As. ``` c.Provide(newBuffer, dig.As(new(io.Reader)), dig.Group("readers")) ``` For example, the above code is equivalent to the following. ``` c.Provide(func(...) io.Reader { b := newBuffer(...) return b }, dig.Group("readers")) ``` Fixes #341
1 parent 5ae7b1f commit c8f963c

File tree

5 files changed

+251
-49
lines changed

5 files changed

+251
-49
lines changed

decorate_test.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,27 @@ import (
3232
"go.uber.org/dig/internal/digtest"
3333
)
3434

35+
type myInt interface {
36+
String() string
37+
Increment()
38+
}
39+
type someInt int
40+
41+
var _ myInt = (*someInt)(nil)
42+
43+
func newSomeInt(i int) *someInt {
44+
v := someInt(i)
45+
return &v
46+
}
47+
48+
func (i *someInt) String() string {
49+
return fmt.Sprintf("%d", i)
50+
}
51+
52+
func (i *someInt) Increment() {
53+
*i += 1
54+
}
55+
3556
func TestDecorateSuccess(t *testing.T) {
3657
t.Run("simple decorate without names or groups", func(t *testing.T) {
3758
t.Parallel()
@@ -124,6 +145,36 @@ func TestDecorateSuccess(t *testing.T) {
124145
})
125146
})
126147

148+
t.Run("decorate grouped values provided as", func(t *testing.T) {
149+
t.Parallel()
150+
151+
type A struct {
152+
dig.In
153+
Values []myInt `group:"values"`
154+
}
155+
156+
type B struct {
157+
dig.Out
158+
Values []myInt `group:"values"`
159+
}
160+
161+
c := digtest.New(t)
162+
163+
for i := range make([]int, 3) {
164+
i := i
165+
c.RequireProvide(func() *someInt { return newSomeInt(i) }, dig.Group("values"), dig.As(new(myInt)))
166+
}
167+
c.Decorate(func(in A) B {
168+
for _, v := range in.Values {
169+
v.Increment()
170+
}
171+
return B{Values: in.Values}
172+
})
173+
c.RequireInvoke(func(a A) {
174+
assert.ElementsMatch(t, []myInt{newSomeInt(1), newSomeInt(2), newSomeInt(3)}, a.Values)
175+
})
176+
})
177+
127178
t.Run("value groups with multiple decorations", func(t *testing.T) {
128179
type params struct {
129180
dig.In

0 commit comments

Comments
 (0)