Y
Y
Yermek2020-06-22 06:58:14
go
Yermek, 2020-06-22 06:58:14

Why doesn't Go see the variable set in TestMain?

I am studying Go here at this course and I have a problem:

There is a TestMain function

func TestMain(m *testing.M) {

  databaseURL := os.Getenv("DATABASE_URL")
  if databaseURL == "" {
    databaseURL = "host=localhost dbname=restapi_test user=uzr password=secret"
  }

  fmt.Println("1: DB URL: ===>", databaseURL)

  os.Exit(m.Run())

}


and test function

func TestUserRepository_Create(t *testing.T) {
  //databaseURL = "host=localhost dbname=restapi_test user=uzr password=secret"
  fmt.Println("2: DB URL: ===>", databaseURL)
  s, teardown := store.TestStore(t, databaseURL)
  defer teardown("users")

  u, err := s.User().Create(&model.User{Email: "[email protected]"})
  assert.NoError(t, err)
  assert.NotNil(t, u)
}


Running the test produces the following output (when defining the databaseURL value in the test itself, everything is OK)

1: DB URL: ===> host=localhost dbname=restapi_test user=uzr password=secret
2: DB URL: ===> 
2020/06/22 09:49:35 ===> 
--- FAIL: TestUserRepository_Create (0.02s)
    userrepository_test.go:15: pq: password authentication failed for user "yermek"
FAIL
FAIL	github.com/yermek/http-rest-api/internal/app/store	0.039s
FAIL


Actually, the question is in the subject - why is the databaseURL value not passed to the test?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-06-22
@ermek6

databaseURL := os.Getenv("DATABASE_URL")
Because you are declaring a local variable in TestMain without touching the global one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question