How do I automatically clean the go cache in Visual Code before running tests?

Viewed 3668

There is a small nuisance with Visual Code and Go, but is mainly related to the most recent release of go 1.11.x and the newly introduced module system. The go builder creates a folder called 'auto' for cached builds, which can be cleaned / deleted via 'go clean -cache'.

Visual Code seems to be confused when executing tests, if such a directory is present, and complains about missing dependencies:

/home/user/.golang/src/github.com/stretchr/testify/assert/assertions.go:20:2: could not import github.com/pmezard/go-difflib/difflib (open auto/4c/4cb1f0f2c9f328e3cade99998704759897fd4e530af38db25c85cdc253c1f1a0-d: no such file or directory)

is there any possibility to fix this? Or is it just another setting I forgot to make?

3 Answers

Try setting the environment variable GOCACHE=off.

Warning from issue 26809 ("GOCACHE=off causes modules to exit the tests"):

The GOCACHE env variable will be phased out out in 1.12, and cannot be used with go modules enabled in 1.11

Configuring VSCode to use using go test -count=1 ... is safer.

The Go 1.12 release notes (for February 2019) makes that official:

Build cache requirement

The build cache is now required as a step toward eliminating $GOPATH/pkg.
Setting the environment variable GOCACHE=off will cause go commands that write to the cache to fail.

In 2022...

  1. Open settings.json in Visual Studio Code with either:

    • For Global setting, open Preferences > Settings from the menu bar.

      • Search for go.testFlags.
      • Under Go: Test Flags, click Edit in settings.json.
    • For Project-only setting, open/create file at [project_root]/.vscode/settings.json

  2. In settings.json, add the following value to the go.testFlags key:

     {    
         "go.testFlags": ["-count=1"]
     }
    
  3. Save and enjoy.

Note: these steps ensure test cache will be skipped every time like OP desires. If you instead want a one-time fix, then run go clean -testcache in the terminal.

Related