src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/testutil/temp_env.go (about)

     1  package testutil
     2  
     3  import "os"
     4  
     5  // Setenv sets the value of an environment variable for the duration of a test.
     6  // It returns value.
     7  func Setenv(c Cleanuper, name, value string) string {
     8  	SaveEnv(c, name)
     9  	os.Setenv(name, value)
    10  	return value
    11  }
    12  
    13  // Setenv unsets an environment variable for the duration of a test.
    14  func Unsetenv(c Cleanuper, name string) {
    15  	SaveEnv(c, name)
    16  	os.Unsetenv(name)
    17  }
    18  
    19  // SaveEnv saves the current value of an environment variable so that it will be
    20  // restored after a test has finished.
    21  func SaveEnv(c Cleanuper, name string) {
    22  	oldValue, existed := os.LookupEnv(name)
    23  	if existed {
    24  		c.Cleanup(func() { os.Setenv(name, oldValue) })
    25  	} else {
    26  		c.Cleanup(func() { os.Unsetenv(name) })
    27  	}
    28  }