Skip to content

Commit

Permalink
Add imports for Named Type's type arguments (#199)
Browse files Browse the repository at this point in the history
  • Loading branch information
TimVosch committed Jun 21, 2023
1 parent 373b8f9 commit 3795b74
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 1 deletion.
7 changes: 7 additions & 0 deletions internal/registry/method_scope.go
Expand Up @@ -82,6 +82,13 @@ func (m MethodScope) populateImports(t types.Type, imports map[string]*Package)
if pkg := t.Obj().Pkg(); pkg != nil {
imports[stripVendorPath(pkg.Path())] = m.registry.AddImport(pkg)
}
// The imports of a Type with a TypeList must be added to the imports list
// For example: Foo[otherpackage.Bar] , must have otherpackage imported
if targs := t.TypeArgs(); targs != nil {
for i := 0; i < targs.Len(); i++ {
m.populateImports(targs.At(i), imports)
}
}

case *types.Array:
m.populateImports(t.Elem(), imports)
Expand Down
9 changes: 8 additions & 1 deletion pkg/moq/moq_test.go
Expand Up @@ -389,6 +389,12 @@ func TestMockGolden(t *testing.T) {
interfaces: []string{"GenericStore1", "GenericStore2", "AliasStore"},
goldenFile: filepath.Join("testpackages/generics", "generics_moq.golden.go"),
},
{
name: "Generic Return Argument Type",
cfg: Config{SrcDir: "testpackages/genericreturn"},
interfaces: []string{"IFooBar"},
goldenFile: filepath.Join("testpackages/genericreturn", "genericreturn.golden.go"),
},
{
name: "TransientImport",
cfg: Config{SrcDir: "testpackages/transientimport"},
Expand Down Expand Up @@ -659,7 +665,8 @@ func TestParseError(t *testing.T) {
t.Errorf("expected error but got nil")
return
}
if !strings.Contains(err.Error(), `could not import github.com/matryer/notexist (invalid package name: "")`) {
// The first clause is the common error. Only in go version 1.19.10 the error differs
if !strings.Contains(err.Error(), `could not import github.com/matryer/notexist (invalid package name: "")`) && !strings.Contains(err.Error(), "stderr: go build github.com/matryer/notexist") {
t.Errorf("unexpected error: %s", err.Error())
}
}
Expand Down
11 changes: 11 additions & 0 deletions pkg/moq/testpackages/genericreturn/genericreturn.go
@@ -0,0 +1,11 @@
package genericreturn

import "github.com/matryer/moq/pkg/moq/testpackages/genericreturn/otherpackage"

type GenericBar[T any] struct {
Bar T
}

type IFooBar interface {
Foobar() GenericBar[otherpackage.Foo]
}
68 changes: 68 additions & 0 deletions pkg/moq/testpackages/genericreturn/genericreturn.golden.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

@@ -0,0 +1,6 @@
package otherpackage

type Foo struct {
A int
B string
}

0 comments on commit 3795b74

Please sign in to comment.