Skip to content
Myr

Make detection for test-binary more universal (#2173)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

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 e5762054c9a6429fa7c234897707d and 1ef0913976db2004980575ed815c3 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

authored by Sebastiaan van Stijn · committed by GitHub · parent 9f90567 · Browse files · 4 files+76 added−3 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

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

Diff stats

4 files+76 added−3 removed

  • other:+76 added−3 removed

4 files+76 added−3 removed

added:command_go120.go+33 added
1// Copyright 2013-2024 The Cobra Authors2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415//go:build !go1.2116// +build !go1.211718package cobra1920import (21 "os"22 "strings"23)2425// based on golang.org/x/mod/internal/lazyregexp: https://cs.opensource.google/go/x/mod/+/refs/tags/v0.19.0:internal/lazyregexp/lazyre.go;l=6626// For a non-go-test program which still has a name ending with ".test[.exe]", it will need to either:27// 1- Use go >= 1.21, or28// 2- call "rootCmd.SetArgs(os.Args[1:])" before calling "rootCmd.Execute()"29var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test")3031func isTesting() bool {32 return inTest33}
added:command_go121.go+25 added
1// Copyright 2013-2024 The Cobra Authors2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415//go:build go1.2116// +build go1.211718package cobra1920import "testing"2122func isTesting() bool {23 // Only available starting with go 1.2124 return testing.Testing()25}
modified:command_test.go+13 added
2837 unmodified lines
2838 checkStringContains(t, output, "unknown flag: --unknown")2839 })2840 }2841}28422843// This tests verifies that when running unit tests, os.Args are not used.2844// This is because we don't want to process any arguments that are provided2845// by "go test"; instead, unit tests must set the arguments they need using2846// rootCmd.SetArgs().2847func TestNoOSArgsWhenTesting(t *testing.T) {2848 root := &Command{Use: "root", Run: emptyRun}2849 os.Args = append(os.Args, "--unknown")28502851 if _, err := root.ExecuteC(); err != nil {2852 t.Errorf("error: %v", err)2853 }2854}
modified:command.go+5 added-3 removed
21 unmodified lines
22 "errors"23 "fmt"24 "io"25 "os"26 "path/filepath"26 "sort"27 "strings"2829 flag "github.com/spf13/pflag"
1046 unmodified lines
1076 c.checkCommandGroups()10771078 args := c.args10791081 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #1551082 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {1080 // If running unit tests, we don't want to take the os.Args, see #155 and #2173.1081 // For example, the following would fail:1082 // go test -c -o foo.test1083 // ./foo.test -test.run TestNoArgs1084 if c.args == nil && !isTesting() {1085 args = os.Args[1:]1086 }10871088 // initialize the hidden command to be used for shell completion
813 unmodified lines