使用 Golang Test Explorer 或自动测试运行程序时设置秘密凭据
Setting secret credentials when using Golang Test Explorer or automated test runner
我正在为一些需要 API 凭据来上传和列出 DigitalOcean Spaces 存储桶中的文件的功能进行单元测试。已经使用 CLI 标志设置了这些值。我正在使用 Go Test Explorer 来 运行 测试,我注意到这两个测试由于凭据为空而失败。有谁知道是否有一种方法可以在测试中设置 envars 而不必在执行“go test -运行”之前在命令行中显式设置它们?
go 1.17
刚刚添加了通过 T.Setenv.
在测试期间更改环境变量的功能
来自docs:
T.Setenv calls os.Setenv(key, value) and uses Cleanup to restore the
environment variable to its original value after the test.
This cannot be used in parallel tests.
用法示例:
func getCreds() (u, p string) {
u, p = os.Getenv("USER"), os.Getenv("PASS")
return
}
func TestEnv(t *testing.T) {
t.Setenv("USER", "xxx")
t.Setenv("PASS", "yyy")
u, p := getCreds()
t.Logf("creds: %q / %q", u, p) // will get local testing env settings
}
func TestNoEnv(t *testing.T) {
u, p := getCreds()
t.Logf("creds: %q / %q", u, p) // will get nothing
}
https://play.golang.org/p/QBl3hV6WjWA
EDIT:从评论看来,您的(或 DigialOcean 的)测试函数使用 FlagSet
,这是命令行选项(如果您在问题中分享了一些测试代码,可能会有所帮助)。无论如何,如果是这种情况,调用 go test
并传递参数的正确方法如下:
go test -args -spaces-key="KEY" -spaces-secret="S3CR3T"
如果您想传递 ENV VAR,那么您之前的做法是正确的:
SCOREKEEPER_SPACES_KEY="key" SCOREKEEPER_SPACES_SECRET="s3cr3t" go test
我正在为一些需要 API 凭据来上传和列出 DigitalOcean Spaces 存储桶中的文件的功能进行单元测试。已经使用 CLI 标志设置了这些值。我正在使用 Go Test Explorer 来 运行 测试,我注意到这两个测试由于凭据为空而失败。有谁知道是否有一种方法可以在测试中设置 envars 而不必在执行“go test -运行”之前在命令行中显式设置它们?
go 1.17
刚刚添加了通过 T.Setenv.
来自docs:
T.Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test.
This cannot be used in parallel tests.
用法示例:
func getCreds() (u, p string) {
u, p = os.Getenv("USER"), os.Getenv("PASS")
return
}
func TestEnv(t *testing.T) {
t.Setenv("USER", "xxx")
t.Setenv("PASS", "yyy")
u, p := getCreds()
t.Logf("creds: %q / %q", u, p) // will get local testing env settings
}
func TestNoEnv(t *testing.T) {
u, p := getCreds()
t.Logf("creds: %q / %q", u, p) // will get nothing
}
https://play.golang.org/p/QBl3hV6WjWA
EDIT:从评论看来,您的(或 DigialOcean 的)测试函数使用 FlagSet
,这是命令行选项(如果您在问题中分享了一些测试代码,可能会有所帮助)。无论如何,如果是这种情况,调用 go test
并传递参数的正确方法如下:
go test -args -spaces-key="KEY" -spaces-secret="S3CR3T"
如果您想传递 ENV VAR,那么您之前的做法是正确的:
SCOREKEEPER_SPACES_KEY="key" SCOREKEEPER_SPACES_SECRET="s3cr3t" go test