github.com/haklop/terraform@v0.3.6/command/pull_test.go (about)

     1  package command
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/md5"
     6  	"encoding/base64"
     7  	"encoding/json"
     8  	"net/http"
     9  	"net/http/httptest"
    10  	"testing"
    11  
    12  	"github.com/hashicorp/terraform/remote"
    13  	"github.com/hashicorp/terraform/terraform"
    14  	"github.com/mitchellh/cli"
    15  )
    16  
    17  func TestPull_noRemote(t *testing.T) {
    18  	tmp, cwd := testCwd(t)
    19  	defer testFixCwd(t, tmp, cwd)
    20  
    21  	ui := new(cli.MockUi)
    22  	c := &PullCommand{
    23  		Meta: Meta{
    24  			ContextOpts: testCtxConfig(testProvider()),
    25  			Ui:          ui,
    26  		},
    27  	}
    28  
    29  	args := []string{}
    30  	if code := c.Run(args); code != 1 {
    31  		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
    32  	}
    33  }
    34  
    35  func TestPull_local(t *testing.T) {
    36  	tmp, cwd := testCwd(t)
    37  	defer testFixCwd(t, tmp, cwd)
    38  
    39  	s := terraform.NewState()
    40  	s.Serial = 10
    41  	conf, srv := testRemoteState(t, s, 200)
    42  
    43  	s = terraform.NewState()
    44  	s.Serial = 5
    45  	s.Remote = conf
    46  	defer srv.Close()
    47  
    48  	// Store the local state
    49  	buf := bytes.NewBuffer(nil)
    50  	terraform.WriteState(s, buf)
    51  	remote.EnsureDirectory()
    52  	remote.Persist(buf)
    53  
    54  	ui := new(cli.MockUi)
    55  	c := &PullCommand{
    56  		Meta: Meta{
    57  			ContextOpts: testCtxConfig(testProvider()),
    58  			Ui:          ui,
    59  		},
    60  	}
    61  	args := []string{}
    62  	if code := c.Run(args); code != 0 {
    63  		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
    64  	}
    65  }
    66  
    67  // testRemoteState is used to make a test HTTP server to
    68  // return a given state file
    69  func testRemoteState(t *testing.T, s *terraform.State, c int) (*terraform.RemoteState, *httptest.Server) {
    70  	var b64md5 string
    71  	buf := bytes.NewBuffer(nil)
    72  
    73  	if s != nil {
    74  		enc := json.NewEncoder(buf)
    75  		if err := enc.Encode(s); err != nil {
    76  			t.Fatalf("err: %v", err)
    77  		}
    78  		md5 := md5.Sum(buf.Bytes())
    79  		b64md5 = base64.StdEncoding.EncodeToString(md5[:16])
    80  	}
    81  
    82  	cb := func(resp http.ResponseWriter, req *http.Request) {
    83  		if req.Method == "PUT" {
    84  			resp.WriteHeader(c)
    85  			return
    86  		}
    87  		if s == nil {
    88  			resp.WriteHeader(404)
    89  			return
    90  		}
    91  		resp.Header().Set("Content-MD5", b64md5)
    92  		resp.Write(buf.Bytes())
    93  	}
    94  	srv := httptest.NewServer(http.HandlerFunc(cb))
    95  	remote := &terraform.RemoteState{
    96  		Type:   "http",
    97  		Config: map[string]string{"address": srv.URL},
    98  	}
    99  	return remote, srv
   100  }