golang / mock

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

-self_package does not work when -package is different from the base dir of package path #342

Closed linzhp closed 4 years ago

linzhp commented 5 years ago

Steps to reproduce:

  1. Clone git@github.com:linzhp/go_examples.git to GOPATH
  2. Run mockgen -package core -self_package github.com/linzhp/go_examples/interfaces github.com/linzhp/go_examples/interfaces Methods

What do I expect:

The generated mock should not import github.com/linzhp/go_examples/interfaces because it is specified in -self_package

What do I see instead:

import (
    gomock "github.com/golang/mock/gomock"
    interfaces "github.com/linzhp/go_examples/interfaces"
    reflect "reflect"
)
codyoss commented 5 years ago

Thanks for the report, I will check out your PR soon here!

codyoss commented 4 years ago

I don't think there is an issue here, or at least not with the example you have given. In this example your interface returns a struct, Info, from the core package. Because of this, the mock must include interfaces "github.com/linzhp/go_examples/interfaces"

The output that makes this required:

// getInfo mocks base method
func (m *MockMethods) getInfo() interfaces.Info {
    m.ctrl.T.Helper()
    ret := m.ctrl.Call(m, "getInfo")
    ret0, _ := ret[0].(interfaces.Info)
    return ret0
}

Thoughts?

linzhp commented 4 years ago

Because of this, the mock must include interfaces "github.com/linzhp/go_examples/interfaces"

This is only true when the mock is going to be compiled in a different package. However, the intention here, by specifying -self_package github.com/linzhp/go_examples/interfaces, is to generate the mock and compile it as part of the package github.com/linzhp/go_examples/interfaces. In other words, the mock and Info will be in the same package, so I don't want the import github.com/linzhp/go_examples/interfaces.

Is this a valid use of the -self_package argument?

codyoss commented 4 years ago

Thanks for the clarification. I did not realize the import path did not match package name

For now as a workaround this should work: mockgen -package core -self_package github.com/linzhp/go_examples/interfaces -source=types.go

Still thinking about the change, just want to make sure if does not break other things.

linzhp commented 4 years ago

Yes, source mode works as a workaround. However, source mode is slower under bazel_gomock rule, as it requires constructing a GOPATH in the sandbox.

Thanks for looking into this.

codyoss commented 4 years ago

Fixed with #343.