istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/test/util.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package test
    16  
    17  import (
    18  	"context"
    19  	"os"
    20  
    21  	"go.uber.org/atomic"
    22  )
    23  
    24  // SetForTest sets a variable for the duration of a test, then resets it once the test is complete.
    25  func SetForTest[T any](t Failer, vv *T, v T) {
    26  	old := *vv
    27  	*vv = v
    28  	t.Cleanup(func() {
    29  		*vv = old
    30  	})
    31  }
    32  
    33  // SetEnvForTest sets an environment variable for the duration of a test, then resets it once the test is complete.
    34  func SetEnvForTest(t Failer, k, v string) {
    35  	old, oldset := os.LookupEnv(k)
    36  	if err := os.Setenv(k, v); err != nil {
    37  		t.Fatal(err)
    38  	}
    39  	t.Cleanup(func() {
    40  		if oldset {
    41  			if err := os.Setenv(k, old); err != nil {
    42  				t.Fatal(err)
    43  			}
    44  		} else {
    45  			if err := os.Unsetenv(k); err != nil {
    46  				t.Fatal(err)
    47  			}
    48  		}
    49  	})
    50  }
    51  
    52  // SetAtomicBoolForTest sets a variable for the duration of a test, then resets it once the test is complete atomically.
    53  func SetAtomicBoolForTest(t Failer, vv *atomic.Bool, v bool) {
    54  	old := vv.Load()
    55  	vv.Store(v)
    56  	t.Cleanup(func() {
    57  		vv.Store(old)
    58  	})
    59  }
    60  
    61  // NewStop returns a stop channel that will automatically be closed when the test is complete
    62  func NewStop(t Failer) chan struct{} {
    63  	s := make(chan struct{})
    64  	t.Cleanup(func() {
    65  		close(s)
    66  	})
    67  	return s
    68  }
    69  
    70  // NewContext returns a context that will automatically be closed when the test is complete
    71  func NewContext(t Failer) context.Context {
    72  	ctx, cancel := context.WithCancel(context.Background())
    73  	t.Cleanup(cancel)
    74  	return ctx
    75  }