Skip to content

Commit

Permalink
test: use t.Setenv
Browse files Browse the repository at this point in the history
  • Loading branch information
crazy-max committed May 5, 2023
1 parent 3c9aa08 commit 88a2348
Showing 1 changed file with 1 addition and 55 deletions.
56 changes: 1 addition & 55 deletions loader_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package gonfig

import (
"os"
"strings"
"testing"
"time"
Expand All @@ -13,8 +12,6 @@ import (
)

func TestEnvLoader(t *testing.T) {
defer UnsetEnv(env.DefaultNamePrefix)

testCases := []struct {
desc string
cfgfile string
Expand Down Expand Up @@ -66,12 +63,10 @@ func TestEnvLoader(t *testing.T) {

for _, tt := range testCases {
t.Run(tt.desc, func(t *testing.T) {
UnsetEnv(env.DefaultNamePrefix)

if tt.environ != nil {
for _, environ := range tt.environ {
n := strings.SplitN(environ, "=", 2)
os.Setenv(n[0], n[1])
t.Setenv(n[0], n[1])
}
}

Expand Down Expand Up @@ -264,52 +259,3 @@ func TestFlagLoader(t *testing.T) {
})
}
}

func UnsetEnv(prefix string) (restore func()) {
before := map[string]string{}

for _, e := range os.Environ() {
if !strings.HasPrefix(e, prefix) {
continue
}

parts := strings.SplitN(e, "=", 2)
before[parts[0]] = parts[1]

os.Unsetenv(parts[0])
}

return func() {
after := map[string]string{}

for _, e := range os.Environ() {
if !strings.HasPrefix(e, prefix) {
continue
}

parts := strings.SplitN(e, "=", 2)
after[parts[0]] = parts[1]

// Check if the envar previously existed
v, ok := before[parts[0]]
if !ok {
// This is a newly added envar with prefix, zap it
os.Unsetenv(parts[0])
continue
}

if parts[1] != v {
// If the envar value has changed, set it back
os.Setenv(parts[0], v)
}
}

// Still need to check if there have been any deleted envars
for k, v := range before {
if _, ok := after[k]; !ok {
// k is not present in after, so we set it.
os.Setenv(k, v)
}
}
}
}

0 comments on commit 88a2348

Please sign in to comment.