testhelper: Guard against modifying environment in parallel tests
Environment variables are shared per processes. As such, when we modify
a variable, then it will be visible for all other threads and Goroutines
as well. This can cause issues in case we modify the environment in
tests which use t.Parallel()
given that concurrently running tests may
override each others environment or read invalid values.
We already have a central helper which is used to modify the environment
in tests with testhelper.ModifyEnvironment()
. Ideally, we'd just check
whether parallel tests are currently enabled, but this information is
not something the testing package exposes to us. Instead, we can make
use of testing.T.Setenv()
, which does exactly these checks for us and
will panic in case the caller tries to modify the environment in a
parallel test. The only usecase it doesn't support is unsetting envvars,
and there is no exposed function that would do this for us. But we can
just first call testing.T.Setenv()
to modify the variable and check
whether we're allowed to, and in case we want to unset it we can call
os.Unsetenv()
afterwards.
Convert ModifyEnvironment()
to do so and thus guard against this
scenario. Given that testing.T.Setenv()
automatically reverts the
change for us after the test has finished we can also drop the returned
cleanup function.