在init()函数中验证环境。

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

Validate environment in init()

问题

我有一个包,它在init()函数中验证进程是否设置了特定的环境变量,否则会引发恐慌。

我这样做是为了确保进程在启动时配置正确。

问题是这种方法实际上无法进行测试(使用_test.go文件),因为测试套件中不存在环境。

解决这个问题的最佳方法是什么?

英文:

I have a package that validates if the process has specific environment variables set on init(), else it panics.

I do this to ensure the process is properly configured at launch.

The problem is that this approach is not really testable (using _test.go files), since the environment doesn't exist in the test suite.

What's the best way to solve this problem?

答案1

得分: 2

你想要能够测试验证,还是完全跳过测试文件中的验证?无论哪种方式,都将使用相同的基本方法,即将验证代码分离到自己的文件中,在测试期间不进行构建。如果你只想在测试期间完全跳过验证,将整个init()函数放入该文件中。如果你想测试验证,只需调用你自己的shim来获取环境值,并将你的shim放入非测试文件中,然后在仅在测试期间编译的文件中放入一个单独的shim。

你可以使用文件头部的构建约束来控制文件在测试期间是否构建。我记得运行测试会应用test约束,所以你可以检查这一点。

英文:

Do you want to be able to test the validation, or just skip it entirely in the test file? Either way is going to use the same basic approach, which is to separate out the validation code into its own file that doesn't build during tests. If you just want to skip validation entirely during the test, put the whole init() function into that file. If you want to test validation, just make the validation code call your own shim to get environment values, and put your shim in that non-test file, and put a separate shim into a file that only compiles during tests.

You can control whether the file builds during tests using a build constraint in the file header. IIRC, running the tests applies the test constraint, so you can check for that.

huangapple
  • 本文由 发表于 2012年12月11日 10:07:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/13812517.html
匿名

发表评论

匿名网友

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

确定