Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set environment variable for Go tests

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?

like image 448
Richard Knop Avatar asked Nov 02 '15 06:11

Richard Knop


People also ask

Where are go environment variables stored?

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 .

Which command is used to run the tests in go?

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).

Where do I put test files in 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.


2 Answers

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

like image 151
kostya Avatar answered Sep 21 '22 06:09

kostya


I like to use godotenv in command mode

godotenv -f ./.env go test ./internal/... -cover
like image 31
rynop Avatar answered Sep 21 '22 06:09

rynop