Commit graph

1 commit

Author SHA1 Message Date
Sebastiaan van Stijn
d1e9d85fcf
Make detection for test-binary more universal (#2173)
When running tests in verbose mode (or other options), tests involving
Cobra may fail if the test does not explicitly set Command.args to an
empty slice; in this case, Cobra defaults to using `os.Args`, which
will contain arguments passed to the test (such as `-v` (verbose)).

Commits e5762054c9 and 1ef0913976
implemented a workaround for this when running (unit) tests for Cobra
itself, but this check is specifig to Cobra (checking for `cobra.test`),
and don't work on Windows (which will have a `.exe` extension),

This patch implements a more universal check, so that users of Cobra
as a module also benefit from this workaround.

go1.21 and up provides a `testing.Testing()` utility ([1]); as the Cobra
module still supports Go1.16 and up, an alternative implementation was
added for older versions, based on golang.org/x/mod/lazyregexp [2].

Before this patch:

    go test -c -o foo.test

    ./foo.test -test.run TestNoArgs
    --- FAIL: TestNoArgs (0.00s)
        args_test.go:37: Unexpected output: Error: unknown command "TestNoArgs" for "c"
            Usage:
              c [flags]

            Flags:
              -h, --help   help for c

        args_test.go:40: Unexpected error: unknown command "TestNoArgs" for "c"
    FAIL

After this patch:

    go test -c -o foo.test

    ./foo.test -test.run TestNoArgs
    PASS

[1]: https://pkg.go.dev/testing#Testing
[2]: https://cs.opensource.google/go/x/mod/+/refs/tags/v0.19.0:internal/lazyregexp/lazyre.go;l=66-78

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
2024-12-28 17:07:03 -05:00