I am trying to run my Go tests like this, setting an environment variable:
FOO=BAR go list ./... | grep -v vendor | xargs -n1 go test -timeout=3s
Inside my tests I do:
log.Print(os.Getenv("FOO"))
Which returns an empty string. Why is FOO not set?
The Go environment If an environment variable is unset, the go command uses a sensible default setting. Defaults changed in this way are recorded in a Go environment configuration file stored in the per-user configuration directory, as reported by os. UserConfigDir .
At the command line in the greetings directory, run the go test command to execute the test. The go test command executes test functions (whose names begin with Test ) in test files (whose names end with _test.go).
The convention for naming test files in Go is to end the file name with the _test.go suffix and place the file in the same directory as the code it tests.
FOO=BAR bash -c 'go list ./... | grep -v vendor | xargs -n1 go test -timeout=3s'
A good explanation why the original command doesn't work can be found in the answer to the question: https://unix.stackexchange.com/questions/134735/environment-variables-are-not-set-when-my-function-is-called-in-a-pipeline
I like to use godotenv in command mode
godotenv -f ./.env go test ./internal/... -cover
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With