Search code examples
gogo-testing

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


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?


Solution

  • 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 "--".