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?
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
testconstraint, so you can check for that.