예제 #1
0
파일: curl.go 프로젝트: pmuellr/cli
func (repo CloudControllerCurlRepository) Request(method, path, headerString, body string) (resHeaders, resBody string, apiResponse net.ApiResponse) {
	url := fmt.Sprintf("%s/%s", repo.config.Target, strings.TrimLeft(path, "/"))

	req, apiResponse := repo.gateway.NewRequest(method, url, repo.config.AccessToken, strings.NewReader(body))
	if apiResponse.IsNotSuccessful() {
		return
	}

	err := mergeHeaders(req.HttpReq.Header, headerString)
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Error parsing headers", err)
		return
	}

	res, apiResponse := repo.gateway.PerformRequestForResponse(req)
	bytes, err := ioutil.ReadAll(res.Body)

	if err != nil {
		apiResponse = net.NewApiResponseWithError("Error reading response", err)
	}
	resBody = string(bytes)

	headerBytes, _ := httputil.DumpResponse(res, false)
	resHeaders = string(headerBytes)

	return
}
예제 #2
0
func (repo CloudControllerApplicationBitsRepository) uploadBits(appGuid string, zipFile *os.File, presentResourcesJson []byte) (apiResponse net.ApiResponse) {
	url := fmt.Sprintf("%s/v2/apps/%s/bits", repo.config.ApiEndpoint(), appGuid)
	fileutils.TempFile("requests", func(requestFile *os.File, err error) {
		if err != nil {
			apiResponse = net.NewApiResponseWithError("Error creating tmp file: %s", err)
			return
		}

		boundary, err := repo.writeUploadBody(zipFile, requestFile, presentResourcesJson)
		if err != nil {
			apiResponse = net.NewApiResponseWithError("Error writing to tmp file: %s", err)
			return
		}

		var request *net.Request
		request, apiResponse = repo.gateway.NewRequest("PUT", url, repo.config.AccessToken(), requestFile)
		if apiResponse.IsNotSuccessful() {
			return
		}

		contentType := fmt.Sprintf("multipart/form-data; boundary=%s", boundary)
		request.HttpReq.Header.Set("Content-Type", contentType)

		response := &Resource{}
		_, apiResponse = repo.gateway.PerformPollingRequestForJSONResponse(request, response, 5*time.Minute)
		if apiResponse.IsNotSuccessful() {
			return
		}
	})

	return
}
예제 #3
0
func (repo CloudControllerBuildpackBitsRepository) UploadBuildpack(buildpack models.Buildpack, buildpackLocation string) (apiResponse net.ApiResponse) {
	fileutils.TempFile("buildpack-upload", func(zipFileToUpload *os.File, err error) {
		if err != nil {
			apiResponse = net.NewApiResponseWithError("Couldn't create temp file for upload", err)
			return
		}

		var buildpackFileName string
		if isWebURL(buildpackLocation) {
			buildpackFileName = path.Base(buildpackLocation)
			downloadBuildpack(buildpackLocation, func(downloadFile *os.File, downloadErr error) {
				if downloadErr != nil {
					err = downloadErr
					return
				}

				err = normalizeBuildpackArchive(downloadFile, zipFileToUpload)
			})
		} else {
			buildpackFileName = filepath.Base(buildpackLocation)

			stats, err := os.Stat(buildpackLocation)
			if err != nil {
				apiResponse = net.NewApiResponseWithError("Error opening buildpack file", err)
				return
			}

			if stats.IsDir() {
				err = repo.zipper.Zip(buildpackLocation, zipFileToUpload)
			} else {
				specifiedFile, err := os.Open(buildpackLocation)
				if err != nil {
					apiResponse = net.NewApiResponseWithError("Couldn't open buildpack file", err)
					return
				}
				err = normalizeBuildpackArchive(specifiedFile, zipFileToUpload)
			}
		}

		if err != nil {
			apiResponse = net.NewApiResponseWithError("Couldn't write zip file", err)
			return
		}

		apiResponse = repo.uploadBits(buildpack, zipFileToUpload, buildpackFileName)
	})

	return
}
예제 #4
0
func (repo CloudControllerApplicationBitsRepository) UploadApp(appGuid string, appDir string, cb func(path string, zipSize, fileCount uint64)) (apiResponse net.ApiResponse) {
	fileutils.TempDir("apps", func(uploadDir string, err error) {
		if err != nil {
			apiResponse = net.NewApiResponseWithMessage(err.Error())
			return
		}

		var presentResourcesJson []byte
		repo.sourceDir(appDir, func(sourceDir string, sourceErr error) {
			if sourceErr != nil {
				err = sourceErr
				return
			}
			presentResourcesJson, err = repo.copyUploadableFiles(sourceDir, uploadDir)
		})

		if err != nil {
			apiResponse = net.NewApiResponseWithMessage("%s", err)
			return
		}

		fileutils.TempFile("uploads", func(zipFile *os.File, err error) {
			if err != nil {
				apiResponse = net.NewApiResponseWithMessage("%s", err.Error())
				return
			}

			err = repo.zipper.Zip(uploadDir, zipFile)
			if err != nil {
				apiResponse = net.NewApiResponseWithError("Error zipping application", err)
				return
			}

			stat, err := zipFile.Stat()
			if err != nil {
				apiResponse = net.NewApiResponseWithError("Error zipping application", err)
				return
			}
			cb(appDir, uint64(stat.Size()), cf.CountFiles(uploadDir))

			apiResponse = repo.uploadBits(appGuid, zipFile, presentResourcesJson)
			if apiResponse.IsNotSuccessful() {
				return
			}
		})
	})
	return
}
예제 #5
0
func (repo CloudControllerBuildpackBitsRepository) uploadBits(buildpack cf.Buildpack, zipFile *os.File) (apiResponse net.ApiResponse) {
	url := fmt.Sprintf("%s/v2/buildpacks/%s/bits", repo.config.Target, buildpack.Guid)

	fileutils.TempFile("requests", func(requestFile *os.File, err error) {
		if err != nil {
			apiResponse = net.NewApiResponseWithMessage(err.Error())
			return
		}

		boundary, err := repo.writeUploadBody(zipFile, requestFile)
		if err != nil {
			apiResponse = net.NewApiResponseWithError("Error creating upload", err)
			return
		}

		request, apiResponse := repo.gateway.NewRequest("PUT", url, repo.config.AccessToken, requestFile)
		contentType := fmt.Sprintf("multipart/form-data; boundary=%s", boundary)
		request.HttpReq.Header.Set("Content-Type", contentType)
		if apiResponse.IsNotSuccessful() {
			return
		}

		apiResponse = repo.gateway.PerformRequest(request)
	})

	return
}
예제 #6
0
func (repo CloudControllerApplicationBitsRepository) getFilesToUpload(allAppFiles []models.AppFileFields) (appFilesToUpload []models.AppFileFields, presentResourcesJson []byte, apiResponse net.ApiResponse) {
	appFilesRequest := []AppFileResource{}
	for _, file := range allAppFiles {
		appFilesRequest = append(appFilesRequest, AppFileResource{
			Path: file.Path,
			Sha1: file.Sha1,
			Size: file.Size,
		})
	}

	allAppFilesJson, err := json.Marshal(appFilesRequest)
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Failed to create json for resource_match request", err)
		return
	}

	path := fmt.Sprintf("%s/v2/resource_match", repo.config.ApiEndpoint())
	req, apiResponse := repo.gateway.NewRequest("PUT", path, repo.config.AccessToken(), bytes.NewReader(allAppFilesJson))
	if apiResponse.IsNotSuccessful() {
		return
	}

	presentResourcesJson, _, apiResponse = repo.gateway.PerformRequestForResponseBytes(req)

	fileResource := []AppFileResource{}
	err = json.Unmarshal(presentResourcesJson, &fileResource)

	if err != nil {
		apiResponse = net.NewApiResponseWithError("Failed to unmarshal json response from resource_match request", err)
		return
	}

	appFilesToUpload = make([]models.AppFileFields, len(allAppFiles))
	copy(appFilesToUpload, allAppFiles)
	for _, file := range fileResource {
		appFile := models.AppFileFields{
			Path: file.Path,
			Sha1: file.Sha1,
			Size: file.Size,
		}
		appFilesToUpload = repo.deleteAppFile(appFilesToUpload, appFile)
	}

	return
}
예제 #7
0
파일: login.go 프로젝트: nsnt/cli
func (cmd Login) setOrganization(c *cli.Context, userChanged bool) (apiResponse net.ApiResponse) {
	orgName := c.String("o")

	if orgName == "" {
		// If the user is changing, clear out the org
		if userChanged {
			err := cmd.configRepo.SetOrganization(cf.OrganizationFields{})
			if err != nil {
				apiResponse = net.NewApiResponseWithError("%s", err)
				return
			}
		}

		// Reuse org in config
		if cmd.config.HasOrganization() && !userChanged {
			return
		}

		stopChan := make(chan bool)
		defer close(stopChan)

		orgsChan, statusChan := cmd.orgRepo.ListOrgs(stopChan)

		availableOrgs := []cf.Organization{}

		for orgs := range orgsChan {
			availableOrgs = append(availableOrgs, orgs...)
			if len(availableOrgs) > maxChoices {
				stopChan <- true
				break
			}
		}

		apiResponse = <-statusChan
		if apiResponse.IsNotSuccessful() {
			cmd.ui.Failed("Error finding avilable orgs\n%s", apiResponse.Message)
			return
		}

		// Target only org if possible
		if len(availableOrgs) == 1 {
			return cmd.targetOrganization(availableOrgs[0])
		}

		orgName = cmd.promptForOrgName(availableOrgs)
	}

	// Find org
	org, apiResponse := cmd.orgRepo.FindByName(orgName)
	if apiResponse.IsNotSuccessful() {
		cmd.ui.Failed("Error finding org %s\n%s", terminal.EntityNameColor(orgName), apiResponse.Message)
		return
	}

	return cmd.targetOrganization(org)
}
예제 #8
0
파일: login.go 프로젝트: nsnt/cli
func (cmd Login) setSpace(c *cli.Context, userChanged bool) (apiResponse net.ApiResponse) {
	spaceName := c.String("s")

	if spaceName == "" {
		// If user is changing, clear the space
		if userChanged {
			err := cmd.configRepo.SetSpace(cf.SpaceFields{})
			if err != nil {
				apiResponse = net.NewApiResponseWithError("%s", err)
				return
			}
		}
		// Reuse space in config
		if cmd.config.HasSpace() && !userChanged {
			return
		}

		stopChan := make(chan bool)
		defer close(stopChan)

		spacesChan, statusChan := cmd.spaceRepo.ListSpaces(stopChan)

		var availableSpaces []cf.Space

		for spaces := range spacesChan {
			availableSpaces = append(availableSpaces, spaces...)
			if len(availableSpaces) > maxChoices {
				stopChan <- true
				break
			}
		}

		apiResponse = <-statusChan
		if apiResponse.IsNotSuccessful() {
			cmd.ui.Failed("Error finding avilable spaces\n%s", apiResponse.Message)
			return
		}

		// Target only space if possible
		if len(availableSpaces) == 1 {
			return cmd.targetSpace(availableSpaces[0])
		}

		spaceName = cmd.promptForSpaceName(availableSpaces)
	}

	// Find space
	space, apiResponse := cmd.spaceRepo.FindByName(spaceName)
	if apiResponse.IsNotSuccessful() {
		cmd.ui.Failed("Error finding space %s\n%s", terminal.EntityNameColor(spaceName), apiResponse.Message)
		return
	}

	return cmd.targetSpace(space)
}
예제 #9
0
func TestMapDomainMappingFails(t *testing.T) {
	reqFactory, domainRepo := getDomainMapperDeps()
	domainRepo.MapApiResponse = net.NewApiResponseWithError("Did not work %s", errors.New("bummer"))

	ui := callDomainMapper(t, true, []string{"my-space", "foo.com"}, reqFactory, domainRepo)

	assert.Equal(t, len(ui.Outputs), 3)
	testassert.SliceContains(t, ui.Outputs, testassert.Lines{
		{"Mapping domain", "foo.com", "my-space"},
		{"FAILED"},
		{"Did not work", "bummer"},
	})
}
func (repo CCUserProvidedServiceInstanceRepository) Update(serviceInstance cf.ServiceInstance) (apiResponse net.ApiResponse) {
	path := fmt.Sprintf("%s/v2/user_provided_service_instances/%s", repo.config.Target, serviceInstance.Guid)

	type RequestBody struct {
		Credentials    map[string]string `json:"credentials,omitempty"`
		SysLogDrainUrl string            `json:"syslog_drain_url,omitempty"`
	}

	reqBody := RequestBody{serviceInstance.Params, serviceInstance.SysLogDrainUrl}
	jsonBytes, err := json.Marshal(reqBody)
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Error parsing response", err)
		return
	}

	return repo.gateway.UpdateResource(path, repo.config.AccessToken, bytes.NewReader(jsonBytes))
}
예제 #11
0
func (repo CloudControllerApplicationRepository) Update(appGuid string, params models.AppParams) (updatedApp models.Application, apiResponse net.ApiResponse) {
	data, err := repo.formatAppJSON(params)
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Failed to marshal JSON", err)
		return
	}

	path := fmt.Sprintf("%s/v2/apps/%s?inline-relations-depth=1", repo.config.ApiEndpoint(), appGuid)
	resource := new(ApplicationResource)
	apiResponse = repo.gateway.UpdateResourceForResponse(path, repo.config.AccessToken(), strings.NewReader(data), resource)
	if apiResponse.IsNotSuccessful() {
		return
	}

	updatedApp = resource.ToModel()
	return
}
예제 #12
0
func (repo CloudControllerBuildpackBitsRepository) UploadBuildpack(buildpack cf.Buildpack, dir string) (apiResponse net.ApiResponse) {
	fileutils.TempFile("buildpack", func(zipFile *os.File, err error) {
		if err != nil {
			apiResponse = net.NewApiResponseWithMessage(err.Error())
			return
		}
		err = repo.zipper.Zip(dir, zipFile)
		if err != nil {
			apiResponse = net.NewApiResponseWithError("Invalid buildpack", err)
			return
		}
		apiResponse = repo.uploadBits(buildpack, zipFile)
		if apiResponse.IsNotSuccessful() {
			return
		}
	})
	return
}
예제 #13
0
func (repo CloudControllerApplicationRepository) SetEnv(app cf.Application, envVars map[string]string) (apiResponse net.ApiResponse) {
	path := fmt.Sprintf("%s/v2/apps/%s", repo.config.Target, app.Guid)

	type setEnvReqBody struct {
		EnvJson map[string]string `json:"environment_json"`
	}

	body := setEnvReqBody{EnvJson: envVars}

	jsonBytes, err := json.Marshal(body)
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Error creating json", err)
		return
	}

	apiResponse = repo.gateway.UpdateResource(path, repo.config.AccessToken, bytes.NewReader(jsonBytes))
	return
}
예제 #14
0
파일: buildpacks.go 프로젝트: nsnt/cli
func (repo CloudControllerBuildpackRepository) Create(name string, position *int, enabled *bool) (createdBuildpack cf.Buildpack, apiResponse net.ApiResponse) {
	path := repo.config.Target + buildpacks_path
	entity := BuildpackEntity{Name: name, Position: position, Enabled: enabled}
	body, err := json.Marshal(entity)
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Could not serialize information", err)
		return
	}

	resource := new(BuildpackResource)
	apiResponse = repo.gateway.CreateResourceForResponse(path, repo.config.AccessToken, bytes.NewReader(body), resource)
	if apiResponse.IsNotSuccessful() {
		return
	}

	createdBuildpack = unmarshallBuildpack(*resource)
	return
}
예제 #15
0
파일: buildpacks.go 프로젝트: nsnt/cli
func (repo CloudControllerBuildpackRepository) Update(buildpack cf.Buildpack) (updatedBuildpack cf.Buildpack, apiResponse net.ApiResponse) {
	path := fmt.Sprintf("%s%s/%s", repo.config.Target, buildpacks_path, buildpack.Guid)

	entity := BuildpackEntity{buildpack.Name, buildpack.Position, buildpack.Enabled, "", ""}
	body, err := json.Marshal(entity)
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Could not serialize updates.", err)
		return
	}

	resource := new(BuildpackResource)
	apiResponse = repo.gateway.UpdateResourceForResponse(path, repo.config.AccessToken, bytes.NewReader(body), resource)
	if apiResponse.IsNotSuccessful() {
		return
	}

	updatedBuildpack = unmarshallBuildpack(*resource)
	return
}
예제 #16
0
func (repo CloudControllerApplicationRepository) startOrStopApp(app cf.Application, updates map[string]interface{}) (updatedApp cf.Application, apiResponse net.ApiResponse) {
	path := fmt.Sprintf("%s/v2/apps/%s?inline-relations-depth=2", repo.config.Target, app.Guid)

	updates["console"] = true

	body, err := json.Marshal(updates)
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Could not serialize app updates.", err)
		return
	}

	resource := new(ApplicationResource)
	apiResponse = repo.gateway.UpdateResourceForResponse(path, repo.config.AccessToken, bytes.NewReader(body), resource)
	if apiResponse.IsNotSuccessful() {
		return
	}

	updatedApp = repo.appFromResource(*resource)
	return
}
예제 #17
0
func (repo CloudControllerApplicationRepository) Scale(app cf.Application) (apiResponse net.ApiResponse) {
	values := map[string]interface{}{}
	if app.DiskQuota > 0 {
		values["disk_quota"] = app.DiskQuota
	}
	if app.Instances > 0 {
		values["instances"] = app.Instances
	}
	if app.Memory > 0 {
		values["memory"] = app.Memory
	}

	bodyBytes, err := json.Marshal(values)
	if err != nil {
		return net.NewApiResponseWithError("Error generating body", err)
	}

	apiResponse = repo.updateApp(app, bytes.NewReader(bodyBytes))
	return
}
예제 #18
0
func (repo CloudControllerApplicationBitsRepository) UploadApp(app cf.Application, appDir string) (apiResponse net.ApiResponse) {
	fileutils.TempDir("apps", func(uploadDir string, err error) {
		if err != nil {
			apiResponse = net.NewApiResponseWithMessage(err.Error())
			return
		}

		var resourcesJson []byte
		repo.sourceDir(appDir, func(sourceDir string, sourceErr error) {
			if sourceErr != nil {
				err = sourceErr
				return
			}
			resourcesJson, err = repo.copyUploadableFiles(sourceDir, uploadDir)
		})

		if err != nil {
			apiResponse = net.NewApiResponseWithMessage(err.Error())
			return
		}

		fileutils.TempFile("uploads", func(zipFile *os.File, err error) {
			if err != nil {
				apiResponse = net.NewApiResponseWithMessage(err.Error())
				return
			}

			err = repo.zipper.Zip(uploadDir, zipFile)
			if err != nil {
				apiResponse = net.NewApiResponseWithError("Error zipping application", err)
				return
			}

			apiResponse = repo.uploadBits(app, zipFile, resourcesJson)
			if apiResponse.IsNotSuccessful() {
				return
			}
		})
	})
	return
}
예제 #19
0
파일: authentication.go 프로젝트: nsnt/cli
func (uaa UAAAuthenticationRepository) getAuthToken(data url.Values) (apiResponse net.ApiResponse) {
	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.AuthorizationEndpoint)
	request, apiResponse := uaa.gateway.NewRequest("POST", path, "Basic "+base64.StdEncoding.EncodeToString([]byte("cf:")), strings.NewReader(data.Encode()))
	if apiResponse.IsNotSuccessful() {
		return
	}
	request.HttpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	response := new(AuthenticationResponse)
	_, apiResponse = uaa.gateway.PerformRequestForJSONResponse(request, &response)

	if apiResponse.IsNotSuccessful() {
		return
	}

	if response.Error.Code != "" {
		apiResponse = net.NewApiResponseWithMessage("Authentication Server error: %s", response.Error.Description)
		return
	}

	uaa.config.AccessToken = fmt.Sprintf("%s %s", response.TokenType, response.AccessToken)
	uaa.config.RefreshToken = response.RefreshToken
	err := uaa.configRepo.Save()
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Error setting configuration", err)
	}

	return
}
예제 #20
0
func (repo CloudControllerApplicationBitsRepository) getFilesToUpload(allAppFiles []cf.AppFile) (appFilesToUpload []cf.AppFile, resourcesJson []byte, apiResponse net.ApiResponse) {
	appFilesRequest := []AppFileResource{}
	for _, file := range allAppFiles {
		appFilesRequest = append(appFilesRequest, AppFileResource{
			Path: file.Path,
			Sha1: file.Sha1,
			Size: file.Size,
		})
	}

	resourcesJson, err := json.Marshal(appFilesRequest)
	if err != nil {
		apiResponse = net.NewApiResponseWithError("Failed to create json for resource_match request", err)
		return
	}

	path := fmt.Sprintf("%s/v2/resource_match", repo.config.Target)
	req, apiResponse := repo.gateway.NewRequest("PUT", path, repo.config.AccessToken, bytes.NewReader(resourcesJson))
	if apiResponse.IsNotSuccessful() {
		return
	}

	res := []AppFileResource{}
	_, apiResponse = repo.gateway.PerformRequestForJSONResponse(req, &res)

	appFilesToUpload = make([]cf.AppFile, len(allAppFiles))
	copy(appFilesToUpload, allAppFiles)
	for _, file := range res {
		appFile := cf.AppFile{
			Path: file.Path,
			Sha1: file.Sha1,
			Size: file.Size,
		}
		appFilesToUpload = repo.deleteAppFile(appFilesToUpload, appFile)
	}

	return
}
예제 #21
0
func (repo CCUserProvidedServiceInstanceRepository) Create(name, drainUrl string, params map[string]string) (apiResponse net.ApiResponse) {
	path := fmt.Sprintf("%s/v2/user_provided_service_instances", repo.config.Target)

	type RequestBody struct {
		Name           string            `json:"name"`
		Credentials    map[string]string `json:"credentials"`
		SpaceGuid      string            `json:"space_guid"`
		SysLogDrainUrl string            `json:"syslog_drain_url"`
	}

	jsonBytes, err := json.Marshal(RequestBody{
		Name:           name,
		Credentials:    params,
		SpaceGuid:      repo.config.SpaceFields.Guid,
		SysLogDrainUrl: drainUrl,
	})

	if err != nil {
		apiResponse = net.NewApiResponseWithError("Error parsing response", err)
		return
	}

	return repo.gateway.CreateResource(path, repo.config.AccessToken, bytes.NewReader(jsonBytes))
}
예제 #22
0
func (repo CloudControllerBuildpackBitsRepository) performMultiPartUpload(url string, fieldName string, fileName string, body io.Reader) (apiResponse net.ApiResponse) {
	fileutils.TempFile("requests", func(requestFile *os.File, err error) {
		if err != nil {
			apiResponse = net.NewApiResponseWithMessage(err.Error())
			return
		}

		writer := multipart.NewWriter(requestFile)
		part, err := writer.CreateFormFile(fieldName, fileName)

		if err != nil {
			writer.Close()
			return
		}

		_, err = io.Copy(part, body)
		writer.Close()

		if err != nil {
			apiResponse = net.NewApiResponseWithError("Error creating upload", err)
			return
		}

		var request *net.Request
		request, apiResponse = repo.gateway.NewRequest("PUT", url, repo.config.AccessToken(), requestFile)
		contentType := fmt.Sprintf("multipart/form-data; boundary=%s", writer.Boundary())
		request.HttpReq.Header.Set("Content-Type", contentType)
		if apiResponse.IsNotSuccessful() {
			return
		}

		apiResponse = repo.gateway.PerformRequest(request)
	})

	return
}
예제 #23
0
			Expect(ccHandler.AllRequestsCalled()).To(BeTrue())
			Expect(apiResponse.StatusCode).To(Equal(http.StatusGatewayTimeout))
		})

		It("returns an error when the UAA endpoint cannot be determined", func() {
			ccReqs, _ := createUsersByRoleEndpoints("/v2/organizations/my-org-guid/managers")

			ts, _ := testnet.NewTLSServer(ccReqs)
			defer ts.Close()
			configRepo := testconfig.NewRepositoryWithDefaults()
			configRepo.SetApiEndpoint(ts.URL)

			ccGateway := net.NewCloudControllerGateway()
			uaaGateway := net.NewUAAGateway()
			endpointRepo := &testapi.FakeEndpointRepo{}
			endpointRepo.UAAEndpointReturns.ApiResponse = net.NewApiResponseWithError("Failed to get endpoint!", errors.New("Failed!"))

			repo := NewCloudControllerUserRepository(configRepo, uaaGateway, ccGateway, endpointRepo)

			_, apiResponse := repo.ListUsersInOrgForRole("my-org-guid", models.ORG_MANAGER)

			Expect(apiResponse).To(Equal(endpointRepo.UAAEndpointReturns.ApiResponse))
		})
	})

	It("TestFindByUsername", func() {
		usersResponse := `{ "resources": [{ "id": "my-guid", "userName": "******" }]}`
		uaaReq := testapi.NewCloudControllerTestRequest(testnet.TestRequest{
			Method:   "GET",
			Path:     "/Users?attributes=id,userName&filter=userName+Eq+%22damien%2Buser1%40pivotallabs.com%22",
			Response: testnet.TestResponse{Status: http.StatusOK, Body: usersResponse},
		deps.serviceRepo.FindServiceOfferingByLabelAndProviderServiceOffering = offering

		testcmd.RunCommand(
			NewPurgeServiceOffering(deps.ui, deps.config, deps.serviceRepo),
			testcmd.NewContext("purge-service-offering", []string{"-f", "the-service-name"}),
			deps.reqFactory,
		)

		Expect(len(deps.ui.Prompts)).To(Equal(0))
		Expect(deps.serviceRepo.PurgeServiceOfferingCalled).To(Equal(true))
	})

	It("fails with an error message when the request fails", func() {
		deps := setupDependencies()

		deps.serviceRepo.FindServiceOfferingByLabelAndProviderApiResponse = net.NewApiResponseWithError("oh no!", errors.New("!"))

		testcmd.RunCommand(
			NewPurgeServiceOffering(deps.ui, deps.config, deps.serviceRepo),
			testcmd.NewContext("purge-service-offering", []string{"-f", "-p", "the-provider", "the-service-name"}),
			deps.reqFactory,
		)

		testassert.SliceContains(deps.ui.Outputs, testassert.Lines{
			{"FAILED"},
			{"oh no!"},
		})

		Expect(deps.serviceRepo.PurgeServiceOfferingCalled).To(Equal(false))
	})
예제 #25
0
	It("succeeds when the domain is found", func() {
		domain := models.DomainFields{Name: "example.com", Guid: "domain-guid"}
		domainRepo := &testapi.FakeDomainRepository{FindByNameInOrgDomain: domain}
		domainReq := NewDomainRequirement("example.com", ui, config, domainRepo)
		success := domainReq.Execute()

		Expect(success).To(BeTrue())
		Expect(domainRepo.FindByNameInOrgName).To(Equal("example.com"))
		Expect(domainRepo.FindByNameInOrgGuid).To(Equal("the-org-guid"))
		Expect(domainReq.GetDomain()).To(Equal(domain))
	})

	It("fails when the domain is not found", func() {
		domainRepo := &testapi.FakeDomainRepository{FindByNameInOrgApiResponse: net.NewNotFoundApiResponse("")}
		domainReq := NewDomainRequirement("example.com", ui, config, domainRepo)

		testassert.AssertPanic(testterm.FailedWasCalled, func() {
			domainReq.Execute()
		})
	})

	It("fails when an error occurs fetching the domain", func() {
		domainRepo := &testapi.FakeDomainRepository{FindByNameInOrgApiResponse: net.NewApiResponseWithError("", errors.New(""))}
		domainReq := NewDomainRequirement("example.com", ui, config, domainRepo)

		testassert.AssertPanic(testterm.FailedWasCalled, func() {
			domainReq.Execute()
		})
	})
})