uber-go / mock

GoMock is a mocking framework for the Go programming language.
Apache License 2.0
2.29k stars 116 forks source link

Aliased type is replaced with its destination type #186

Open atombender opened 4 months ago

atombender commented 4 months ago

This appears to only affect reflect mode. Source mode works correctly. It may be that this bug exists because type aliases are not available through reflection. If that is the case, feel free to close.

Actual behavior

Consider these files:

// In foo/foo.go
package foo

import "github.com/atombender/gomock-issue/foo/internal/things"

type Thing = things.Thing
// In foo/internal/things/things.go
package things

type Thing struct{}
// In bar/bar.go
package bar

import "github.com/atombender/gomock-issue/foo"

type Starter interface {
    Start(thing *foo.Thing)
}

The generated mock will look like this:

import (
    reflect "reflect"

    things "github.com/atombender/gomock-issue/foo/internal/things"
    gomock "go.uber.org/mock/gomock"
)
...

func (m *MockStarter) Start(arg0 *things.Thing) {
...

This is a real problem since the things package is internal, e.g. internal/things.go, relative to foo, which is in an adjacent package. This means the compilation fails:

package github.com/atombender/gomock-issue/bar/mocks
    bar/mocks/mocks.go:15:2: use of internal package github.com/atombender/gomock-issue/foo/internal/things not allowed

Expected behavior

The generated mock should actually refer to the original type:

func (m *MockStarter) Start(arg0 *foo.Thing) {

To Reproduce

Repository with full repro. Test with:

$ mockgen -package mocks -destination ./bar/mocks/mocks.go github.com/atombender/gomock-issue/bar Starter
$ go build ./...

Additional Information

serbrech commented 4 months ago

I hit this when generating mocks for azure-sdk-for-go clients because they make heavy use of internal + type alias to export what's needed

ash2k commented 3 months ago

I think reflect mode needs to be updated to use the new API added in Go 1.22: https://github.com/golang/go/issues/63223

serbrech commented 3 months ago

oh, that's a good find! Yes detecting the alias, and having the info on which type is aliased will definitely allow to resolve this cleanly!