Home > Article > Backend Development > How to Execute Go Tests Sequentially across Multiple Packages?
How to Execute Tests across Multiple Go Packages Sequentially
When executing tests for multiple packages using go test ./..., it's important to consider the parallelization aspect. By default, tests are run concurrently across packages. However, certain scenarios, such as database-based tests, require sequential execution.
In the provided example, database contention arises due to parallel test execution. Each test file defines global database variables, which can cause conflicts when tests run simultaneously.
Solution:
To enforce sequential execution across packages, use the undocumented -p flag along with go test as follows:
go test -p 1 ./...
The -p 1 flag builds and tests all packages in serial, resolving the contention issue.
Alternative Solution (Using Shell Script):
If using the -p 1 flag is not feasible, an alternative shell script-based approach can be employed. Here's a Bash script example:
find . -name '*.go' -printf '%h\n' | sort -u | xargs -n1 -P1 go test
This script lists all subdirectories containing .go files, removes duplicates, and runs go test on each subdirectory sequentially.
The above is the detailed content of How to Execute Go Tests Sequentially across Multiple Packages?. For more information, please follow other related articles on the PHP Chinese website!