env GOTOOLCHAIN=auto
env TESTGO_VERSION=go1.21.1

# Basic switch should work.
env TESTGO_VERSION_SWITCH=switch
go version
stdout go1.21.99

# Toolchain target mismatch should be detected.
env TESTGO_VERSION_SWITCH=mismatch
! go version
stderr '^go: toolchain go1.21.1 invoked to provide go1.21.99$'

# Toolchain loop should be detected.
env TESTGO_VERSION_SWITCH=loop
! go version
stderr -count=10 '^go: switching from go1.21.1 to go1.21.99 \[depth 9[0-9]\]$'
stderr -count=1 '^go: switching from go1.21.1 to go1.21.99 \[depth 100\]$'
stderr '^go: too many toolchain switches$'

[short] skip

# Internal env vars should not leak to go test or go run.
env TESTGO_VERSION_SWITCH=switch
go version
stdout go1.21.99
go test
stdout clean
go run .
stdout clean

-- go.mod --
module m
go 1.21.99

-- m_test.go --
package main

import "testing"

func TestEnv(t *testing.T) {
	// the check is in func init in m.go
}

-- m.go --
package main

import "os"

func init() {
	envs := []string{
		"GOTOOLCHAIN_INTERNAL_SWITCH_COUNT",
		"GOTOOLCHAIN_INTERNAL_SWITCH_VERSION",
	}
	for _, e := range envs {
		if v := os.Getenv(e); v != "" {
			panic("$"+e+"="+v)
		}
	}
	os.Stdout.WriteString("clean\n")
}

func main() {
}

