Richard Knop
Richard Knop

Reputation: 83705

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?

Upvotes: 16

Views: 30070

Answers (3)

rynop
rynop

Reputation: 53569

I like to use godotenv in command mode

godotenv -f ./.env go test ./internal/... -cover

Upvotes: 10

kostya
kostya

Reputation: 9559

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

Upvotes: 9

Volker
Volker

Reputation: 42412

That's not how setting variables for pipes works. See:

 FOO=BAR echo "AAA" | FOO=WAZ printenv | grep FOO

Upvotes: 2

Related Questions