Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to pass variables to test cases in golang

Tags:

go

When writing test cases for golang, what is the standard way to pass in 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? Environment variable? Something else?

like image 209
Jay Avatar asked Oct 31 '17 22:10

Jay


People also ask

How do you pass variables in Golang?

Golang supports two different ways to pass arguments to the function i.e. Pass by Value or Call by Value and Pass By Reference or Call By Reference. By default, Golang uses the call by value way to pass the arguments to the function.

Does Golang run tests in parallel?

The go test command may run tests for different packages in parallel as well, according to the setting of the -p flag. If this is not explicitly specified, the number will be the value of the GOMAXPROCS environment variable.

How do you test concurrency in go?

If you want to test concurrency you'll need to make a few go routines and have them run, well, concurrently. You might try taking the locking out and intentionally get it to crash or misbehave by concurrently modifying things and then add the locking in to ensure it solves it.


1 Answers

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)

like image 180
Jay Avatar answered Oct 13 '22 09:10

Jay