英文:
Is there a way in Golang to set flags when trying to execute `go test ./... -v`
问题
我需要执行类似于 go test ./... -v -args -name1 val1 的命令,但是似乎没有任何与 go test ... 一起使用的命令适用于 go test ./...。
英文:
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 ./...
答案1
得分: 3
Go测试框架使用全局的flag.(*FlagSet)实例。在测试文件中创建的任何标志都可以从命令行中使用。未被测试框架使用的位置参数可以通过flag.Args()(以及flag.Arg、flag.NArg)获得。在命令行上,位置参数需要使用--进行分隔。
例如:
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())
}
假设上述测试位于testflag、testflag/a和testflag/b几个目录中,运行go test -v ./... -value bar -- some thing会输出:
=== 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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论