New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bug: The go test command cannot parse custom args with flag.Parse() #39206
Comments
This is not a bug. From the documentation for package flag:
and your |
This is a common idiom you will see in many command line tools, not just Go.
|
well then you know what i am trying to do. so what is the solution? |
Flags in tests are really no different than in any other program, except that you don't get to call flag.Parse() yourself: package main
import (
"flag"
"log"
"os"
"testing"
)
var x = flag.Bool("env", false, "")
// run with `go test --env`
func TestFlags(t *testing.T) {
log.Println(os.Args) // /tmp/go-build197321626/b001/tmp.lW3vriEIbp.test -test.timeout=10m0s --env
log.Println(flag.Args()) // []
log.Println(*x) // true
} To treat arguments as flags create a dedicated FlagSet: // run with `go test -- --env`
func TestArgs(t *testing.T) {
fs := flag.NewFlagSet("my-test", flag.ContinueOnError)
y := fs.Bool("env", false, "")
log.Println(os.Args) // [/tmp/go-build483180072/b001/tmp.lW3vriEIbp.test -test.timeout=10m0s -- --env]
log.Println(flag.Args()) // [--env]
if err := fs.Parse(flag.Args()); err != nil {
t.Fatal(err)
}
log.Println(*y) // true
} |
The docs for the interaction between If anything is still confusing, please suggest doc improvements. Aside from that, I agree that the current behavior seems to be correct. |
Timed out in state WaitingForInfo. Closing. (I am just a bot, though. Please speak up if this is a mistake or you have the requested information.) |
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
yes 1.14
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
I ran:
What did you expect to see?
I expected flag.Parse() to capture the flag
What did you see instead?
the --env flag is not captured, even though it appears in the args list when I use:
I see:
I put the Q on SO first:
https://stackoverflow.com/questions/61944527/how-to-pass-custom-flags-to-go-test?noredirect=1#comment109560255_61944527
The text was updated successfully, but these errors were encountered: