Add common package

drew/add-droneio
Drew Bednar 4 months ago
parent 67d9b410cb
commit 217f05223d

@ -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
}
}

@ -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)
})
}
Loading…
Cancel
Save