bazelbuild / rules_go

Go rules for Bazel
Apache License 2.0
1.35k stars 635 forks source link

How to test an analysis.Analyzer? #3934

Open jschaf opened 1 month ago

jschaf commented 1 month ago

What version of rules_go are you using?

0.47.0

What version of gazelle are you using?

0.36.0

What version of Bazel are you using?

7.1.1

Does this issue reproduce with the latest releases of all the above?

Yes

What operating system and processor architecture are you using?

macOS arm64

Any other potentially useful information about your toolchain?

N/A

What did you do?

I want to test a locally created analyzer using Go sourcecode in a testdata directory.

Test file

func TestAll(t *testing.T) {
    pkgsDriver, err := runfiles.Rlocation("io_bazel_rules_go/go/tools/go_bin_runner/bin/go")
    require.NoError(t, err)
    err = os.Setenv("GOPACKAGESDRIVER", "off")
    require.NoError(t, err)
    err = os.Setenv("PATH", os.Getenv("PATH")+":"+filepath.Dir(pkgsDriver))
    require.NoError(t, err)

    testDataDir, err := runfiles.Rlocation("simc/build/go/lint/channel_suffix/testdata")
    require.NoError(t, err)

    analysistest.Run(t, testDataDir, Analyzer)
}

What did you expect to see?

A passing test.

What did you see instead?

go tool not available: 'go env GOROOT' does not match runtime.GOROOT:

I've tried a few alternatives.

  1. Running the analysis test directly

    func TestAll(t *testing.T) {
    analysistest.Run(t, analysistest.TestData(), Analyzer)
    }
    
    // ERROR: go tool not available: exec: "go": executable file not found in $PATH
  2. Use the gopackagesdriver

func TestAll(t *testing.T) {
    pkgsDriver, err := runfiles.Rlocation("io_bazel_rules_go/go/tools/gopackagesdriver/gopackagesdriver_/gopackagesdriver")
    require.NoError(t, err)
    err = os.Setenv("GOPACKAGESDRIVER", pkgsDriver)
    require.NoError(t, err)

    testDataDir, err := runfiles.Rlocation("simc/build/go/lint/channel_suffix/testdata")
    require.NoError(t, err)

    analysistest.Run(t, testDataDir, Analyzer)
}

// ERROR: analysistest.go:344: loading []: unexpected end of JSON input