Set environment variable for Go tests

18,121

Solution 1

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

Solution 2

I like to use godotenv in command mode

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

Solution 3

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

 FOO=BAR echo "AAA" | FOO=WAZ printenv | grep FOO
Share:
18,121
Richard Knop
Author by

Richard Knop

I'm a software engineer mostly working on backend from 2011. I have used various languages but has been mostly been writing Go code since 2014. In addition, I have been involved in lot of infra work and have experience with various public cloud platforms, Kubernetes, Terraform etc. For databases I have used lot of Postgres and MySQL but also Redis and other key value or document databases. Check some of my open source projects: https://github.com/RichardKnop/machinery https://github.com/RichardKnop/go-oauth2-server https://github.com/RichardKnop

Updated on July 18, 2022

Comments

  • Richard Knop
    Richard Knop almost 2 years

    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?

  • Markus W Mahlberg
    Markus W Mahlberg over 8 years
    Mind to explain this a bit? ;)
  • kostya
    kostya over 8 years