英文:
Setting secret credentials when using Golang Test Explorer or automated test runner
问题
我正在为一些需要API凭据来上传和列出DigitalOcean Spaces存储桶中文件的函数编写单元测试。这些值已经使用CLI标志设置好了。我正在使用Go Test Explorer来运行这些测试,我注意到这两个测试失败了,因为凭据为空。有人知道是否有一种方法可以在测试中设置环境变量,而不必在执行"go test -run"之前在命令行中显式设置它们吗?
英文:
I am working on some unit tests for some functions that require API credentials to upload and list files in a DigitalOcean Spaces bucket. Thee values have already been set using CLI flags. I am using Go Test Explorer to run the tests, and I noticed that those two tests fail due to the credentials being empty. Does anyone know if there is a way to set envars in a test without having to explicitly set them in the commmand line before executing "go test -run"?
答案1
得分: 3
go 1.17
刚刚通过T.Setenv方法添加了在测试期间更改环境变量的功能。
根据文档:
> T.Setenv调用os.Setenv(key, value),并使用Cleanup在测试后将环境变量恢复为其原始值。
>
> 这不能在并行测试中使用。
示例用法:
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) // 将获取本地测试环境设置
}
func TestNoEnv(t *testing.T) {
u, p := getCreds()
t.Logf("creds: %q / %q", u, p) // 将获取空值
}
https://play.golang.org/p/QBl3hV6WjWA
编辑:根据评论,似乎您(或者是DigitalOcean)的测试函数使用了FlagSet
,它是命令行选项(如果您在问题中分享一些测试代码可能会有所帮助)。无论如何,如果是这种情况,正确调用go test
并传递参数的方式如下:
go test -args -spaces-key="KEY" -spaces-secret="S3CR3T"
如果您想传递环境变量,则之前的方式是正确的:
SCOREKEEPER_SPACES_KEY="key" SCOREKEEPER_SPACES_SECRET="s3cr3t" go test
英文:
go 1.17
just added the ability to change environment variables for the duration of a test via T.Setenv.
From the 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.
Example Usage:
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: from the comments it appears that your (or DigialOcean's) test functions use FlagSet
which is command line options (might be helpful if you shared some of the test code in the question). Anyway if this is the case, the correct way to invoke a go test
and pass arguments is like so:
go test -args -spaces-key="KEY" -spaces-secret="S3CR3T"
If you want to pass ENV VARs then the way you were doing before was correct:
SCOREKEEPER_SPACES_KEY="key" SCOREKEEPER_SPACES_SECRET="s3cr3t" go test
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论