func testScore(t *testing.T, scoreBody string, expectedScore string) { passwordScoreResponse := testhelpers.TestResponse{Status: http.StatusOK, Body: scoreBody} passwordScoreEndpoint := testhelpers.CreateEndpoint( "POST", "/password/score", func(req *http.Request) bool { bodyMatcher := testhelpers.RequestBodyMatcher("password=new-password") contentTypeMatches := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" return contentTypeMatches && bodyMatcher(req) }, passwordScoreResponse, ) scoreServer := httptest.NewTLSServer(http.HandlerFunc(passwordScoreEndpoint)) defer scoreServer.Close() targetServer := createInfoServer(scoreServer.URL) defer targetServer.Close() config := &configuration.Configuration{ AccessToken: "BEARER my_access_token", Target: targetServer.URL, } gateway := net.NewCloudControllerGateway(&testhelpers.FakeAuthenticator{}) repo := NewCloudControllerPasswordRepository(config, gateway) score, err := repo.GetScore("new-password") assert.NoError(t, err) assert.Equal(t, score, expectedScore) }
func TestListEvents(t *testing.T) { listEventsServer := httptest.NewTLSServer(http.HandlerFunc(listEventsEndpoint)) defer listEventsServer.Close() config := &configuration.Configuration{ Target: listEventsServer.URL, AccessToken: "BEARER my_access_token", } repo := NewCloudControllerAppEventsRepository(config, net.NewCloudControllerGateway()) list, apiErr := repo.ListEvents(cf.Application{Guid: "my-app-guid"}) firstExpectedTime, err := time.Parse(APP_EVENT_TIMESTAMP_FORMAT, "2013-10-07T16:51:07+00:00") secondExpectedTime, err := time.Parse(APP_EVENT_TIMESTAMP_FORMAT, "2013-10-07T17:51:07+00:00") expectedEvents := []cf.Event{ { InstanceIndex: 1, ExitStatus: 1, ExitDescription: "app instance exited", Timestamp: firstExpectedTime, }, { InstanceIndex: 2, ExitStatus: 2, ExitDescription: "app instance was stopped", Timestamp: secondExpectedTime, }, } assert.NoError(t, err) assert.True(t, apiErr.IsSuccessful()) assert.Equal(t, list, expectedEvents) }
func TestGetServiceOfferings(t *testing.T) { ts := httptest.NewTLSServer(http.HandlerFunc(multipleOfferingsEndpoint)) defer ts.Close() config := &configuration.Configuration{ AccessToken: "BEARER my_access_token", Target: ts.URL, } gateway := net.NewCloudControllerGateway(&testhelpers.FakeAuthenticator{}) repo := NewCloudControllerServiceRepository(config, gateway) offerings, err := repo.GetServiceOfferings() assert.NoError(t, err) assert.Equal(t, 2, len(offerings)) firstOffering := offerings[0] assert.Equal(t, firstOffering.Label, "Offering 1") assert.Equal(t, firstOffering.Version, "1.0") assert.Equal(t, firstOffering.Description, "Offering 1 description") assert.Equal(t, firstOffering.Provider, "Offering 1 provider") assert.Equal(t, firstOffering.Guid, "offering-1-guid") assert.Equal(t, len(firstOffering.Plans), 2) plan := firstOffering.Plans[0] assert.Equal(t, plan.Name, "Offering 1 Plan 1") assert.Equal(t, plan.Guid, "offering-1-plan-1-guid") secondOffering := offerings[1] assert.Equal(t, secondOffering.Label, "Offering 2") assert.Equal(t, secondOffering.Guid, "offering-2-guid") assert.Equal(t, len(secondOffering.Plans), 1) }
func createInsecureEndpointRepoForUpdate(config configuration.ReadWriter, endpoint func(w http.ResponseWriter, r *http.Request)) (ts *httptest.Server, repo EndpointRepository) { if endpoint != nil { ts = httptest.NewServer(http.HandlerFunc(endpoint)) } gateway := net.NewCloudControllerGateway() return ts, NewEndpointRepository(config, gateway) }
func testUploadApp(dir string, requests []testnet.TestRequest) (app models.Application, apiResponse net.ApiResponse) { ts, handler := testnet.NewTLSServer(requests) defer ts.Close() configRepo := testconfig.NewRepositoryWithDefaults() configRepo.SetApiEndpoint(ts.URL) gateway := net.NewCloudControllerGateway() gateway.PollingThrottle = time.Duration(0) zipper := cf.ApplicationZipper{} repo := NewCloudControllerApplicationBitsRepository(configRepo, gateway, zipper) var ( reportedPath string reportedFileCount, reportedUploadSize uint64 ) apiResponse = repo.UploadApp("my-cool-app-guid", dir, func(path string, uploadSize, fileCount uint64) { reportedPath = path reportedUploadSize = uploadSize reportedFileCount = fileCount }) Expect(reportedPath).To(Equal(dir)) Expect(reportedFileCount).To(Equal(uint64(len(expectedApplicationContent)))) Expect(reportedUploadSize).To(Equal(uint64(759))) Expect(handler.AllRequestsCalled()).To(BeTrue()) return }
func TestListEventsWithNoEvents(t *testing.T) { emptyEventsRequest := testnet.TestRequest{ Method: "GET", Path: "/v2/apps/my-app-guid/events", Response: testnet.TestResponse{ Status: http.StatusOK, Body: `{"resources": []}`}, } listEventsServer, handler := testnet.NewTLSServer(t, []testnet.TestRequest{emptyEventsRequest}) defer listEventsServer.Close() config := &configuration.Configuration{ Target: listEventsServer.URL, AccessToken: "BEARER my_access_token", } repo := NewCloudControllerAppEventsRepository(config, net.NewCloudControllerGateway()) eventChan, apiErr := repo.ListEvents("my-app-guid") _, ok := <-eventChan _, open := <-apiErr assert.False(t, ok) assert.False(t, open) assert.True(t, handler.AllRequestsCalled()) }
func TestCreateApplication(t *testing.T) { ts := httptest.NewTLSServer(http.HandlerFunc(createApplicationEndpoint)) defer ts.Close() config := &configuration.Configuration{ AccessToken: "BEARER my_access_token", Target: ts.URL, Space: cf.Space{Guid: "my-space-guid"}, } gateway := net.NewCloudControllerGateway(&testhelpers.FakeAuthenticator{}) repo := NewCloudControllerApplicationRepository(config, gateway) newApp := cf.Application{ Name: "my-cool-app", Instances: 3, Memory: 2048, BuildpackUrl: "buildpack-url", Stack: cf.Stack{Guid: "some-stack-guid"}, } createdApp, err := repo.Create(newApp) assert.NoError(t, err) assert.Equal(t, createdApp, cf.Application{Name: "my-cool-app", Guid: "my-cool-app-guid"}) }
func TestFindByName(t *testing.T) { ts := httptest.NewTLSServer(http.HandlerFunc(singleAppEndpoint)) defer ts.Close() config := &configuration.Configuration{ AccessToken: "BEARER my_access_token", Target: ts.URL, Space: cf.Space{Name: "my-space", Guid: "my-space-guid"}, } gateway := net.NewCloudControllerGateway(&testhelpers.FakeAuthenticator{}) repo := NewCloudControllerApplicationRepository(config, gateway) app, err := repo.FindByName("App1") assert.NoError(t, err) assert.Equal(t, app.Name, "App1") assert.Equal(t, app.Guid, "app1-guid") assert.Equal(t, app.Memory, 128) assert.Equal(t, app.Instances, 1) assert.Equal(t, app.EnvironmentVars, map[string]string{"foo": "bar", "baz": "boom"}) assert.Equal(t, len(app.Urls), 1) assert.Equal(t, app.Urls[0], "app1.cfapps.io") app, err = repo.FindByName("app that does not exist") assert.Error(t, err) }
func TestRoutesFindAll(t *testing.T) { ts := httptest.NewTLSServer(http.HandlerFunc(findAllEndpoint)) defer ts.Close() config := &configuration.Configuration{ AccessToken: "BEARER my_access_token", Target: ts.URL, } gateway := net.NewCloudControllerGateway(&testhelpers.FakeAuthenticator{}) repo := NewCloudControllerRouteRepository(config, gateway) routes, err := repo.FindAll() assert.NoError(t, err) assert.Equal(t, len(routes), 2) route := routes[0] assert.Equal(t, route.Host, "route-1-host") assert.Equal(t, route.Guid, "route-1-guid") assert.Equal(t, route.Domain.Name, "cfapps.io") assert.Equal(t, route.Domain.Guid, "domain-1-guid") route = routes[1] assert.Equal(t, route.Guid, "route-2-guid") }
func TestSpacesFindAllWithIncorrectToken(t *testing.T) { ts := httptest.NewTLSServer(http.HandlerFunc(multipleSpacesEndpoint)) defer ts.Close() config := &configuration.Configuration{ AccessToken: "BEARER incorrect_access_token", Target: ts.URL, Organization: cf.Organization{Guid: "some-org-guid"}, } gateway := net.NewCloudControllerGateway(&testhelpers.FakeAuthenticator{}) repo := NewCloudControllerSpaceRepository(config, gateway) var ( spaces []cf.Space err error ) // Capture output so debugging info does not show up in test // output testhelpers.CaptureOutput(func() { spaces, err = repo.FindAll() }) assert.Error(t, err) assert.Equal(t, 0, len(spaces)) }
func main() { fileutils.SetTmpPathPrefix("cf") if os.Getenv("CF_COLOR") == "" { os.Setenv("CF_COLOR", "true") } termUI := terminal.NewUI() assignTemplates() configRepo := configuration.NewConfigurationDiskRepository() config := loadConfig(termUI, configRepo) repoLocator := api.NewRepositoryLocator(config, configRepo, map[string]net.Gateway{ "auth": net.NewUAAGateway(), "cloud-controller": net.NewCloudControllerGateway(), "uaa": net.NewUAAGateway(), }) cmdFactory := commands.NewFactory(termUI, config, configRepo, repoLocator) reqFactory := requirements.NewFactory(termUI, config, repoLocator) cmdRunner := commands.NewRunner(cmdFactory, reqFactory) app, err := app.NewApp(cmdRunner) if err != nil { return } app.Run(os.Args) }
func createUsersRepo(t *testing.T, ccReqs []testnet.TestRequest, uaaReqs []testnet.TestRequest) (cc *httptest.Server, ccHandler *testnet.TestHandler, uaa *httptest.Server, uaaHandler *testnet.TestHandler, repo UserRepository) { ccTarget := "" uaaTarget := "" if len(ccReqs) > 0 { cc, ccHandler = testnet.NewTLSServer(t, ccReqs) ccTarget = cc.URL } if len(uaaReqs) > 0 { uaa, uaaHandler = testnet.NewTLSServer(t, uaaReqs) uaaTarget = uaa.URL } config := &configuration.Configuration{ AccessToken: "BEARER my_access_token", Target: ccTarget, Organization: cf.Organization{Guid: "some-org-guid"}, } ccGateway := net.NewCloudControllerGateway() uaaGateway := net.NewUAAGateway() endpointRepo := &testapi.FakeEndpointRepo{GetEndpointEndpoints: map[cf.EndpointType]string{ cf.UaaEndpointKey: uaaTarget, }} repo = NewCloudControllerUserRepository(config, uaaGateway, ccGateway, endpointRepo) return }
func setupDependencies() (deps *cliDependencies) { if os.Getenv("CF_COLOR") == "" { os.Setenv("CF_COLOR", "true") } deps = new(cliDependencies) deps.termUI = terminal.NewUI(os.Stdin) deps.manifestRepo = manifest.NewManifestDiskRepository() deps.configRepo = configuration.NewRepositoryFromFilepath(configuration.DefaultFilePath(), func(err error) { if err != nil { deps.termUI.Failed(fmt.Sprintf("Config error: %s", err)) } }) deps.apiRepoLocator = api.NewRepositoryLocator(deps.configRepo, map[string]net.Gateway{ "auth": net.NewUAAGateway(deps.configRepo), "cloud-controller": net.NewCloudControllerGateway(deps.configRepo), "uaa": net.NewUAAGateway(deps.configRepo), }) return }
func createUsersRepo(t *testing.T, ccReqs []testnet.TestRequest, uaaReqs []testnet.TestRequest) (cc *httptest.Server, ccHandler *testnet.TestHandler, uaa *httptest.Server, uaaHandler *testnet.TestHandler, repo UserRepository) { ccTarget := "" uaaTarget := "" if len(ccReqs) > 0 { cc, ccHandler = testnet.NewTLSServer(t, ccReqs) ccTarget = cc.URL } if len(uaaReqs) > 0 { uaa, uaaHandler = testnet.NewTLSServer(t, uaaReqs) uaaTarget = uaa.URL } org := cf.OrganizationFields{} org.Guid = "some-org-guid" config := &configuration.Configuration{ AccessToken: "BEARER my_access_token", Target: ccTarget, OrganizationFields: org, } ccGateway := net.NewCloudControllerGateway() uaaGateway := net.NewUAAGateway() endpointRepo := &testapi.FakeEndpointRepo{} endpointRepo.UAAEndpointReturns.Endpoint = uaaTarget repo = NewCloudControllerUserRepository(config, uaaGateway, ccGateway, endpointRepo) return }
func testUploadApp(t *testing.T, dir string, requests []testnet.TestRequest) (app cf.Application, apiResponse net.ApiResponse) { ts, handler := testnet.NewTLSServer(t, requests) defer ts.Close() config := &configuration.Configuration{ AccessToken: "BEARER my_access_token", Target: ts.URL, } gateway := net.NewCloudControllerGateway() gateway.PollingThrottle = time.Duration(0) zipper := cf.ApplicationZipper{} repo := NewCloudControllerApplicationBitsRepository(config, gateway, zipper) var reportedFileCount, reportedUploadSize uint64 apiResponse = repo.UploadApp("my-cool-app-guid", dir, func(uploadSize, fileCount uint64) { reportedUploadSize = uploadSize reportedFileCount = fileCount }) assert.Equal(t, reportedFileCount, uint64(len(expectedApplicationContent))) assert.Equal(t, reportedUploadSize, uint64(759)) assert.True(t, handler.AllRequestsCalled()) return }
func main() { defer func() { maybeSomething := recover() if maybeSomething != nil { displayCrashDialog() } }() fileutils.SetTmpPathPrefix("cf") if os.Getenv("CF_COLOR") == "" { os.Setenv("CF_COLOR", "true") } termUI := terminal.NewUI() configRepo := configuration.NewConfigurationDiskRepository() config := loadConfig(termUI, configRepo) manifestRepo := manifest.NewManifestDiskRepository() repoLocator := api.NewRepositoryLocator(config, configRepo, map[string]net.Gateway{ "auth": net.NewUAAGateway(), "cloud-controller": net.NewCloudControllerGateway(), "uaa": net.NewUAAGateway(), }) cmdFactory := commands.NewFactory(termUI, config, configRepo, manifestRepo, repoLocator) reqFactory := requirements.NewFactory(termUI, config, repoLocator) cmdRunner := commands.NewRunner(cmdFactory, reqFactory) app, err := app.NewApp(cmdRunner) if err != nil { return } app.Run(os.Args) }
func newCurlDependencies() (deps curlDependencies) { deps.config = &configuration.Configuration{ AccessToken: "BEARER my_access_token", } deps.gateway = net.NewCloudControllerGateway() return }
func createUserProvidedServiceInstanceRepo(req testnet.TestRequest) (ts *httptest.Server, handler *testnet.TestHandler, repo UserProvidedServiceInstanceRepository) { ts, handler = testnet.NewServer([]testnet.TestRequest{req}) configRepo := testconfig.NewRepositoryWithDefaults() configRepo.SetApiEndpoint(ts.URL) gateway := net.NewCloudControllerGateway(configRepo) repo = NewCCUserProvidedServiceInstanceRepository(configRepo, gateway) return }
func createServiceRepoWithConfig(reqs []testnet.TestRequest, config configuration.ReadWriter) (testServer *httptest.Server, handler *testnet.TestHandler, repo ServiceRepository) { testServer, handler = testnet.NewServer(reqs) config.SetApiEndpoint(testServer.URL) gateway := net.NewCloudControllerGateway(config) repo = NewCloudControllerServiceRepository(config, gateway) return }
func createServiceAuthTokenRepo(request testnet.TestRequest) (ts *httptest.Server, handler *testnet.TestHandler, repo ServiceAuthTokenRepository) { ts, handler = testnet.NewTLSServer([]testnet.TestRequest{request}) configRepo := testconfig.NewRepositoryWithDefaults() configRepo.SetApiEndpoint(ts.URL) gateway := net.NewCloudControllerGateway() repo = NewCloudControllerServiceAuthTokenRepository(configRepo, gateway) return }
func createBuildpackRepo(requests ...testnet.TestRequest) (ts *httptest.Server, handler *testnet.TestHandler, repo BuildpackRepository) { ts, handler = testnet.NewTLSServer(requests) config := testconfig.NewRepositoryWithDefaults() config.SetApiEndpoint(ts.URL) gateway := net.NewCloudControllerGateway() repo = NewCloudControllerBuildpackRepository(config, gateway) return }
func createSpacesRepo(reqs ...testnet.TestRequest) (ts *httptest.Server, handler *testnet.TestHandler, repo SpaceRepository) { ts, handler = testnet.NewServer(reqs) configRepo := testconfig.NewRepositoryWithDefaults() configRepo.SetApiEndpoint(ts.URL) gateway := net.NewCloudControllerGateway(configRepo) repo = NewCloudControllerSpaceRepository(configRepo, gateway) return }
func createAppSummaryRepo(requests []testnet.TestRequest) (ts *httptest.Server, handler *testnet.TestHandler, repo AppSummaryRepository) { ts, handler = testnet.NewTLSServer(requests) configRepo := testconfig.NewRepositoryWithDefaults() configRepo.SetApiEndpoint(ts.URL) gateway := net.NewCloudControllerGateway() repo = NewCloudControllerAppSummaryRepository(configRepo, gateway) return }
func createDomainRepo(reqs []testnet.TestRequest) (ts *httptest.Server, handler *testnet.TestHandler, repo DomainRepository) { ts, handler = testnet.NewServer(reqs) config := testconfig.NewRepositoryWithDefaults() config.SetApiEndpoint(ts.URL) gateway := net.NewCloudControllerGateway() repo = NewCloudControllerDomainRepository(config, gateway) return }
func createPasswordRepo(req testnet.TestRequest) (passwordServer *httptest.Server, handler *testnet.TestHandler, repo PasswordRepository) { passwordServer, handler = testnet.NewServer([]testnet.TestRequest{req}) configRepo := testconfig.NewRepositoryWithDefaults() configRepo.SetUaaEndpoint(passwordServer.URL) gateway := net.NewCloudControllerGateway(configRepo) repo = NewCloudControllerPasswordRepository(configRepo, gateway) return }
func callApi(args []string, configRepo configuration.ConfigurationRepository) (ui *testhelpers.FakeUI) { ui = new(testhelpers.FakeUI) gateway := net.NewCloudControllerGateway(nil) cmd := NewApi(ui, gateway, configRepo) ctxt := testhelpers.NewContext("api", args) reqFactory := &testhelpers.FakeReqFactory{} testhelpers.RunCommand(cmd, ctxt, reqFactory) return }
func createOrganizationRepo(reqs ...testnet.TestRequest) (testserver *httptest.Server, handler *testnet.TestHandler, repo OrganizationRepository) { testserver, handler = testnet.NewServer(reqs) configRepo := testconfig.NewRepositoryWithDefaults() configRepo.SetApiEndpoint(testserver.URL) gateway := net.NewCloudControllerGateway(configRepo) repo = NewCloudControllerOrganizationRepository(configRepo, gateway) return }
func TestTailsLogsFor(t *testing.T) { expectedMessage := messagetesthelpers.MarshalledLogMessage(t, "My message", "my-app-id") websocketEndpoint := func(conn *websocket.Conn) { conn.Write(expectedMessage) conn.Close() } websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint)) defer websocketServer.Close() var redirectEndpoint = func(writer http.ResponseWriter, request *http.Request) { assert.Equal(t, request.URL.Path, "/tail/") assert.Equal(t, request.URL.RawQuery, "app=my-app-guid") assert.Equal(t, request.Method, "GET") assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token") writer.Header().Set("Location", strings.Replace(websocketServer.URL, "https", "wss", 1)) writer.WriteHeader(http.StatusFound) } http.HandleFunc("/", redirectEndpoint) go http.ListenAndServe(":"+LOGGREGATOR_REDIRECTOR_PORT, nil) redirectServer := httptest.NewTLSServer(http.HandlerFunc(redirectEndpoint)) defer redirectServer.Close() gateway := net.NewCloudControllerGateway(&testhelpers.FakeAuthenticator{}) app := cf.Application{Name: "my-app", Guid: "my-app-guid"} config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "http://localhost"} loggregatorHostResolver := func(hostname string) string { return hostname } logsRepo := NewLoggregatorLogsRepository(config, gateway, loggregatorHostResolver) connected := false onConnect := func() { connected = true } tailedMessages := []*logmessage.LogMessage{} onMessage := func(message *logmessage.LogMessage) { tailedMessages = append(tailedMessages, message) } logsRepo.TailLogsFor(app, onConnect, onMessage) assert.Equal(t, len(tailedMessages), 1) actualMessage, err := proto.Marshal(tailedMessages[0]) assert.NoError(t, err) assert.Equal(t, actualMessage, expectedMessage) assert.True(t, connected) }
func createPasswordRepo(req testnet.TestRequest) (passwordServer *httptest.Server, handler *testnet.TestHandler, repo PasswordRepository) { passwordServer, handler = testnet.NewTLSServer([]testnet.TestRequest{req}) endpointRepo := &testapi.FakeEndpointRepo{} endpointRepo.UAAEndpointReturns.Endpoint = passwordServer.URL configRepo := testconfig.NewRepositoryWithDefaults() gateway := net.NewCloudControllerGateway() repo = NewCloudControllerPasswordRepository(configRepo, gateway, endpointRepo) return }
func createServiceRepoWithConfig(t *testing.T, reqs []testnet.TestRequest, config *configuration.Configuration) (ts *httptest.Server, handler *testnet.TestHandler, repo ServiceRepository) { if len(reqs) > 0 { ts, handler = testnet.NewTLSServer(t, reqs) config.Target = ts.URL } gateway := net.NewCloudControllerGateway() repo = NewCloudControllerServiceRepository(config, gateway) return }