github.com/lynxsecurity/viper@v1.10.0/internal/testutil/env_go1_16.go (about)

     1  //go:build !go1.17
     2  // +build !go1.17
     3  
     4  package testutil
     5  
     6  import (
     7  	"os"
     8  	"testing"
     9  )
    10  
    11  // Based on https://github.com/frankban/quicktest/blob/577841610793d24f99e31cc2c0ef3a541fefd7c7/patch.go#L34-L64
    12  // Licensed under the MIT license
    13  // Copyright (c) 2017 Canonical Ltd.
    14  
    15  // Setenv sets an environment variable to a temporary value for the
    16  // duration of the test.
    17  //
    18  // At the end of the test (see "Deferred execution" in the package docs), the
    19  // environment variable is returned to its original value.
    20  func Setenv(t *testing.T, name, val string) {
    21  	setenv(t, name, val, true)
    22  }
    23  
    24  // setenv sets or unsets an environment variable to a temporary value for the
    25  // duration of the test
    26  func setenv(t *testing.T, name, val string, valOK bool) {
    27  	oldVal, oldOK := os.LookupEnv(name)
    28  	if valOK {
    29  		os.Setenv(name, val)
    30  	} else {
    31  		os.Unsetenv(name)
    32  	}
    33  	t.Cleanup(func() {
    34  		if oldOK {
    35  			os.Setenv(name, oldVal)
    36  		} else {
    37  			os.Unsetenv(name)
    38  		}
    39  	})
    40  }