Skip to content

Aliased imports don't propagate well in the generated mocks (at least in source mode) #166

@mtoader

Description

@mtoader

Generating a mock, in source mode, for an interface that references types from an imported package that is aliased will not generate the same alias in the generated output. This creates problems when you want to generate within the same package since other tools, mockgen included, can't deal with packages that import other package with different aliases.

Expected behavior A clear and concise description of what you expected to
happen.

The generated mock should use the same aliases as the source package.

To Reproduce Steps to reproduce the behavior

  1. Try to generate a mock for a file like this:
package import_aliased

import (
	definition_alias "github.com/package/definition"
)

//go:generate mockgen -package import_aliased -destination source_mock.go -source=source.go -imports definition_alias=github.com/package/definition

type S interface {
	M(definition_alias.X)
}
  1. The generated file preamble will look like
// Code generated by MockGen. DO NOT EDIT.
// Source: source.go
//
// Generated by this command:
//
//	mockgen -package import_aliased -destination source_mock.go -source=source.go -imports definition_alias=github.com/package/definition
//

// Package import_aliased is a generated GoMock package.
package import_aliased

import (
	reflect "reflect"

	definition "github.com/package/definition"
	gomock "go.uber.org/mock/gomock"
)

// MockS is a mock of S interface.
type MockS struct {
	ctrl     *gomock.Controller
	recorder *MockSMockRecorder
}
...

notice that now the import_aliased package imports the github.com/package/definition with two aliases: definition and definition_alias. This is not a real problem for the go compiler but mockgen itself can't handle it. The right thing here is for generated file to reference the import with the same alias.

Additional Information

  • gomock mode (reflect or source): source
  • gomock version or git ref: 986b50e
  • golang version: 1.20 - 1.22

Triage Notes for the Maintainers

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions