matryer / moq

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

Ignore anonymous imports when resolving import aliases #150

Closed maneac closed 3 years ago

maneac commented 3 years ago

Problem

Given the following two files in a package:

file1.go:

package foo

import (
    bar "some.repo/import/bar"
)

type Barrier interface {
    Baz(bar.Qux)
}

...

file2.go:

package foo

import (
    _ "some.repo/import/bar"
)

...

, suppose you want to generate a mock of Barrier.

Today, running moq -out barrier.mock.go . Barrier would produce the following:

barrier.mock.go

package foo

import (
    _ "some.repo/import/bar"
    "sync"
)

...

type BarrierMock struct {
    // BazFunc mocks the Baz method.
    BazFunc(quxer _.Qux)

...

, which is invalid Go :cry: .

Why

This is caused by a specific interaction between two steps:

Combined, the above means the valid bar alias is overwritten by the invalid _ that gets processed later, and applied to the imported types in the generated functions.

Solution

Ignore anonymous imports when constructing the alias map. This means a valid alias will never be overwritten, and as anonymous imports will always be unused by a mock, they will always be safe to ignore.

sudo-suhas commented 3 years ago

Thanks for explaining the problem and proposing the solution. Could we please also add a test case for the same?

sudo-suhas commented 3 years ago

Thank you @maneac for the PR 🎉

Change has been tagged and released in v0.2.2.