Home  >  Article  >  Backend Development  >  How to run "go test" in the parent directory of multiple go modules and return non-zero on error

How to run "go test" in the parent directory of multiple go modules and return non-zero on error

王林
王林forward
2024-02-05 23:48:03701browse

如何在多个go模块的父目录中运行“go test”并在出现错误时返回非零

Question content

Look at this directory structure:

/root
    /hoge
        go.mod
        go.sum
        main.go
        /test
           main_test.go
           /unit
              sub_test.go
    /fuga
        go.mod
        go.sum
        main.go
        /test
           main_test.go

You can run the test using the following code, but it will always return exit code 0 if it fails.

find . -name go.mod -execdir go test ./... \;

Is there a way to return a non-zero value if it fails?


Correct Answer


Use this command:

find . -name go.mod -execdir go test ./... -- {} +

findCommand Manual About -execdir command{}

If any call using the " " form returns a non-zero value as the exit status, find returns a non-zero exit status. If find encounters an error, it sometimes causes an immediate exit, so some pending commands may not run at all.

But go test does not require matching files in the find command. In fact, it will fail like this:

$ go test ./... go.mod
no required module provides package go.mod; to add it:
    go get go.mod

Fails because go.mod is interpreted as a package.

The solution is to add the terminator -- before {} . See Command Line Flag Syntax:

Flag parsing stops before the first non-flag parameter ("-" is a non-flag parameter) or after the terminator "--".

The above is the detailed content of How to run "go test" in the parent directory of multiple go modules and return non-zero on error. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete