While it is true that
go test will not run test binaries in the same Go package in parallel (unless the
--parallel flag is set), test binaries belonging to different packages (that is, contained in different directories) may still be run in parallel by default!
I had known about the
--parallel flag, which enables parallel execution for Go tests and had assumed that by default, all tests would be run sequentially otherwise. However, on a project I was working on, I began facing problems with tests that interacted with a local PostgreSQL server, with non-deterministic database conflicts being thrown unpredictably. This didn’t make sense as every test contained a teardown process that should have ensured that they were independent and side-effect free.
After several rounds of debugging (and pulling my hair out), I revisited the documentation for
go test and the
--parallel flag, stumbling upon this:
Note that -parallel only applies within a single test binary. The ‘go test’ command may run tests for different packages in parallel as well, according to the setting of the -p flag (see ‘go help build’).
It turns out that the
--parallel flag only applies to test binaries in the same package and not across packages. Therefore, tests belonging to different Go packages may still be executed in parallel! The maximum number of programs (including test binaries) that Go can run in parallel is instead governed by the build flag
-p (by default the number of CPUs) and not
Now it all made sense. Tests belonging to different Go packages in my project were being run in parallel, resulting in database conflicts when different tests accessed the test database simultaneously. Executing
go test -p 1
limited all tests to be run only one at a time, fixing this issue.