Skip to content

Commit

Permalink
test: os.Unsetenv affects global state (#5)
Browse files Browse the repository at this point in the history
* test: os.Unsetenv affects global state

This change adds a helper function that guarantees the cleanup of
environment variables.

For each applicable test function, we run this at the start, and at the
end through a `defer` keyword. Previously, we were unsetting the
environment variable within the test, though there is a risk that since
global state is being manipulated, we may run into a flakey test where
an environment variable is inadvertently lingering.

* test: use unsetEnv helper to manage global state

---------

Co-authored-by: James Telfer <[email protected]>
  • Loading branch information
therealvio and jamestelfer authored Dec 11, 2024
1 parent 95f23d2 commit 3ccb905
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/plugin/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ func TestFailOnMissingEnvironment(t *testing.T) {
var config plugin.Config
fetcher := plugin.EnvironmentConfigFetcher{}

t.Setenv("BUILDKITE_PLUGIN_EXAMPLE_GO_MESSAGE", "")
os.Unsetenv("BUILDKITE_PLUGIN_EXAMPLE_GO_MESSAGE")
unsetEnv(t, "BUILDKITE_PLUGIN_EXAMPLE_GO_MESSAGE")

err := fetcher.Fetch(&config)

Expand All @@ -33,3 +32,20 @@ func TestFetchConfigFromEnvironment(t *testing.T) {
require.NoError(t, err, "fetch should not error")
assert.Equal(t, "test-message", config.Message, "fetched message should match environment")
}

func unsetEnv(t *testing.T, key string) {
t.Helper()

// ensure state is restored correctly
currValue, exists := os.LookupEnv(key)
t.Cleanup(func() {
if exists {
os.Setenv(key, currValue)
} else {
os.Unsetenv(key)
}
})

// clear the value
os.Unsetenv(key)
}

0 comments on commit 3ccb905

Please sign in to comment.