matryer / moq

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

moq causes import cycle since #62 #64

Closed omarkohl closed 4 years ago

omarkohl commented 6 years ago

Since updating moq a few hours ago we are getting import cycles when re-generating the mocks. I strongly suspect this is due to #62. The line marked with a comment "NEW and causes problems" was not inserted by moq until now.

File: api/usecase/moqproblem/usecase.go

package moqproblem

type File struct {
    Archive string
    Host    string
    Path    string
}

//go:generate moq -pkg moqproblem -out corrupted_file_getter_moq.go . CorruptedFileGetter

type CorruptedFileGetter interface {
    GetCorruptedFiles(archive string) ([]File, error)
}

File: api/usecase/moqproblem/corrupted_file_getter_moq.go

// Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq

package moqproblem

import (
    "private.com/repo.git/api/usecase/moqproblem" // <---------- NEW and causes problems
    "sync"
)

var (
    lockCorruptedFileGetterMockGetCorruptedFiles sync.RWMutex
)

// ...

EDIT: Update the example to be executable. Try it out:

mkdir -p ~/go/src/private.com/repo.git/api/usecase/moqproblem
# Place the first file above in ~/go/src/private.com/repo.git/api/usecase/moqproblem/usecase.go
cd ~/go/src/private.com/repo.git/
go generate ./...
go test ./...

You will get the following error:

can't load package: import cycle not allowed
package private.com/repo.git/api/usecase/moqproblem
    imports private.com/repo.git/api/usecase/moqproblem
import cycle not allowed
package private.com/repo.git/api/usecase/moqproblem
    imports private.com/repo.git/api/usecase/moqproblem
omarkohl commented 6 years ago

The problem goes away if I replace the go:generate command and remove the explicit package.

not:

//go:generate moq -pkg moqproblem -out corrupted_file_getter_moq.go . CorruptedFileGetter

instead:

//go:generate moq -out corrupted_file_getter_moq.go . CorruptedFileGetter

But I still think it is a bug. Why shouldn't it be possible to explicitly state the package even if it is the same as the one where the interface is defined?

sudo-suhas commented 4 years ago

The -pkg flag is meant to be used when the destination package is different (ex: moqproblem_test in the same folder or mocks in a completely different folder by also specifying -out ../mocks/corrupted_file_getter_moq.go).