github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/configs/configload/testing.go (about)

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