v3: adds unused import in matryer template with template.skip-ensure
Description
When source package, and target package name are different and template.skip-ensure is true, it adds an unused import
Reproducer
all: false
template: matryer
force-file-write: true
packages:
github.com/org/repo/package/subpackage:
interfaces:
Interfacer:
config:
pkgname: "packagemocks"
dir: "./subpackage/packagemocks"
filename: "mocks.go"
structname: "InterfacerMock"
template-data:
skip-ensure: true
Expected behavior
I would expect it wouldn't try to import an unused import.
Mockery version
v3.5.0
Installation Mechanism
- [X]
go get - [] Pre-built release
- [] homebrew
- [] Other: [please describe]
Go version
go version go1.24.4 darwin/arm64
As an additional data point, if I declare template-data:\n\tskip-ensure: true at the top of the file, it correctly handles the unused import paths.
This is a quirk of how file-level attributes are ingested into the mock generation process. Specifying template-data at the interface level in some cases doesn't make sense because this particular attribute applies to the file as a whole, not the interface. Hopefully it's obvious why: what happens if two interfaces specify conflicting skip-ensure values? Which one do you use?
We do some amount of reconciliation for parameters like this that apply to file-level attributes, but currently we don't do this for template-data parameters. Mockery is supposed to be completely agnostic to the contents of template-data because it's something only consumed by the template itself. You can see that the matryer template looks at the top-level TemplateData: https://github.com/vektra/mockery/blob/v3.5.0/internal/mock_matryer.templ#L19 . This "top-level" data actually comes from the package-level config: https://github.com/vektra/mockery/blob/v3.5.0/internal/template_generator.go#L449 , which itself is inherited from the top-level config.
The only way I can imagine making this easier is if mockery enforces that all interfaces have the same template-data keys/values as the package-level config. Then, an error message could be emitted that very clearly indicates to the user what the exact problem is and how to fix it.
I apologize that this is confusing. There is an impedance mismatch between the way the configuration is structured and what actually gets written out to disk.
The additional problem of the unused import would exist regardless of the other configuration problem I mentioned. The template assumes that if skip-ensure is set that at least one of the mocks also have it set: https://github.com/vektra/mockery/blob/v3.5.0/internal/mock_matryer.templ#L35
I understand clearly why you're getting tripped up here... I'll have to file this as a bug and see if there's a better way to go about this.