How to Run Go Tests Sequentially for Multiple Packages to Avoid Contention?

Patricia Arquette
Release: 2024-11-04 06:15:29
Original
206 people have browsed it

How to Run Go Tests Sequentially for Multiple Packages to Avoid Contention?

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
Copy after login

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; }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!