func (repo CloudControllerRouteRepository) Find(host string, domain models.DomainFields, path string, port int) (models.Route, error) { var route models.Route queryString := queryStringForRouteSearch(host, domain.GUID, path, port) q := struct { Query string `url:"q"` InlineRelationsDepth int `url:"inline-relations-depth"` }{queryString, 1} opt, _ := query.Values(q) found := false apiErr := repo.gateway.ListPaginatedResources( repo.config.APIEndpoint(), fmt.Sprintf("/v2/routes?%s", opt.Encode()), resources.RouteResource{}, func(resource interface{}) bool { keepSearching := true route = resource.(resources.RouteResource).ToModel() if doesNotMatchVersionSpecificAttributes(route, path, port) { return keepSearching } found = true return !keepSearching }) if apiErr == nil && !found { apiErr = errors.NewModelNotFoundError("Route", host) } return route, apiErr }
func (repo CloudControllerUserRepository) FindByUsername(username string) (models.UserFields, error) { uaaEndpoint, apiErr := repo.getAuthEndpoint() var user models.UserFields if apiErr != nil { return user, apiErr } usernameFilter := neturl.QueryEscape(fmt.Sprintf(`userName Eq "%s"`, username)) path := fmt.Sprintf("%s/Users?attributes=id,userName&filter=%s", uaaEndpoint, usernameFilter) users, apiErr := repo.updateOrFindUsersWithUAAPath([]models.UserFields{}, path) if apiErr != nil { errType, ok := apiErr.(errors.HTTPError) if ok { if errType.StatusCode() == 403 { return user, errors.NewAccessDeniedError() } } return user, apiErr } else if len(users) == 0 { return user, errors.NewModelNotFoundError("User", username) } return users[0], apiErr }
func (repo CloudControllerServiceRepository) FindInstanceByName(name string) (instance models.ServiceInstance, apiErr error) { path := fmt.Sprintf("%s/v2/spaces/%s/service_instances?return_user_provided_service_instances=true&q=%s&inline-relations-depth=1", repo.config.APIEndpoint(), repo.config.SpaceFields().GUID, url.QueryEscape("name:"+name)) responseJSON := new(resources.PaginatedServiceInstanceResources) apiErr = repo.gateway.GetResource(path, responseJSON) if apiErr != nil { return } if len(responseJSON.Resources) == 0 { apiErr = errors.NewModelNotFoundError("Service instance", name) return } instanceResource := responseJSON.Resources[0] instance = instanceResource.ToModel() if instanceResource.Entity.ServicePlan.Metadata.GUID != "" { resource := &resources.ServiceOfferingResource{} path = fmt.Sprintf("%s/v2/services/%s", repo.config.APIEndpoint(), instanceResource.Entity.ServicePlan.Entity.ServiceOfferingGUID) apiErr = repo.gateway.GetResource(path, resource) instance.ServiceOffering = resource.ToFields() } return }
func (repo *OldFakeBuildpackRepository) FindByName(name string) (buildpack models.Buildpack, apiErr error) { repo.FindByNameName = name buildpack = repo.FindByNameBuildpack if repo.FindByNameNotFound { apiErr = errors.NewModelNotFoundError("Buildpack", name) } return }
func (repo CloudControllerServiceRepository) FindServiceOfferingByLabelAndProvider(label, provider string) (models.ServiceOffering, error) { path := fmt.Sprintf("/v2/services?q=%s", url.QueryEscape("label:"+label+";provider:"+provider)) offerings, apiErr := repo.getServiceOfferings(path) if apiErr != nil { return models.ServiceOffering{}, apiErr } else if len(offerings) == 0 { apiErr = errors.NewModelNotFoundError("Service offering", label+" "+provider) return models.ServiceOffering{}, apiErr } return offerings[0], apiErr }
func (repo CloudControllerServiceRepository) FindServiceOfferingsForSpaceByLabel(spaceGUID, name string) (offerings models.ServiceOfferings, err error) { offerings, err = repo.getServiceOfferings(fmt.Sprintf("/v2/spaces/%s/services?q=%s", spaceGUID, url.QueryEscape("label:"+name))) if httpErr, ok := err.(errors.HTTPError); ok && httpErr.ErrorCode() == errors.BadQueryParameter { offerings, err = repo.findServiceOfferingsByPaginating(spaceGUID, name) } if err == nil && len(offerings) == 0 { err = errors.NewModelNotFoundError("Service offering", name) } return }
func (repo CloudControllerQuotaRepository) FindByName(name string) (quota models.QuotaFields, apiErr error) { path := fmt.Sprintf("/v2/quota_definitions?q=%s", url.QueryEscape("name:"+name)) quotas, apiErr := repo.findAllWithPath(path) if apiErr != nil { return } if len(quotas) == 0 { apiErr = errors.NewModelNotFoundError("Quota", name) return } quota = quotas[0] return }
func (repo CloudControllerServiceAuthTokenRepository) FindByLabelAndProvider(label, provider string) (authToken models.ServiceAuthTokenFields, apiErr error) { path := fmt.Sprintf("/v2/service_auth_tokens?q=%s", url.QueryEscape("label:"+label+";provider:"+provider)) authTokens, apiErr := repo.findAllWithPath(path) if apiErr != nil { return } if len(authTokens) == 0 { apiErr = errors.NewModelNotFoundError("Service Auth Token", label+" "+provider) return } authToken = authTokens[0] return }
func (repo CloudControllerSpaceQuotaRepository) FindByGUID(guid string) (quota models.SpaceQuota, apiErr error) { quotas, apiErr := repo.FindByOrg(repo.config.OrganizationFields().GUID) if apiErr != nil { return } for _, quota := range quotas { if quota.GUID == guid { return quota, nil } } apiErr = errors.NewModelNotFoundError("Space Quota", guid) return models.SpaceQuota{}, apiErr }
func (repo CloudControllerSpaceQuotaRepository) FindByNameAndOrgGUID(spaceQuotaName string, orgGUID string) (models.SpaceQuota, error) { quotas, apiErr := repo.FindByOrg(orgGUID) if apiErr != nil { return models.SpaceQuota{}, apiErr } for _, quota := range quotas { if quota.Name == spaceQuotaName { return quota, nil } } apiErr = errors.NewModelNotFoundError("Space Quota", spaceQuotaName) return models.SpaceQuota{}, apiErr }
func (repo CloudControllerStackRepository) FindByName(name string) (stack models.Stack, apiErr error) { path := fmt.Sprintf("/v2/stacks?q=%s", url.QueryEscape("name:"+name)) stacks, apiErr := repo.findAllWithPath(path) if apiErr != nil { return } if len(stacks) == 0 { apiErr = errors.NewModelNotFoundError("Stack", name) return } stack = stacks[0] return }
func (repo CloudControllerDomainRepository) findOneWithPath(path, name string) (models.DomainFields, error) { var domain models.DomainFields foundDomain := false err := repo.listDomains(path, func(result models.DomainFields) bool { domain = result foundDomain = true return false }) if err == nil && !foundDomain { err = errors.NewModelNotFoundError("Domain", name) } return domain, err }
func (repo CloudControllerDomainRepository) FindByNameInOrg(name string, orgGUID string) (models.DomainFields, error) { domain, err := repo.findOneWithPath(repo.strategy.OrgDomainURL(orgGUID, name), name) switch err.(type) { case *errors.ModelNotFoundError: domain, err = repo.FindSharedByName(name) if err != nil { return models.DomainFields{}, err } if !domain.Shared { err = errors.NewModelNotFoundError("Domain", name) } } return domain, err }
func (repo CloudControllerBuildpackRepository) FindByName(name string) (buildpack models.Buildpack, apiErr error) { foundIt := false apiErr = repo.gateway.ListPaginatedResources( repo.config.APIEndpoint(), fmt.Sprintf("%s?q=%s", buildpacksPath, url.QueryEscape("name:"+name)), resources.BuildpackResource{}, func(resource interface{}) bool { buildpack = resource.(resources.BuildpackResource).ToFields() foundIt = true return false }) if !foundIt { apiErr = errors.NewModelNotFoundError("Buildpack", name) } return }
func (repo CloudControllerRepository) ReadFromSpace(name string, spaceGUID string) (app models.Application, apiErr error) { path := fmt.Sprintf("%s/v2/spaces/%s/apps?q=%s&inline-relations-depth=1", repo.config.APIEndpoint(), spaceGUID, url.QueryEscape("name:"+name)) appResources := new(resources.PaginatedApplicationResources) apiErr = repo.gateway.GetResource(path, appResources) if apiErr != nil { return } if len(appResources.Resources) == 0 { apiErr = errors.NewModelNotFoundError("App", name) return } res := appResources.Resources[0] app = res.ToModel() return }
func (repo CloudControllerServiceBrokerRepository) FindByName(name string) (serviceBroker models.ServiceBroker, apiErr error) { foundBroker := false apiErr = repo.gateway.ListPaginatedResources( repo.config.APIEndpoint(), fmt.Sprintf("/v2/service_brokers?q=%s", url.QueryEscape("name:"+name)), resources.ServiceBrokerResource{}, func(resource interface{}) bool { serviceBroker = resource.(resources.ServiceBrokerResource).ToFields() foundBroker = true return false }) if !foundBroker && (apiErr == nil) { apiErr = errors.NewModelNotFoundError("Service Broker", name) } return }
func (repo CloudControllerSpaceRepository) FindByNameInOrg(name, orgGUID string) (space models.Space, apiErr error) { foundSpace := false apiErr = repo.gateway.ListPaginatedResources( repo.config.APIEndpoint(), fmt.Sprintf("/v2/organizations/%s/spaces?q=%s&inline-relations-depth=1", orgGUID, url.QueryEscape("name:"+strings.ToLower(name))), resources.SpaceResource{}, func(resource interface{}) bool { space = resource.(resources.SpaceResource).ToModel() foundSpace = true return false }) if !foundSpace { apiErr = errors.NewModelNotFoundError("Space", name) } return }
func (repo CloudControllerOrganizationRepository) FindByName(name string) (org models.Organization, apiErr error) { found := false apiErr = repo.gateway.ListPaginatedResources( repo.config.APIEndpoint(), fmt.Sprintf("/v2/organizations?q=%s&inline-relations-depth=1", url.QueryEscape("name:"+strings.ToLower(name))), resources.OrganizationResource{}, func(resource interface{}) bool { org = resource.(resources.OrganizationResource).ToModel() found = true return false }) if apiErr == nil && !found { apiErr = errors.NewModelNotFoundError("Organization", name) } return }
func (repo CloudControllerServiceRepository) FindServicePlanByDescription(planDescription resources.ServicePlanDescription) (string, error) { path := fmt.Sprintf("/v2/services?inline-relations-depth=1&q=%s", url.QueryEscape("label:"+planDescription.ServiceLabel+";provider:"+planDescription.ServiceProvider)) offerings, err := repo.getServiceOfferings(path) if err != nil { return "", err } for _, serviceOfferingResource := range offerings { for _, servicePlanResource := range serviceOfferingResource.Plans { if servicePlanResource.Name == planDescription.ServicePlanName { return servicePlanResource.GUID, nil } } } return "", errors.NewModelNotFoundError("Plan", planDescription.String()) }
func (repo cloudControllerSecurityGroupRepo) Read(name string) (models.SecurityGroup, error) { path := fmt.Sprintf("/v2/security_groups?q=%s", url.QueryEscape("name:"+name)) group := models.SecurityGroup{} foundGroup := false err := repo.gateway.ListPaginatedResources( repo.config.APIEndpoint(), path, resources.SecurityGroupResource{}, func(resource interface{}) bool { if asgr, ok := resource.(resources.SecurityGroupResource); ok { group = asgr.ToModel() foundGroup = true } return false }, ) if err != nil { return group, err } if !foundGroup { return group, errors.NewModelNotFoundError("security group", name) } err = repo.gateway.ListPaginatedResources( repo.config.APIEndpoint(), group.SpaceURL+"?inline-relations-depth=1", resources.SpaceResource{}, func(resource interface{}) bool { if asgr, ok := resource.(resources.SpaceResource); ok { group.Spaces = append(group.Spaces, asgr.ToModel()) return true } return false }, ) return group, err }
}) }) It("does not prompt when the -f flag is given", func() { ui.Inputs = []string{} runCommand("-f", "org-to-delete") Expect(ui.Outputs()).To(ContainSubstrings( []string{"Deleting", "org-to-delete"}, []string{"OK"}, )) Expect(orgRepo.DeleteArgsForCall(0)).To(Equal("org-to-delete-guid")) }) It("warns the user when the org does not exist", func() { orgRepo.FindByNameReturns(models.Organization{}, errors.NewModelNotFoundError("Organization", "org org-to-delete does not exist")) runCommand("org-to-delete") Expect(orgRepo.DeleteCallCount()).To(Equal(0)) Expect(ui.Outputs()).To(ContainSubstrings( []string{"Deleting", "org-to-delete"}, []string{"OK"}, )) Expect(ui.WarnOutputs).To(ContainSubstrings([]string{"org-to-delete", "does not exist."})) }) }) })
ui.Inputs = []string{} runCommand("-f", "a label", "a provider") Expect(ui.Prompts).To(BeEmpty()) Expect(ui.Outputs()).To(ContainSubstrings( []string{"Deleting"}, []string{"OK"}, )) Expect(authTokenRepo.DeletedServiceAuthTokenFields.GUID).To(Equal("the-guid")) }) }) Context("when the service auth token does not exist", func() { BeforeEach(func() { authTokenRepo.FindByLabelAndProviderAPIResponse = errors.NewModelNotFoundError("Service Auth Token", "") }) It("warns the user when the specified service auth token does not exist", func() { runCommand("a label", "a provider") Expect(ui.Outputs()).To(ContainSubstrings( []string{"Deleting service auth token as", "my-user"}, []string{"OK"}, )) Expect(ui.WarnOutputs).To(ContainSubstrings([]string{"does not exist"})) }) }) Context("when there is an error deleting the service auth token", func() {
Context("when finding the group returns an error", func() { BeforeEach(func() { securityGroupRepo.ReadReturns(models.SecurityGroup{}, errors.New("pbbbbbbbbbbt")) }) It("fails and tells the user", func() { runCommand("-f", "whoops") Expect(ui.Outputs()).To(ContainSubstrings([]string{"FAILED"})) }) }) Context("when a group with that name does not exist", func() { BeforeEach(func() { securityGroupRepo.ReadReturns(models.SecurityGroup{}, errors.NewModelNotFoundError("Security group", "uh uh uh -- you didn't sahy the magick word")) }) It("fails and tells the user", func() { runCommand("-f", "whoop") Expect(ui.WarnOutputs).To(ContainSubstrings([]string{"whoop", "does not exist"})) }) }) It("fails and warns the user if deleting fails", func() { securityGroupRepo.DeleteReturns(errors.New("raspberry")) runCommand("-f", "whoops") Expect(ui.Outputs()).To(ContainSubstrings([]string{"FAILED"})) })
callTarget([]string{"-s", "my-space"}) Expect(ui.Outputs()).To(ContainSubstrings( []string{"FAILED"}, []string{"Unable to access space", "my-space"}, )) Expect(config.SpaceFields().GUID).To(Equal("")) Expect(ui.ShowConfigurationCalled).To(BeFalse()) Expect(config.OrganizationFields().GUID).NotTo(BeEmpty()) expectSpaceToBeCleared() }) It("fails when the space is not found", func() { spaceRepo.FindByNameReturns(models.Space{}, errors.NewModelNotFoundError("Space", "my-space")) callTarget([]string{"-s", "my-space"}) expectSpaceToBeCleared() Expect(ui.Outputs()).To(ContainSubstrings( []string{"FAILED"}, []string{"my-space", "not found"}, )) }) It("fails to target the space automatically if is not found", func() { orgRepo.ListOrgsReturns([]models.Organization{org}, nil) orgRepo.FindByNameReturns(org, nil) spaceRepo.FindByNameReturns(models.Space{}, errors.NewModelNotFoundError("Space", "my-space"))
It("notifies the user that the migration was successful", func() { serviceRepo.GetServiceInstanceCountForServicePlanReturns(2, nil) testcmd.RunCLICommand("migrate-service-instances", args, requirementsFactory, updateCommandDependency, false, ui) Expect(ui.Outputs()).To(ContainSubstrings( []string{"Attempting to migrate", "2", "service instances"}, []string{"1", "service instance", "migrated"}, []string{"OK"}, )) }) }) Context("when finding the v1 plan fails", func() { Context("because the plan does not exist", func() { BeforeEach(func() { serviceRepo.FindServicePlanByDescriptionReturns("", errors.NewModelNotFoundError("Service Plan", "")) }) It("notifies the user of the failure", func() { testcmd.RunCLICommand("migrate-service-instances", args, requirementsFactory, updateCommandDependency, false, ui) Expect(ui.Outputs()).To(ContainSubstrings( []string{"FAILED"}, []string{"Plan", "v1-service-label", "v1-provider-name", "v1-plan-name", "cannot be found"}, )) }) It("does not display the warning", func() { testcmd.RunCLICommand("migrate-service-instances", args, requirementsFactory, updateCommandDependency, false, ui) Expect(ui.Outputs()).ToNot(ContainSubstrings([]string{"WARNING:", "this operation is to replace a service broker"}))
[]string{"OK"})) }) It("skips to delete service key when '-f' option is not provided and confirmed 'no'", func() { ui.Inputs = append(ui.Inputs, "no") Expect(callDeleteServiceKey([]string{"fake-service-instance", "fake-service-key"})).To(BeTrue()) Expect(ui.Prompts).To(ContainSubstrings([]string{"Really delete the service key", "fake-service-key"})) Expect(ui.Outputs()).To(BeEmpty()) }) }) Context("deletes service key unsuccessful", func() { It("fails to delete service key when service instance does not exist", func() { serviceRepo.FindInstanceByNameReturns(models.ServiceInstance{}, errors.NewModelNotFoundError("Service instance", "non-exist-service-instance")) callDeleteServiceKey([]string{"non-exist-service-instance", "fake-service-key", "-f"}) Expect(ui.Outputs()).To(ContainSubstrings( []string{"Deleting key", "fake-service-key", "for service instance", "non-exist-service-instance", "as", "my-user..."}, []string{"OK"}, []string{"Service instance", "non-exist-service-instance", "does not exist."}, )) }) It("fails to delete service key when the service key repository returns an error", func() { serviceKeyRepo.GetServiceKeyMethod.Error = errors.New("") callDeleteServiceKey([]string{"fake-service-instance", "non-exist-service-key", "-f"}) Expect(ui.Outputs()).To(ContainSubstrings(
Expect(ui.Prompts).NotTo(ContainSubstrings( []string{"Really purge service instance service-instance-name from Cloud Foundry?"}, )) }) It("purges the service instance", func() { cmd.Execute(flagContext) Expect(serviceRepo.PurgeServiceInstanceCallCount()).To(Equal(1)) Expect(serviceRepo.PurgeServiceInstanceArgsForCall(0)).To(Equal(serviceInstance)) }) }) }) Context("when the instance can not be found", func() { BeforeEach(func() { serviceRepo.FindInstanceByNameReturns(models.ServiceInstance{}, cferrors.NewModelNotFoundError("model-type", "model-name")) }) It("prints a warning", func() { cmd.Execute(flagContext) Expect(ui.Outputs()).To(ContainSubstrings( []string{"Service instance service-instance-name not found"}, )) }) }) Context("when an error occurs fetching the instance", func() { var runCLIErr error BeforeEach(func() { serviceRepo.FindInstanceByNameReturns(models.ServiceInstance{}, errors.New("an-error"))
}) It("fails with error", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("find-err")) }) It("does not try to delete the route", func() { Expect(err).To(HaveOccurred()) Expect(routeRepo.DeleteCallCount()).To(BeZero()) }) }) Context("when there is a ModelNotFoundError when finding the route", func() { BeforeEach(func() { routeRepo.FindReturns(models.Route{}, errors.NewModelNotFoundError("model-type", "model-name")) }) It("tells the user that it could not delete the route", func() { Expect(err).NotTo(HaveOccurred()) Expect(ui.Outputs()).To(ContainSubstrings( []string{"Unable to delete, route", "does not exist"}, )) }) It("does not try to delete the route", func() { Expect(err).NotTo(HaveOccurred()) Expect(routeRepo.DeleteCallCount()).To(BeZero()) }) })
domain := models.DomainFields{Name: "example.com", GUID: "domain-guid"} domainRepo := new(apifakes.FakeDomainRepository) domainRepo.FindByNameInOrgReturns(domain, nil) domainReq := NewDomainRequirement("example.com", config, domainRepo) err := domainReq.Execute() Expect(err).NotTo(HaveOccurred()) orgName, orgGUID := domainRepo.FindByNameInOrgArgsForCall(0) Expect(orgName).To(Equal("example.com")) Expect(orgGUID).To(Equal("the-org-guid")) Expect(domainReq.GetDomain()).To(Equal(domain)) }) It("fails when the domain is not found", func() { domainRepo := new(apifakes.FakeDomainRepository) domainRepo.FindByNameInOrgReturns(models.DomainFields{}, errors.NewModelNotFoundError("Domain", "")) domainReq := NewDomainRequirement("example.com", config, domainRepo) err := domainReq.Execute() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Domain")) Expect(err.Error()).To(ContainSubstring("not found")) }) It("fails when an error occurs fetching the domain", func() { domainRepo := new(apifakes.FakeDomainRepository) domainRepo.FindByNameInOrgReturns(models.DomainFields{}, errors.New("an-error")) domainReq := NewDomainRequirement("example.com", config, domainRepo) err := domainReq.Execute() Expect(err).To(HaveOccurred())
requirementsFactory.NewLoginRequirementReturns(requirements.Passing{}) Expect(runCommand("my-craaaaaazy-security-group", "my-org")).To(BeTrue()) }) }) }) }) Context("when the user is logged in and provides the name of a security group", func() { BeforeEach(func() { requirementsFactory.NewLoginRequirementReturns(requirements.Passing{}) }) Context("when a security group with that name does not exist", func() { BeforeEach(func() { fakeSecurityGroupRepo.ReadReturns(models.SecurityGroup{}, errors.NewModelNotFoundError("security group", "my-nonexistent-security-group")) }) It("fails and tells the user", func() { runCommand("my-nonexistent-security-group", "my-org", "my-space") Expect(fakeSecurityGroupRepo.ReadArgsForCall(0)).To(Equal("my-nonexistent-security-group")) Expect(ui.Outputs()).To(ContainSubstrings( []string{"FAILED"}, []string{"security group", "my-nonexistent-security-group", "not found"}, )) }) }) Context("when the org does not exist", func() { BeforeEach(func() {