github.com/profects/terraform@v0.9.0-beta1.0.20170227135739-92d4809db30d/backend/local/testing.go (about)

     1  package local
     2  
     3  import (
     4  	"io/ioutil"
     5  	"path/filepath"
     6  	"testing"
     7  
     8  	"github.com/hashicorp/terraform/terraform"
     9  )
    10  
    11  // TestLocal returns a configured Local struct with temporary paths and
    12  // in-memory ContextOpts.
    13  //
    14  // No operations will be called on the returned value, so you can still set
    15  // public fields without any locks.
    16  func TestLocal(t *testing.T) *Local {
    17  	tempDir := testTempDir(t)
    18  	return &Local{
    19  		StatePath:       filepath.Join(tempDir, "state.tfstate"),
    20  		StateOutPath:    filepath.Join(tempDir, "state.tfstate"),
    21  		StateBackupPath: filepath.Join(tempDir, "state.tfstate.bak"),
    22  		ContextOpts:     &terraform.ContextOpts{},
    23  	}
    24  }
    25  
    26  // TestLocalProvider modifies the ContextOpts of the *Local parameter to
    27  // have a provider with the given name.
    28  func TestLocalProvider(t *testing.T, b *Local, name string) *terraform.MockResourceProvider {
    29  	// Build a mock resource provider for in-memory operations
    30  	p := new(terraform.MockResourceProvider)
    31  	p.DiffReturn = &terraform.InstanceDiff{}
    32  	p.RefreshFn = func(
    33  		info *terraform.InstanceInfo,
    34  		s *terraform.InstanceState) (*terraform.InstanceState, error) {
    35  		return s, nil
    36  	}
    37  	p.ResourcesReturn = []terraform.ResourceType{
    38  		terraform.ResourceType{
    39  			Name: "test_instance",
    40  		},
    41  	}
    42  
    43  	// Initialize the opts
    44  	if b.ContextOpts == nil {
    45  		b.ContextOpts = &terraform.ContextOpts{}
    46  	}
    47  	if b.ContextOpts.Providers == nil {
    48  		b.ContextOpts.Providers = make(map[string]terraform.ResourceProviderFactory)
    49  	}
    50  
    51  	// Setup our provider
    52  	b.ContextOpts.Providers[name] = func() (terraform.ResourceProvider, error) {
    53  		return p, nil
    54  	}
    55  
    56  	return p
    57  }
    58  
    59  func testTempDir(t *testing.T) string {
    60  	d, err := ioutil.TempDir("", "tf")
    61  	if err != nil {
    62  		t.Fatalf("err: %s", err)
    63  	}
    64  
    65  	return d
    66  }