github.com/kevinklinger/open_terraform@v1.3.6/noninternal/configs/configload/testing.go (about)

     1  package configload
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"testing"
     7  )
     8  
     9  // NewLoaderForTests is a variant of NewLoader that is intended to be more
    10  // convenient for unit tests.
    11  //
    12  // The loader's modules directory is a separate temporary directory created
    13  // for each call. Along with the created loader, this function returns a
    14  // cleanup function that should be called before the test completes in order
    15  // to remove that temporary directory.
    16  //
    17  // In the case of any errors, t.Fatal (or similar) will be called to halt
    18  // execution of the test, so the calling test does not need to handle errors
    19  // itself.
    20  func NewLoaderForTests(t *testing.T) (*Loader, func()) {
    21  	t.Helper()
    22  
    23  	modulesDir, err := ioutil.TempDir("", "tf-configs")
    24  	if err != nil {
    25  		t.Fatalf("failed to create temporary modules dir: %s", err)
    26  		return nil, func() {}
    27  	}
    28  
    29  	cleanup := func() {
    30  		os.RemoveAll(modulesDir)
    31  	}
    32  
    33  	loader, err := NewLoader(&Config{
    34  		ModulesDir: modulesDir,
    35  	})
    36  	if err != nil {
    37  		cleanup()
    38  		t.Fatalf("failed to create config loader: %s", err)
    39  		return nil, func() {}
    40  	}
    41  
    42  	return loader, cleanup
    43  }