Skip to content

Commit

Permalink
test: use unsetEnv helper to manage global state
Browse files Browse the repository at this point in the history
  • Loading branch information
jamestelfer committed Dec 10, 2024
1 parent 3fee711 commit 73a01f6
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions src/plugin/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,18 @@ import (
)

func TestFailOnMissingEnvironment(t *testing.T) {
unsetEnvironmentVariables()

var config plugin.Config
fetcher := plugin.EnvironmentConfigFetcher{}

unsetEnv(t, "BUILDKITE_PLUGIN_EXAMPLE_GO_MESSAGE")

err := fetcher.Fetch(&config)

expectedErr := "required key BUILDKITE_PLUGIN_EXAMPLE_GO_MESSAGE missing value"
assert.EqualError(t, err, expectedErr, "fetch should error on missing environment variable")
}

func TestFetchConfigFromEnvironment(t *testing.T) {
unsetEnvironmentVariables()
defer unsetEnvironmentVariables()

var config plugin.Config
fetcher := plugin.EnvironmentConfigFetcher{}

Expand All @@ -36,8 +33,19 @@ func TestFetchConfigFromEnvironment(t *testing.T) {
assert.Equal(t, "test-message", config.Message, "fetched message should match environment")
}

// Unsets environment variables through an all-in-one function. Extend this with additional environment variables as
// needed.
func unsetEnvironmentVariables() {
os.Unsetenv("BUILDKITE_PLUGIN_EXAMPLE_GO_MESSAGE")
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 73a01f6

Please sign in to comment.