Home > Software design >  Is there a way in Golang to set flags when trying to execute `go test ./... -v`
Is there a way in Golang to set flags when trying to execute `go test ./... -v`

Time:04-16

I need to execute something like go test ./... -v -args -name1 val1 But nothing that works with go test ... seems to work with go test ./...

CodePudding user response:

The Go test framework uses the global flag.(*FlagSet) instance. Any flags created in test files are available from the commands line. Positional arguments that aren't consumed by the test framework are available via flag.Args() (and flag.Arg, flag.NArg). Positional args will need -- to separate them on the command line.

For example:

package testflag

import (
    "flag"
    "testing"
)

var value = flag.String("value", "", "Test value to log")

func TestFlagLog(t *testing.T) {
    t.Logf("Value = %q", *value)
    t.Logf("Args = %q", flag.Args())
}

Assuming the above test is in several directories testflag, testflag/a, and testflag/b, running go test -v ./... -value bar -- some thing outputs:

=== RUN   TestFlagLog
    testflag_test.go:11: Value = "bar"
    testflag_test.go:12: Args = ["some" "thing"]
--- PASS: TestFlagLog (0.00s)
PASS
ok          testflag        0.002s
=== RUN   TestFlagLog
    testflag_test.go:11: Value = "bar"
    testflag_test.go:12: Args = ["some" "thing"]
--- PASS: TestFlagLog (0.00s)
PASS
ok          testflag/a      0.001s
=== RUN   TestFlagLog
    testflag_test.go:11: Value = "bar"
    testflag_test.go:12: Args = ["some" "thing"]
--- PASS: TestFlagLog (0.00s)
PASS
ok          testflag/b      0.002s
  • Related