Tuesday, February 7, 2017

Go - TestMain

Every day learning new things about Go, trapped into an interesting one. Apparently, not only you could test your main method, you should follow some well-defined practices.

First of all, it shouldn't be
func TestMain(t *testing.T) {
...
}

as usually, but
func TestMain(m *testing.M) {
...
}
So, the typical structure for the main_test.go would be:

func TestMain(m *testing.M) {
  setup()
  main()
  // or
  // go func() {
  //  main()
  // }()
  code := m.Run()
  tearDown()
  os.Exit(code)
}

func TestA(t *testing.T) {
...
}

func TestZ(t *testing.T) {
...
}

func TestB(t *testing.T) {
...


Interesting fact - tests would run in the order they are declared in the file, not alphabetically, which is usually what you want. 

When to use pointers in Go

When in doubt - use pointer! A comprehensive reference on the topic.

Wednesday, February 1, 2017

Running Mongo 3.x on Travis CI

Unfortunately Mongo 3.x support is not supported by Travis CI OOTB. There are some workarounds to achieve this, the idea is to install mongo as a package. However all of them have some disadvantages.

My solution to that would be to use docker as a service and run mongo in container.

.travis.yml

language: go
services:
- docker
script:
- "./run.sh"

run.sh

language: go
services:
- docker
script:
- "./run.sh"

if [[ -z $(docker images | grep mongo | grep 3.4.1) ]]; then
  echo "Pulling mongo image."
  docker pull mongo:3.4.1
fi

if [[ -z $(docker ps | grep mongo | grep 3.4.1) ]]; then
  echo "Starting mongo container."
  MONGO_ID=$(docker run -p 27017:27017 -d mongo:3.4.1)
fi

### RUN YOUR CODE HERE (e.g. tests)

if [[ -n $MONGO_ID ]]; then
  echo "Killing mongo container."
  KILLED=$(docker kill $MONGO_ID)
fi