在Golang中,执行`go test ./… -v`时,有一种设置标志的方法吗?

huangapple go评论122阅读模式
英文:

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.Argflag.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())
}

假设上述测试位于testflagtestflag/atestflag/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

huangapple
  • 本文由 发表于 2022年4月15日 07:26:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/71878585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定