Jay
Jay

Reputation: 20136

How to pass environment variables to test cases in Go

When writing test cases for Go, what is the standard way to pass in environment variables that need to be provided to the tests.

For example, we don't want to embed passwords in the source code of the test cases.

What is the most standard way to handle this? Do we have the test cases look for a config file? Something else?

Upvotes: 14

Views: 12616

Answers (2)

Jay
Jay

Reputation: 20136

It appears I have stumbled across the answer. Adding this to test cases allows you to pass parameters, i.e.

var password string

func init() {
        flag.StringVar(&password, "password", "", "Database Password")
}

Then you can do this:

go test github.com/user/project -password=123345

(As noted below, Don't do this on a test where you don't trust other users on the test server who have access to view running processes, (i.e. perhaps your test database has sensitive data in it. However. If you are in a organisation that likes to keep sensitive data in a test environment this is probably the least of your security problems)

Upvotes: 16

mozey
mozey

Reputation: 2292

Use an env var

func func TestFoo(t *testing.T) {
  x := os.Getenv("MY_X")
  fmt.Println(x)
}

Then call your test like this

MY_X=bar go test -v ./... -run TestFoo

and it should print bar

Upvotes: 11

Related Questions