From 3de8e2343ed9211ea9b446deaae2ce4c0f0b31a6 Mon Sep 17 00:00:00 2001 From: Armon Dadgar Date: Thu, 2 Oct 2014 12:22:06 -0700 Subject: [PATCH] remote: testing remote state fetch --- remote/client.go | 4 +- remote/client_test.go | 85 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 2 deletions(-) diff --git a/remote/client.go b/remote/client.go index 8aee8aef7..a0866b4cb 100644 --- a/remote/client.go +++ b/remote/client.go @@ -57,11 +57,11 @@ func GetState(conf *terraform.RemoteState) (*RemoteStatePayload, error) { case http.StatusUnauthorized: return nil, fmt.Errorf("Remote server requires authentication") case http.StatusForbidden: - return nil, fmt.Errorf("Invalid authentication token") + return nil, fmt.Errorf("Invalid authentication") case http.StatusInternalServerError: return nil, fmt.Errorf("Remote server reporting internal error") default: - return nil, fmt.Errorf("Received unexpected HTTP response code %d", resp.StatusCode) + return nil, fmt.Errorf("Unexpected HTTP response code %d", resp.StatusCode) } // Read in the body diff --git a/remote/client_test.go b/remote/client_test.go index 73a5e6e48..fc639a091 100644 --- a/remote/client_test.go +++ b/remote/client_test.go @@ -5,6 +5,7 @@ import ( "crypto/md5" "io" "net/http" + "net/http/httptest" "strings" "testing" @@ -74,3 +75,87 @@ REQ: goto REQ } } + +func TestGetState(t *testing.T) { + type tcase struct { + Code int + Header http.Header + Body []byte + ExpectMD5 []byte + ExpectErr string + } + inp := []byte("testing") + inpMD5 := md5.Sum(inp) + hash := inpMD5[:16] + cases := []*tcase{ + &tcase{ + Code: http.StatusOK, + Body: inp, + ExpectMD5: hash, + }, + &tcase{ + Code: http.StatusNoContent, + }, + &tcase{ + Code: http.StatusNotFound, + }, + &tcase{ + Code: http.StatusUnauthorized, + ExpectErr: "Remote server requires authentication", + }, + &tcase{ + Code: http.StatusForbidden, + ExpectErr: "Invalid authentication", + }, + &tcase{ + Code: http.StatusInternalServerError, + ExpectErr: "Remote server reporting internal error", + }, + &tcase{ + Code: 418, + ExpectErr: "Unexpected HTTP response code 418", + }, + } + + for _, tc := range cases { + cb := func(resp http.ResponseWriter, req *http.Request) { + for k, v := range tc.Header { + resp.Header()[k] = v + } + resp.WriteHeader(tc.Code) + if tc.Body != nil { + resp.Write(tc.Body) + } + } + s := httptest.NewServer(http.HandlerFunc(cb)) + defer s.Close() + + remote := &terraform.RemoteState{ + Name: "foobar", + Server: s.URL, + } + + payload, err := GetState(remote) + errStr := "" + if err != nil { + errStr = err.Error() + } + if errStr != tc.ExpectErr { + t.Fatalf("bad err: %v %v", errStr, tc.ExpectErr) + } + + if tc.ExpectMD5 != nil { + if payload == nil || !bytes.Equal(payload.MD5, tc.ExpectMD5) { + t.Fatalf("bad: %#v", payload) + } + } + + if tc.Body != nil { + buf := bytes.NewBuffer(nil) + io.Copy(buf, payload.R) + if !bytes.Equal(buf.Bytes(), tc.Body) { + t.Fatalf("bad: %#v", payload) + } + } + } +}