设置Go测试的环境变量

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

Set environment variable for Go tests

问题

我正在尝试这样运行我的Go测试,设置一个环境变量:

FOO=BAR go list ./... | grep -v vendor | xargs -n1 go test -timeout=3s

在我的测试中,我执行了以下操作:

log.Print(os.Getenv("FOO"))

但是返回了一个空字符串。为什么FOO没有被设置?

英文:

I am trying to run my Go tests like this, setting an environment variable:

FOO=BAR go list ./... | grep -v vendor | xargs -n1 go test -timeout=3s

Inside my tests I do:

log.Print(os.Getenv("FOO"))

Which returns an empty string. Why is FOO not set?

答案1

得分: 9

以下是翻译好的内容:

FOO=BAR bash -c 'go list ./... | grep -v vendor | xargs -n1 go test -timeout=3s'

原始命令无法正常工作的一个很好的解释可以在这个问题的答案中找到:https://unix.stackexchange.com/questions/134735/environment-variables-are-not-set-when-my-function-is-called-in-a-pipeline

英文:
FOO=BAR bash -c 'go list ./... | grep -v vendor | xargs -n1 go test -timeout=3s'

A good explanation why the original command doesn't work can be found in the answer to the question: https://unix.stackexchange.com/questions/134735/environment-variables-are-not-set-when-my-function-is-called-in-a-pipeline

答案2

得分: 7

我喜欢在命令模式下使用godotenv

godotenv -f ./.env go test ./internal/... -cover
英文:

I like to use godotenv in command mode

godotenv -f ./.env go test ./internal/... -cover

答案3

得分: 2

这不是设置管道变量的正确方式。请参考以下示例:

 FOO=BAR echo "AAA" | FOO=WAZ printenv | grep FOO
英文:

That's not how setting variables for pipes works. See:

 FOO=BAR echo "AAA" | FOO=WAZ printenv | grep FOO

huangapple
  • 本文由 发表于 2015年11月2日 14:35:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/33471976.html
匿名

发表评论

匿名网友

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

确定