Search code examples
unit-testinggoconcurrencyinitializationgoroutine

Can the init() function start go routines safely, including along tests?


I have an app. which creates an HTTP service to listen to a few connections points we can use to check the app status.

That service runs in the background (with a go routine).

It gets initialized in the init() function among other things:

func init() {
    ...
    initHttpEndPoints();
    ...
}

Can the fact that a go routine is created in the init() function cause issues when testing this app.?

I'm asking because it looks like my tests re-run the init() a second time and I'm wondering why that is and what the side effects could be... (probably not so good if all the go routines are all of a sudden duplicated.)

Note: The complete app. creates several hundred go routines in the init() function. I use the HTTP end point as an example.

Strongly related answer: Are tests run concurrently?


Solution

  • In addition to icza's answer, it sounds like you're using init() incorrectly with the testing package.

    Rather than using init() to initialize things needed for tests, you should define the function TestMain().