Skip to content

Commit

Permalink
Allow using dig.As with dig.Group (#375)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
tchung1118 authored Jan 30, 2023
1 parent 5ae7b1f commit c8f963c
Show file tree
Hide file tree
Showing 5 changed files with 251 additions and 49 deletions.
51 changes: 51 additions & 0 deletions decorate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,27 @@ import (
"go.uber.org/dig/internal/digtest"
)

type myInt interface {
String() string
Increment()
}
type someInt int

var _ myInt = (*someInt)(nil)

func newSomeInt(i int) *someInt {
v := someInt(i)
return &v
}

func (i *someInt) String() string {
return fmt.Sprintf("%d", i)
}

func (i *someInt) Increment() {
*i += 1
}

func TestDecorateSuccess(t *testing.T) {
t.Run("simple decorate without names or groups", func(t *testing.T) {
t.Parallel()
Expand Down Expand Up @@ -124,6 +145,36 @@ func TestDecorateSuccess(t *testing.T) {
})
})

t.Run("decorate grouped values provided as", func(t *testing.T) {
t.Parallel()

type A struct {
dig.In
Values []myInt `group:"values"`
}

type B struct {
dig.Out
Values []myInt `group:"values"`
}

c := digtest.New(t)

for i := range make([]int, 3) {
i := i
c.RequireProvide(func() *someInt { return newSomeInt(i) }, dig.Group("values"), dig.As(new(myInt)))
}
c.Decorate(func(in A) B {
for _, v := range in.Values {
v.Increment()
}
return B{Values: in.Values}
})
c.RequireInvoke(func(a A) {
assert.ElementsMatch(t, []myInt{newSomeInt(1), newSomeInt(2), newSomeInt(3)}, a.Values)
})
})

t.Run("value groups with multiple decorations", func(t *testing.T) {
type params struct {
dig.In
Expand Down
Loading

0 comments on commit c8f963c

Please sign in to comment.