github.com/treeverse/lakefs@v1.24.1-0.20240520134607-95648127bfb0/pkg/testutil/env.go (about)

     1  package testutil
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  )
     7  
     8  // WithEnvironmentVariable Sets an environment variable for the duration of the test,
     9  //
    10  //	restoring it to a previous value, if any, at teardown.
    11  //
    12  // Warning: Environment variables affect other goroutines that might be running at the same time -
    13  //
    14  //	so this function is *not* thread safe.
    15  func WithEnvironmentVariable(t *testing.T, k, v string) {
    16  	originalV, hasAny := os.LookupEnv(k)
    17  	err := os.Setenv(k, v)
    18  	if err != nil {
    19  		t.Fatal(err)
    20  		return
    21  	}
    22  	t.Cleanup(func() {
    23  		if hasAny {
    24  			_ = os.Setenv(k, originalV)
    25  		} else {
    26  			_ = os.Unsetenv(k)
    27  		}
    28  	})
    29  }