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

Patricia Arquette
Release: 2024-11-02 21:51:30
Original
862 people have browsed it

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

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

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

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!

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!