matryer / moq

Interface mocking tool for go generate
http://bit.ly/meetmoq
MIT License
2k stars 127 forks source link

Moq creates non-unique import aliases #184

Closed cldmstr closed 2 years ago

cldmstr commented 2 years ago

In one of our projects I have an, admittedly quite exotic, edge-case where we're mocking an interface from another package and the transient imports all have the same package name at the end of the path. The conflict resolve mechanism for aliases doesn't work in this case, as it only looks at 2 conflicting packages at a time.

To reproduce it requires at least 4 imports and you need to be mocking an interface from another package, so not setting unique aliases yourself.

Mocked Interface

package transientimport

import (
    "github.com/matryer/moq/pkg/moq/testpackages/transientimport/base"
)

type Transient = base.Transient

Original Interface

package base

import (
    four "github.com/matryer/moq/pkg/moq/testpackages/transientimport/four/app/v1"
    one "github.com/matryer/moq/pkg/moq/testpackages/transientimport/one/v1"
    three "github.com/matryer/moq/pkg/moq/testpackages/transientimport/three/v1"
    two "github.com/matryer/moq/pkg/moq/testpackages/transientimport/two/app/v1"
)

type Transient interface {
    DoSomething(one.One, two.Two, three.Three, four.Four)
}

The origin is that we're using an interface from the k8s.io/client-go/kubernetes package and want to use mocks of that interface in our tests.

I put together a test case and possible solution here: https://github.com/cldmstr/moq/tree/unique-import-aliases

matryer commented 2 years ago

@cldmstr thanks for opening this - can you please explain your proposed solution?

sudo-suhas commented 2 years ago

Thank you very much @cldmstr for proposing a solution along with the issue! However, there is still a chance of conflict if, for example, the Transient interface imported and used a package named fourappv1. Will raise a PR that should address it, will need your help in testing it (already checked against bespinian/livelint.

cldmstr commented 2 years ago

Thanks a lot for looking into this @sudo-suhas. Yes, I think your solution is definitely more complete and will solve any such problems, no matter the level.