Go: Concurrently Running Tests for Multiple Packages: Resolving Contentions
When testing multiple packages under a subdirectory, running individual tests with go test succeeds. However, attempts to run all tests simultaneously using go test ./... result in failures. The issue stems from potential contentions when accessing common resources, like shared databases.
Global variables used in individual test files may create contention if multiple tests operate on the same database simultaneously. To prevent this, consider using the -parallel 1 flag. This enforces sequential execution of tests within each package.
Despite using -parallel 1, tests may still fail due to contention. This suggests that tests from different packages are running concurrently. To eliminate any possibility of parallelism between packages, a workaround is to manually run the tests using a bash script or an alias. The following command sequence achieves this:
find . -name '*.go' -printf '%h\n' | sort -u | xargs -n1 -P1 go test
This command listing unique subdirectories containing *.go files and executes go test on each subdirectory sequentially.
As an alternative, the following shell script or alias can be used:
function gotest(){ find -name '*.go' -printf '%h\n' | sort -u | xargs -n1 -P1 go test; }
By running gotest ., all tests in the current directory can be executed sequentially.
While not as straightforward as go test ./..., this workaround ensures that tests are executed sequentially across packages, resolving any contention issues arising from parallel test execution.
The above is the detailed content of How to Run Go Tests Sequentially for Multiple Packages to Avoid Contention?. For more information, please follow other related articles on the PHP Chinese website!