github.com/kanishk98/terraform@v1.3.0-dev.0.20220917174235-661ca8088a6a/internal/experiments/testing.go (about)

     1  package experiments
     2  
     3  import (
     4  	"testing"
     5  )
     6  
     7  // OverrideForTesting temporarily overrides the global tables
     8  // of experiments in order to allow for a predictable set when unit testing
     9  // the experiments infrastructure code.
    10  //
    11  // The correct way to use this function is to defer a call to its result so
    12  // that the original tables can be restored at the conclusion of the calling
    13  // test:
    14  //
    15  //	defer experiments.OverrideForTesting(t, current, concluded)()
    16  //
    17  // This function modifies global variables that are normally fixed throughout
    18  // our execution, so this function must not be called from non-test code and
    19  // any test using it cannot safely run concurrently with other tests.
    20  func OverrideForTesting(t *testing.T, current Set, concluded map[Experiment]string) func() {
    21  	// We're not currently using the given *testing.T in here, but we're
    22  	// requiring it anyway in case we might need it in future, and because
    23  	// it hopefully reinforces that only test code should be calling this.
    24  
    25  	realCurrents := currentExperiments
    26  	realConcludeds := concludedExperiments
    27  	currentExperiments = current
    28  	concludedExperiments = concluded
    29  	return func() {
    30  		currentExperiments = realCurrents
    31  		concludedExperiments = realConcludeds
    32  	}
    33  }