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

huangapple go评论77阅读模式
英文:

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

问题

请看这个目录结构:

/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

你可以使用以下代码运行测试,但如果测试失败,它将始终返回退出码0。

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

有没有办法在测试失败时返回非零值?

英文:

Take a 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 with the following code, but if it fails, it will always return an exit code of 0.

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

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

答案1

得分: 0

使用以下命令:

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

关于find命令中-execdir command {} +的手册:

> 如果任何使用+形式的调用返回非零值作为退出状态,则find将返回非零的退出状态。如果find遇到错误,有时会导致立即退出,因此某些待处理的命令可能根本不会运行。

但是go test不需要来自find命令的匹配文件。实际上,它会失败,如下所示:

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

它失败是因为go.mod被解释为一个包。

解决方法是在{} +之前添加终止符--。请参阅命令行标志语法

> 在第一个非标志参数之前(“-”是一个非标志参数)或终止符“--”之后,标志解析就会停止。

英文:

Use this command:

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

Manual for the find command about -execdir command {} +:

> If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all.

But go test don't need the matched file from 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

It failed because go.mod is interpreted as a package.

The workaround is to add the terminator -- before {} +. See Command line flag syntax:

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

huangapple
  • 本文由 发表于 2023年6月8日 17:43:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430551.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定