diff options
author | Patrick Steinhardt <psteinhardt@gitlab.com> | 2022-07-06 09:52:46 +0300 |
---|---|---|
committer | Patrick Steinhardt <psteinhardt@gitlab.com> | 2022-07-07 07:50:27 +0300 |
commit | 08b2d318b9ce3904bf6c8432edfcedaf352f123e (patch) | |
tree | dea2b15aeac7d38638815e5a6535af55a672f292 | |
parent | 9deccce765e2437e87563378f878b8604fc73a9a (diff) |
testhelper: Add new `Unsetenv()` helper
With Go 1.17 a new `t.Setenv()` helper was introduced that automatically
restores the previous environment variable and that verifies that the
current test is not labelled as parallel. We're about to migrate all
callers to use it instead of `testhelper.ModifyEnvironment()`.
One part that `testhelper.ModifyEnvironment()` does though is to unset
an environment variable in case the given value is the empty string. And
unfortunately, Go didn't introduce a `t.Unsetenv()` helper at the same
time.
Implement a new function `testhelper.Unsetenv()` that behaves the same
as `t.Setenv()`, except that it unsets the environment variable.
-rw-r--r-- | internal/testhelper/testhelper.go | 15 |
1 files changed, 15 insertions, 0 deletions
diff --git a/internal/testhelper/testhelper.go b/internal/testhelper/testhelper.go index dacf805b3..c5af5b254 100644 --- a/internal/testhelper/testhelper.go +++ b/internal/testhelper/testhelper.go @@ -284,6 +284,21 @@ func ModifyEnvironment(t testing.TB, key string, value string) { } } +// Unsetenv unsets an environment variable. The variable will be restored after the test has +// finished. +func Unsetenv(t testing.TB, key string) { + t.Helper() + + // We're first using `t.Setenv()` here due to two reasons: first, it will automitcally + // handle restoring the environment variable for us after the test has finished. And second, + // it performs a check whether we're running with `t.Parallel()`. + t.Setenv(key, "") + + // And now we can unset the environment variable given that we know we're not running in a + // parallel test and where the cleanup function has been installed. + require.NoError(t, os.Unsetenv(key)) +} + // GenerateCerts creates a certificate that can be used to establish TLS protected TCP connection. // It returns paths to the file with the certificate and its private key. func GenerateCerts(t *testing.T) (string, string) { |