github.com/opentofu/opentofu@v1.7.1/internal/configs/configload/testing.go (about)

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