func (repo *FakeBuildpackRepository) Create(name string, position *int, enabled *bool, locked *bool) (createdBuildpack models.Buildpack, apiErr error) { if repo.CreateBuildpackExists { return repo.CreateBuildpack, errors.NewHttpError(400, errors.BUILDPACK_EXISTS, "Buildpack already exists") } repo.CreateBuildpack = models.Buildpack{Name: name, Position: position, Enabled: enabled, Locked: locked} return repo.CreateBuildpack, repo.CreateApiResponse }
func (repo *FakeOrgRepository) Create(name string) (apiErr error) { if repo.CreateOrgExists { apiErr = errors.NewHttpError(400, errors.ORG_EXISTS, "Space already exists") return } repo.CreateName = name return }
func (repo *FakeSpaceRepository) Create(name string, orgGuid string) (space models.Space, apiErr error) { if repo.CreateSpaceExists { apiErr = errors.NewHttpError(400, errors.SPACE_EXISTS, "Space already exists") return } repo.CreateSpaceName = name repo.CreateSpaceOrgGuid = orgGuid space = repo.CreateSpaceSpace return }
func cloudControllerErrorHandler(statusCode int, body []byte) error { response := ccErrorResponse{} json.Unmarshal(body, &response) if response.Code == 1000 { return errors.NewInvalidTokenError(response.Description) } else { return errors.NewHttpError(statusCode, strconv.Itoa(response.Code), response.Description) } }
func (repo *FakeUserRepository) Create(username, password string) (apiErr error) { repo.CreateUserUsername = username repo.CreateUserPassword = password if repo.CreateUserExists { apiErr = errors.NewHttpError(400, errors.USER_EXISTS, "User already exists") } return }
func (repo *FakeAppSummaryRepo) GetSummary(appGuid string) (summary models.AppSummary, apiErr error) { repo.GetSummaryAppGuid = appGuid summary = repo.GetSummarySummary if repo.GetSummaryErrorCode != "" { apiErr = errors.NewHttpError(400, repo.GetSummaryErrorCode, "Error") } return }
func (repo *FakePasswordRepo) UpdatePassword(old string, new string) (apiErr errors.Error) { repo.UpdateOldPassword = old repo.UpdateNewPassword = new if repo.UpdateUnauthorized { apiErr = errors.NewHttpError(401, "", "", "unauthorized", "Authorization Failed") } return }
func (repo *FakeServiceBindingRepo) Create(instanceGuid, appGuid string) (apiErr error) { repo.CreateServiceInstanceGuid = instanceGuid repo.CreateApplicationGuid = appGuid if repo.CreateErrorCode != "" { apiErr = errors.NewHttpError(400, repo.CreateErrorCode, "Error binding service") } return }
func (gateway Gateway) doRequestAndHandlerError(request *Request) (rawResponse *http.Response, apiErr errors.Error) { rawResponse, err := gateway.doRequest(request.HttpReq) if err != nil { apiErr = WrapSSLErrors(request.HttpReq.URL.Host, err) return } if rawResponse.StatusCode > 299 { errorResponse := gateway.errHandler(rawResponse) apiErr = errors.NewHttpError(rawResponse.StatusCode, errorResponse.ResponseHeader, errorResponse.ResponseBody, errorResponse.Code, errorResponse.Description) } return }
func (repo *FakeApplicationRepository) Read(name string) (app models.Application, apiErr error) { repo.ReadName = name app = repo.ReadApp if repo.ReadErr { apiErr = errors.New("Error finding app by name.") } if repo.ReadAuthErr { apiErr = errors.NewHttpError(401, "1000", "Authentication failed.") } if repo.ReadNotFound { apiErr = errors.NewModelNotFoundError("App", name) } return }
func (repo *FakeAppInstancesRepo) GetInstances(appGuid string) (instances []models.AppInstanceFields, apiErr error) { repo.GetInstancesAppGuid = appGuid time.Sleep(1 * time.Millisecond) //needed for Windows only, otherwise it thinks error codes are not assigned if len(repo.GetInstancesResponses) > 0 { instances = repo.GetInstancesResponses[0] repo.GetInstancesResponses = repo.GetInstancesResponses[1:] } if len(repo.GetInstancesErrorCodes) > 0 { errorCode := repo.GetInstancesErrorCodes[0] repo.GetInstancesErrorCodes = repo.GetInstancesErrorCodes[1:] if errorCode != "" { apiErr = errors.NewHttpError(400, errorCode, "Error staging app") } } return }
func (uaa UAAAuthenticationRepository) getAuthToken(data url.Values) error { type uaaErrorResponse struct { Code string `json:"error"` Description string `json:"error_description"` } type AuthenticationResponse struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` RefreshToken string `json:"refresh_token"` Error uaaErrorResponse `json:"error"` } path := fmt.Sprintf("%s/oauth/token", uaa.config.AuthenticationEndpoint()) request, err := uaa.gateway.NewRequest("POST", path, "Basic "+base64.StdEncoding.EncodeToString([]byte("cf:")), strings.NewReader(data.Encode())) if err != nil { return errors.NewWithError("Failed to start oauth request", err) } request.HttpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") response := new(AuthenticationResponse) _, err = uaa.gateway.PerformRequestForJSONResponse(request, &response) switch err.(type) { case nil: case errors.HttpError: return err default: return errors.NewWithError("auth request failed", err) } // TODO: get the actual status code if response.Error.Code != "" { return errors.NewHttpError(0, response.Error.Code, response.Error.Description) } uaa.config.SetAccessToken(fmt.Sprintf("%s %s", response.TokenType, response.AccessToken)) uaa.config.SetRefreshToken(response.RefreshToken) return nil }
{"failed"}, {"shared domains"}, {"borked!"}, }) }) It("lists only the domains for the org if the new shared_domains endpoint returns a 404", func() { orgFields := models.OrganizationFields{ Name: "my-org", Guid: "my-org-guid", } reqFactory := &testreq.FakeReqFactory{LoginSuccess: true, TargetedOrgSuccess: true, OrganizationFields: orgFields} domainRepo := &testapi.FakeDomainRepository{ ListSharedDomainsApiResponse: errors.NewHttpError(404, "", "", "", ""), ListDomainsForOrgDomains: []models.DomainFields{ models.DomainFields{Name: "ze-domain"}, }, } ui := callListDomains([]string{}, reqFactory, domainRepo) testassert.SliceContains(ui.Outputs, testassert.Lines{ {"Getting domains in org", "my-org", "my-user"}, {"ze-domain"}, }) }) It("TestListDomainsOrgDomainsFails", func() { orgFields := models.OrganizationFields{} orgFields.Name = "my-org"
}) }) It("successfully pushes an app when the CC API only supports the old domains endpoints", func() { privateDomain := models.DomainFields{ Shared: false, Name: "private.cf-app.com", Guid: "private-domain-guid", } sharedDomain := models.DomainFields{ Name: "shared.cf-app.com", Shared: true, Guid: "shared-domain-guid", } domainRepo.ListSharedDomainsApiResponse = errors.NewHttpError(404, "the-code", "something went wrong") domainRepo.ListDomainsDomains = []models.DomainFields{privateDomain, sharedDomain} routeRepo.FindByHostAndDomainErr = true appRepo.ReadNotFound = true callPush("-t", "111", "my-new-app") Expect(routeRepo.FindByHostAndDomainHost).To(Equal("my-new-app")) Expect(routeRepo.CreatedHost).To(Equal("my-new-app")) Expect(routeRepo.CreatedDomainGuid).To(Equal("shared-domain-guid")) Expect(routeRepo.BoundAppGuid).To(Equal("my-new-app-guid")) Expect(routeRepo.BoundRouteGuid).To(Equal("my-new-app-route-guid")) testassert.SliceContains(ui.Outputs, testassert.Lines{ {"Creating app", "my-new-app", "my-org", "my-space"}, {"OK"},
{"failed"}, {"shared domains"}, {"borked!"}, }) }) It("lists only the domains for the org if the new shared_domains endpoint returns a 404", func() { orgFields := models.OrganizationFields{ Name: "my-org", Guid: "my-org-guid", } reqFactory := &testreq.FakeReqFactory{LoginSuccess: true, TargetedOrgSuccess: true, OrganizationFields: orgFields} domainRepo := &testapi.FakeDomainRepository{ ListSharedDomainsApiResponse: errors.NewHttpError(404, "9003", "something bad happened"), ListDomainsForOrgDomains: []models.DomainFields{ models.DomainFields{Name: "ze-domain"}, }, } ui := callListDomains([]string{}, reqFactory, domainRepo) testassert.SliceContains(ui.Outputs, testassert.Lines{ {"Getting domains in org", "my-org", "my-user"}, {"ze-domain"}, }) }) It("TestListDomainsOrgDomainsFails", func() { orgFields := models.OrganizationFields{} orgFields.Name = "my-org"
callPush("app") testassert.SliceContains(ui.Outputs, testassert.Lines{ {"Uploading"}, {"FAILED"}, }) }) Describe("when binding the route fails", func() { BeforeEach(func() { routeRepo.FindByHostAndDomainRoute.Host = "existing-app" routeRepo.FindByHostAndDomainRoute.Domain = models.DomainFields{Name: "foo.cf-app.com"} }) It("suggests using 'random-route' if the default route is taken", func() { routeRepo.BindErr = errors.NewHttpError(400, errors.INVALID_RELATION, "The URL not available") callPush("existing-app") testassert.SliceContains(ui.Outputs, testassert.Lines{ {"FAILED"}, {"existing-app.foo.cf-app.com", "already in use"}, {"TIP", "random-route"}, }) }) It("does not suggest using 'random-route' for other failures", func() { routeRepo.BindErr = errors.NewHttpError(500, "some-code", "exception happened") callPush("existing-app")
{"Binding service", "global-service", "app1", "my-org", "my-space", "my-user"}, {"OK"}, {"Creating", "app2"}, {"OK"}, {"Binding service", "app2-service", "app2", "my-org", "my-space", "my-user"}, {"OK"}, {"Binding service", "global-service", "app2", "my-org", "my-space", "my-user"}, {"OK"}, }) }) }) Context("when the app is already bound to the service", func() { BeforeEach(func() { appRepo.ReadReturns.App = maker.NewApp(maker.Overrides{}) serviceBinder.BindApplicationReturns.Error = errors.NewHttpError(500, "90003", "it don't work") }) It("gracefully continues", func() { callPush() Expect(len(serviceBinder.AppsToBind)).To(Equal(4)) testassert.SliceDoesNotContain(ui.Outputs, testassert.Lines{{"FAILED"}}) }) }) Context("when the service instance can't be found", func() { BeforeEach(func() { routeRepo.FindByHostAndDomainErr = true serviceRepo.FindInstanceByNameErr = true manifestRepo.ReadManifestReturns.Manifest = manifestWithServicesAndEnv() })
Path: "/v2/service_instances", Matcher: testnet.RequestBodyMatcher(`{"name":"my-service","service_plan_guid":"different-plan-guid","space_guid":"my-space-guid","async":true}`), Response: testnet.TestResponse{ Status: http.StatusBadRequest, Body: `{"code":60002,"description":"The service instance name is taken: my-service"}`, }}), findServiceInstanceReq, serviceOfferingReq) }) It("fails if the plan is different", func() { err := repo.CreateServiceInstance("my-service", "different-plan-guid") Expect(testHandler).To(testnet.HaveAllRequestsCalled()) Expect(err).To(HaveOccurred()) Expect(err).To(BeAssignableToTypeOf(errors.NewHttpError(400, "", ""))) }) }) }) Describe("finding service instances by name", func() { It("returns the service instance", func() { setupTestServer(findServiceInstanceReq, serviceOfferingReq) instance, err := repo.FindInstanceByName("my-service") Expect(testHandler).To(testnet.HaveAllRequestsCalled()) Expect(err).NotTo(HaveOccurred()) Expect(instance.Name).To(Equal("my-service")) Expect(instance.Guid).To(Equal("my-service-instance-guid"))
It("creates the quota with paid service plans allowed", func() { runCommand("--allow-paid-service-plans", "my-for-profit-quota") Expect(quotaRepo.CreateCalledWith.NonBasicServicesAllowed).To(BeTrue()) }) }) Context("when creating a quota returns an error", func() { It("alerts the user when creating the quota fails", func() { quotaRepo.CreateReturns.Error = errors.New("WHOOP THERE IT IS") runCommand("my-quota") Expect(ui.Outputs).To(ContainSubstrings( []string{"creating quota", "my-quota"}, []string{"FAILED"}, )) }) It("warns the user when quota already exists", func() { quotaRepo.CreateReturns.Error = errors.NewHttpError(400, "240002", "Quota Definition is taken: quota-sct") runCommand("Banana") Expect(ui.Outputs).ToNot(ContainSubstrings( []string{"FAILED"}, )) Expect(ui.WarnOutputs).To(ContainSubstrings([]string{"already exists"})) }) }) }) })
}) It("TestPushingAppWithOldV2DomainsEndpoint", func() { deps := getPushDependencies() privateDomain := models.DomainFields{} privateDomain.Shared = false privateDomain.Name = "private.cf-app.com" privateDomain.Guid = "private-domain-guid" sharedDomain := models.DomainFields{} sharedDomain.Name = "shared.cf-app.com" sharedDomain.Shared = true sharedDomain.Guid = "shared-domain-guid" deps.domainRepo.ListSharedDomainsApiResponse = errors.NewHttpError(404, "", "", "", "") deps.domainRepo.ListDomainsDomains = []models.DomainFields{privateDomain, sharedDomain} deps.routeRepo.FindByHostAndDomainErr = true deps.appRepo.ReadNotFound = true ui := callPush([]string{"-t", "111", "my-new-app"}, deps) Expect(deps.routeRepo.FindByHostAndDomainHost).To(Equal("my-new-app")) Expect(deps.routeRepo.CreatedHost).To(Equal("my-new-app")) Expect(deps.routeRepo.CreatedDomainGuid).To(Equal("shared-domain-guid")) Expect(deps.routeRepo.BoundAppGuid).To(Equal("my-new-app-guid")) Expect(deps.routeRepo.BoundRouteGuid).To(Equal("my-new-app-route-guid")) testassert.SliceContains(ui.Outputs, testassert.Lines{ {"Creating app", "my-new-app", "my-org", "my-space"}, {"OK"},
package net import ( "cf/configuration" "cf/errors" "encoding/json" ) type uaaErrorResponse struct { Code string `json:"error"` Description string `json:"error_description"` } var uaaErrorHandler = func(statusCode int, body []byte) error { response := uaaErrorResponse{} json.Unmarshal(body, &response) if response.Code == "invalid_token" { return errors.NewInvalidTokenError(response.Description) } else { return errors.NewHttpError(statusCode, response.Code, response.Description) } } func NewUAAGateway(config configuration.Reader) Gateway { return newGateway(uaaErrorHandler, config) }