github.com/rakutentech/cli@v6.12.5-0.20151006231303-24468b65536e+incompatible/cf/net/cloud_controller_gateway_test.go (about)

     1  package net_test
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"time"
     8  
     9  	"github.com/cloudfoundry/cli/cf/configuration/core_config"
    10  	"github.com/cloudfoundry/cli/cf/errors"
    11  	. "github.com/cloudfoundry/cli/cf/net"
    12  	testconfig "github.com/cloudfoundry/cli/testhelpers/configuration"
    13  	testterm "github.com/cloudfoundry/cli/testhelpers/terminal"
    14  	. "github.com/onsi/ginkgo"
    15  	. "github.com/onsi/gomega"
    16  )
    17  
    18  var failingCloudControllerRequest = func(writer http.ResponseWriter, request *http.Request) {
    19  	writer.WriteHeader(http.StatusBadRequest)
    20  	jsonResponse := `{ "code": 210003, "description": "The host is taken: test1" }`
    21  	fmt.Fprintln(writer, jsonResponse)
    22  }
    23  
    24  var invalidTokenCloudControllerRequest = func(writer http.ResponseWriter, request *http.Request) {
    25  	writer.WriteHeader(http.StatusBadRequest)
    26  	jsonResponse := `{ "code": 1000, "description": "The token is invalid" }`
    27  	fmt.Fprintln(writer, jsonResponse)
    28  }
    29  
    30  var _ = Describe("Cloud Controller Gateway", func() {
    31  	var gateway Gateway
    32  	var config core_config.Reader
    33  
    34  	BeforeEach(func() {
    35  		config = testconfig.NewRepository()
    36  		gateway = NewCloudControllerGateway(config, time.Now, &testterm.FakeUI{})
    37  	})
    38  
    39  	It("parses error responses", func() {
    40  		ts := httptest.NewTLSServer(http.HandlerFunc(failingCloudControllerRequest))
    41  		defer ts.Close()
    42  		gateway.SetTrustedCerts(ts.TLS.Certificates)
    43  
    44  		request, apiErr := gateway.NewRequest("GET", ts.URL, "TOKEN", nil)
    45  		_, apiErr = gateway.PerformRequest(request)
    46  
    47  		Expect(apiErr).NotTo(BeNil())
    48  		Expect(apiErr.Error()).To(ContainSubstring("The host is taken: test1"))
    49  		Expect(apiErr.(errors.HttpError).ErrorCode()).To(ContainSubstring("210003"))
    50  	})
    51  
    52  	It("parses invalid token responses", func() {
    53  		ts := httptest.NewTLSServer(http.HandlerFunc(invalidTokenCloudControllerRequest))
    54  		defer ts.Close()
    55  		gateway.SetTrustedCerts(ts.TLS.Certificates)
    56  
    57  		request, apiErr := gateway.NewRequest("GET", ts.URL, "TOKEN", nil)
    58  		_, apiErr = gateway.PerformRequest(request)
    59  
    60  		Expect(apiErr).NotTo(BeNil())
    61  		Expect(apiErr.Error()).To(ContainSubstring("The token is invalid"))
    62  		Expect(apiErr.(*errors.InvalidTokenError)).To(HaveOccurred())
    63  	})
    64  })