From 217f05223d0bb129128febe5a82064dda1378fd8 Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Wed, 18 Sep 2024 11:38:17 -0400 Subject: [PATCH] Add common package --- common/common.go | 13 +++++++++++++ common/common_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 common/common.go create mode 100644 common/common_test.go diff --git a/common/common.go b/common/common.go new file mode 100644 index 0000000..22a633c --- /dev/null +++ b/common/common.go @@ -0,0 +1,13 @@ +package common + +import "os" + +// GetenvDefault retrieves an environment variable if set, or a provided default +func GetenvDefault(key string, d string) string { + val, ok := os.LookupEnv(key) + if ok { + return val + } else { + return d + } +} diff --git a/common/common_test.go b/common/common_test.go new file mode 100644 index 0000000..9376b1e --- /dev/null +++ b/common/common_test.go @@ -0,0 +1,39 @@ +package common + +import ( + "os" + "testing" +) + +var testEnvKey string = "TEST_MQTT_KEY" + +func assertError(t testing.TB, got, want string) { + t.Helper() + if got != want { + t.Errorf("Error: got '%s', want '%s'", got, want) + } +} + +func TestGetenvDefault(t *testing.T) { + t.Run("key not set", func(t *testing.T) { + originalEnv := os.Getenv(testEnvKey) + os.Unsetenv(testEnvKey) + defer os.Setenv(testEnvKey, originalEnv) + + got := GetenvDefault(testEnvKey, "found") + want := "found" + + assertError(t, got, want) + }) + + t.Run("key set", func(t *testing.T) { + originalEnv := os.Getenv(testEnvKey) + os.Setenv(testEnvKey, "batman") + defer os.Setenv(testEnvKey, originalEnv) + + got := GetenvDefault(testEnvKey, "found") + want := "batman" + assertError(t, got, want) + + }) +}