samedi 6 janvier 2018

Passing database credentials to tests in go?

I have tried couple of approaches (shown below) but I don't like any of them. So I decided to ask the community if there is a better way to do it.

Approach 1

Pass database credentials as arguments:

go test -args -db_user=test -db_pass=secret

Then use it in tests as:

package my_test
var dbUser = flag.String("db_user", "", "test database user")
var dbPass = flag.String("db_pass", "", "test database password")

func TestSomething(t *testing.T) {
    db := open(*dbUser, *dbPass)
}

Approach 2

Set environment variables before running tests:

$ export TEST_DB_USER=user
$ export TEST_DB_PASS=secret
$ go test

or

$ TEST_DB_USER=user TEST_DB_PASS=secret go test -v

Then use it in tests as:

package my_test
var dbUser = flag.String("db_user", "", "test database user")
var dbPass = flag.String("db_pass", "", "test database password")

func TestSomething(t *testing.T) {
    db := open(os.Getenv("TEST_DB_USER"), os.Getenv("TEST_DB_PASS"))
}

Approach 3

Use .env.test file and http://ift.tt/1N2srru package to load database connection credentials before running tests.

Aucun commentaire:

Enregistrer un commentaire