Build cache versus test-result cache
Build cache versus test-result cache
Go caches compilation results and, in package-list mode, eligible successful test results. A repeated go test . may display (cached) without executing the test binary again. go test -count=1 . disables test-result reuse but still permits build caching. The build cache depends on source, compiler and flags; it is not the same as the downloaded module cache. To observe this safely, use a temporary module and never clean a shared cache as part of routine CI.
package main
import ( "encoding/json" "fmt" "os/exec")
func main() { out, err := exec.Command("go", "env", "-json", "GOCACHE", "GOMODCACHE").Output() if err != nil { panic(err) } var v map[string]string if err = json.Unmarshal(out, &v); err != nil { panic(err) } fmt.Println(v["GOCACHE"] != "", v["GOMODCACHE"] != "")}GOCACHE holds reusable build data; GOMODCACHE holds modules. The paths alone do not prove a cache hit. In a disposable module containing a passing test, run go test . twice, then go test -count=1 .. Inspect the actual output. The cache considers eligible flags and observed inputs; not every invocation is cacheable. Local-directory mode (go test without package arguments) does not use test-result caching.
Expected output:
true trueObserve cache eligibility in a transcript
package main
import ( "fmt" "strings")
func cached(line string) bool { f := strings.Fields(line) return len(f) >= 3 && f[0] == "ok" && f[len(f)-1] == "(cached)"}func main() { fmt.Println(cached("ok example.org/demo (cached)")) fmt.Println(cached("ok example.org/demo 0.003s")) fmt.Println(cached("FAIL example.org/demo"))}This classifier is a teaching aid for the conventional human-readable summary, not a stable parser for every go test output. For machine evidence prefer go test -json and retain the invocation. GODEBUG=gocachetest=1 explains test cache decisions; gocachehash=1 is very verbose. Changes to external C libraries may escape build-cache detection: rebuild affected cgo packages with -a or use an isolated clean cache. Do not confuse go clean -testcache with -modcache.
Expected output:
truefalsefalseTry it locally
Write a cache-transcript summary that counts cached success lines and uncached success lines, ignoring other output. Test one of each.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Toolchain and compatibility 02: Build cache versus test-result cache
Check the lesson objective before moving on.
What does -count=1 prevent?
Which cache stores downloaded modules?