Skip to content

Commit

Permalink
Add TestSetEnvWithResetCallback.
Browse files Browse the repository at this point in the history
  • Loading branch information
gailazar300 committed Apr 1, 2024
1 parent 71b5429 commit bab8c9a
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
23 changes: 23 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -602,3 +602,26 @@ func ExtractSha256FromResponseBody(body []byte) (string, error) {
func Pointer[K any](val K) *K {
return &val
}

func SetEnvWithResetCallback(key, value string) func() {
oldValue, exist := os.LookupEnv(key)
errMsg := "failed %s %s as environment variable. Cause: %s"

if err := os.Setenv(key, value); err != nil {
log.Debug(fmt.Sprintf(errMsg, "setting", key, err.Error()))
return func() {}
}

if exist {
return func() {
if err := os.Setenv(key, oldValue); err != nil {
log.Debug(fmt.Sprintf(errMsg, "setting", key, err.Error()))
}
}
}
return func() {
if err := os.Unsetenv(key); err != nil {
log.Debug(fmt.Sprintf(errMsg, "unsetting", key, err.Error()))
}
}
}
45 changes: 45 additions & 0 deletions utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils

import (
"fmt"
"os"
"reflect"
"sort"
"testing"
Expand Down Expand Up @@ -287,3 +288,47 @@ func TestValidateMinimumVersion(t *testing.T) {
})
}
}

func TestSetEnvWithResetCallback(t *testing.T) {
type args struct {
key string
value string
}
tests := []struct {
name string
args args
init func()
finish func()
}{
{
name: "existing environment variable",
args: args{key: "TEST_KEY", value: "test_value"},
init: func() {
assert.NoError(t, os.Setenv("TEST_KEY", "test-init-value"))
},
finish: func() {
assert.Equal(t, os.Getenv("TEST_KEY"), "test-init-value")
},
},
{
name: "non-existing environment variable",
args: args{key: "NEW_TEST_KEY", value: "test_value"},
init: func() {

},
finish: func() {
_, exist := os.LookupEnv("NEW_TEST_KEY")
assert.False(t, exist)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.init()
resetCallback := SetEnvWithResetCallback(tt.args.key, tt.args.value)
assert.Equal(t, tt.args.value, os.Getenv(tt.args.key))
resetCallback()
tt.finish()
})
}
}

0 comments on commit bab8c9a

Please sign in to comment.