Description
What I want to achieve
I want to write tests for analyzers that utilize packages.Module
information.
x/tools/go/analysis/analysistest
provides helper functions for testing go/analysis
analyzers.
// It loads the packages from the specified GOPATH-style project
// directory using golang.org/x/tools/go/packages, ...
func Run(t Testing, dir string, a *analysis.Analyzer, patterns ...string) []*Result
// RunWithSuggestedFixes behaves like Run, ...
func RunWithSuggestedFixes(t Testing, dir string, a *analysis.Analyzer, patterns ...string) []*Result
Run
andRunWithSuggestedFixes
internally callgo/packages.Load
but explicitly in GOPATH mode.- The
dir
is supposed to be GOPATH, which doesn't apply in module mode. packages.Config
is not accepted.
These limit the utility of the package when authoring module-aware analyzers.
What I propose
I propose to add module-friendly test helpers. Something like:
func TestAnalyzer(t Testing, a *analysis.Analyzer, pkgs *[]packages.Package) []*Result
or
func TestAnalyzer(t Testing, a *analysis.Analyzer, cfg *packages.Config, patterns ...string) []*Result
Alternatives to consider
GOPATH style project layout is easy and convenient. For the last half decade, nobody
complained about this issue, which indicates supporting module mode in this package is not
important. My analyzer is not a typical one.
So I considered -
-
Refactor and move the core of
x/tools/go/analysis/analysistest
tox/tools/internal/analysisinternal/...
. Unfortunately, I see this will cause move ofx/tools/go/analysis/internal/checker
andanalysisflags
. I like containinganalysis
specific internal logic under x/tools/go/analysis/internal and am not sure about this big move. -
Make part of
analysistest.Run
available through a var inx/tools/internal/analysisinternal/...
that's set by analysistest init. See CL408375 This is a smaller change than 2, but documentation for the type aliasedanalysistest.Testing
andchecker.TestAnalyzerResult
isn't great.
What about WriteFiles
It also supports only GOPATH mode. WriteFiles
can be potentially replaced with go/packages/packagestest
.
// WriteFiles is a helper function that creates a temporary directory
// and populates it with a GOPATH-style project using filemap...
func WriteFiles(filemap map[string]string) (dir string, cleanup func(), err error)
But for a simple analyzer test, this is more convenient than the helpers in go/packages/packagestest
.
cc @golang/tools-team