Home > Backend Development > Golang > How to Execute Go Tests Sequentially across Multiple Packages?

How to Execute Go Tests Sequentially across Multiple Packages?

Mary-Kate Olsen
Release: 2024-11-04 07:59:30
Original
249 people have browsed it

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:

1

go test -p 1 ./...

Copy after login

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:

1

find . -name '*.go' -printf '%h\n' | sort -u | xargs -n1 -P1 go test

Copy after login

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!

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