Home  >  Article  >  Backend Development  >  How to Run `go test` in a Parent Directory with Multiple Go Modules?

How to Run `go test` in a Parent Directory with Multiple Go Modules?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 21:51:30862browse

How to Run `go test` in a Parent Directory with Multiple Go Modules?

Running go test in Parent Directory of Multiple Go Modules

When working with a directory structure containing multiple go modules, such as:

<code class="pre">/root
    /one
        go.mod
        go.sum
        main.go
        main_test.go
    /two
        go.mod
        go.sum
        main.go
        main_test.go</code>

Executing go test . or go test ./... from the root directory(/root) may result in an error indicating that no packages were found. This is because go test expects to operate on a single module.

To overcome this limitation, one approach is to use a shell trick. For instance, the following command should iterate through the subdirectories and execute go test ./... in each one:

<code class="pre">find . -type d -name main_test.go -exec go test '{}/' \;</code>

Alternatively, many projects implement a Makefile or a testing script that performs this operation. For example, a test.sh script could include:

<code class="pre">for i in $(find . -type d -name main_test.go | sed 's|main_test.go||'); do
    cd $i
    go test ./...
    cd ..
done</code>

This script would loop through the repository, change to each subdirectory containing a main_test.go file, execute go test ./..., then return to the parent directory.

Larger projects may maintain a list of all their modules, such as the one maintained by the go-cloud project (https://github.com/google/go-cloud/blob/master/allmodules). This list can be used by scripts to iterate through the modules and perform various operations, including running tests.

The above is the detailed content of How to Run `go test` in a Parent Directory with Multiple Go Modules?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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