TIL: How to recognize if we're running in gitlab ci in golang

Some time ago i found a guy who collected his “TIL”’s (Today i learned) on his personal blog. It did not matter how small or unimpressive his learnings seemed to others, he just started to collect and publish them. I always wanted to do the same, so here we are.

Today i wrote some tests for a small cli tool written in golang which imports and exports data from a graph database. Needless to say you need to have an instance of the graph database ready if you want to check if your code still works after version upgrades or code changes.

When running those tests on my local machine, i wanted to use a different hostname as a target address for the database instance (localhost) as opoosed to when running the tests in my Gitlab CI Pipeline (we call this db for demonstration purposes). Turns out, go offers a TestMain function which comes in kinda handy in our scenario. In this function i simply check for an environment variable called GITLAB_CI.

Gitlab Docs tells us:

Available for all jobs executed in CI/CD. true when available.

there we go:

func TestMain(m *testing.M) {
	// Gitlab Ci Running detection
	if len(os.Getenv("GITLAB_CI")) > 0 {
		TestHost = "db"
  }
  m.Run()
}

If the GITLAB_CI variable exists, we simply switch the value to db for our TestHost Variable.