func NewTestServer(server *ghttp.Server) *ghttp.Server { sampleSuccessTokenStringFormat := `{"access_token":"%s","token_type":"bearer","refresh_token":"%s","expires_in":599,"scope":"password.write cloud_controller.write openid cloud_controller.read","jti":"%s"}` loginTokenResponse := fmt.Sprintf(sampleSuccessTokenStringFormat, "access-token", "refresh-token", "jti") aiBasicResponse, _ := ioutil.ReadFile("fixtures/ai_basic_response.json") aiInfoHandler := ghttp.RespondWith(http.StatusOK, aiBasicResponse) aiDeleteHandler := ghttp.RespondWith(http.StatusNoContent, "") aiInfoPath, _ := regexp.Compile("/v2/apps/.*/instances") aiDeletePath, _ := regexp.Compile("/v2/apps/.*/instances/.*") server.RouteToHandler("GET", aiInfoPath, aiInfoHandler) server.RouteToHandler("DELETE", aiDeletePath, aiDeleteHandler) server.RouteToHandler("POST", "/oauth/token", ghttp.RespondWith(http.StatusOK, "{}")) server.AppendHandlers( ghttp.RespondWith(http.StatusOK, loginTokenResponse), ) return server }
<D:collection/> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 OK</D:status> </D:propstat> </D:response> </D:multistatus> ` responseBodyRoot = strings.Replace(responseBodyRoot, "http://192.168.11.11:8444", fakeServer.URL(), -1) }) It("lists objects", func() { fakeServer.RouteToHandler("PROPFIND", "/blobs", ghttp.CombineHandlers( ghttp.VerifyHeaderKV("Depth", "1"), ghttp.VerifyBasicAuth("user", "pass"), ghttp.RespondWith(207, responseBodyRoot, http.Header{"Content-Type": []string{"application/xml"}}), )) expectedTime, err := time.Parse(time.RFC1123, "Wed, 29 Jul 2015 18:43:36 GMT") Expect(err).NotTo(HaveOccurred()) Expect(blobStore.List()).To(ConsistOf( blob.Blob{Path: "b-droplet.tgz", Size: 4096, Created: expectedTime}, blob.Blob{Path: "a-droplet.tgz", Size: 4096, Created: expectedTime}, blob.Blob{Path: "c-droplet.tgz", Size: 4096, Created: expectedTime}, )) Expect(fakeServer.ReceivedRequests()).To(HaveLen(1)) })
flushEvents chan struct{} ) var getActualLRPGroups = func() []*models.ActualLRPGroup { actualLRPGroups, err := bbsClient.ActualLRPGroups(models.ActualLRPFilter{}) Expect(err).NotTo(HaveOccurred()) return actualLRPGroups } BeforeEach(func() { Eventually(getActualLRPGroups, 5*pollingInterval).Should(BeEmpty()) flushEvents = make(chan struct{}) fakeGarden = ghttp.NewUnstartedServer() // these tests only look for the start of a sequence of requests fakeGarden.AllowUnhandledRequests = false fakeGarden.RouteToHandler("GET", "/ping", ghttp.RespondWithJSONEncoded(http.StatusOK, struct{}{})) fakeGarden.RouteToHandler("GET", "/containers", ghttp.RespondWithJSONEncoded(http.StatusOK, struct{}{})) fakeGarden.RouteToHandler("GET", "/capacity", ghttp.RespondWithJSONEncoded(http.StatusOK, garden.Capacity{MemoryInBytes: 1024 * 1024 * 1024, DiskInBytes: 2048 * 1024 * 1024, MaxContainers: 4})) fakeGarden.RouteToHandler("GET", "/containers/bulk_info", ghttp.RespondWithJSONEncoded(http.StatusOK, struct{}{})) logger = lagertest.NewTestLogger("test") serviceClient = bbs.NewServiceClient(consulSession, clock.NewClock()) pollingInterval = 50 * time.Millisecond evacuationTimeout = 200 * time.Millisecond rootFSName = "the-rootfs" rootFSPath = "/path/to/rootfs" rootFSArg := fmt.Sprintf("%s:%s", rootFSName, rootFSPath)
callbackURL string taskDB *dbfakes.FakeTaskDB statusCodes chan int reqCount chan struct{} task *models.Task httpClient *http.Client ) BeforeEach(func() { httpClient = cf_http.NewClient() statusCodes = make(chan int) reqCount = make(chan struct{}) fakeServer.RouteToHandler("POST", "/the-callback/url", func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(<-statusCodes) }) callbackURL = fakeServer.URL() + "/the-callback/url" taskDB = new(dbfakes.FakeTaskDB) taskDB.ResolvingTaskReturns(nil) taskDB.DeleteTaskReturns(nil) }) simulateTaskCompleting := func(signals <-chan os.Signal, ready chan<- struct{}) error { close(ready) task = model_helpers.NewValidTask("the-task-guid") task.CompletionCallbackUrl = callbackURL taskworkpool.HandleCompletedTask(logger, httpClient, taskDB, task) return nil }
Mask: net.CIDRMask(24, 32), }, Gateway: net.ParseIP("192.168.1.1"), Routes: []types.Route{{ Dst: net.IPNet{ IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32), }, GW: net.ParseIP("192.168.1.1"), }}, }, } statusCode := http.StatusCreated server.RouteToHandler("POST", "/cni/add", ghttp.CombineHandlers( ghttp.VerifyHeaderKV("Content-Type", "application/json"), ghttp.RespondWithJSONEncodedPtr(&statusCode, &ipamResult), )) }) AfterEach(func() { server.Close() }) Describe("ADD", func() { It("returns IPAM data", func() { var err error var cmd *exec.Cmd cmd, err = buildCNICmdLight("ADD", netConfig, containerNSPath, containerID) Expect(err).NotTo(HaveOccurred()) session, err = gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred())
desiredLRPResponse = &models.DesiredLRPResponse{ Error: nil, DesiredLrp: &models.DesiredLRP{ ProcessGuid: processGuid, Instances: 100, Routes: &models.Routes{routes.DIEGO_SSH: &sshRouteMessage}, }, } clientConfig = &ssh.ClientConfig{} }) JustBeforeEach(func() { fakeBBS.RouteToHandler("POST", "/v1/actual_lrp_groups/get_by_process_guid_and_index", ghttp.CombineHandlers( ghttp.VerifyRequest("POST", "/v1/actual_lrp_groups/get_by_process_guid_and_index"), VerifyProto(expectedGetActualLRPRequest), RespondWithProto(actualLRPGroupResponse), )) fakeBBS.RouteToHandler("POST", "/v1/desired_lrps/get_by_process_guid.r1", ghttp.CombineHandlers( ghttp.VerifyRequest("POST", "/v1/desired_lrps/get_by_process_guid.r1"), VerifyProto(getDesiredLRPRequest), RespondWithProto(desiredLRPResponse), )) args := testrunner.Args{ Address: address, BBSAddress: bbsAddress, CCAPIURL: ccAPIURL, DiegoCredentials: diegoCredentials, EnableCFAuth: enableCFAuth, EnableDiegoAuth: enableDiegoAuth,
), ghttp.CombineHandlers( ghttp.VerifyRequest("POST", "/api/v1/pipes"), ghttp.RespondWithJSONEncoded(http.StatusCreated, atc.Pipe{ ID: "some-other-pipe-id", }), ), ) atcServer.RouteToHandler("POST", "/api/v1/builds", ghttp.CombineHandlers( ghttp.VerifyRequest("POST", "/api/v1/builds"), ghttp.VerifyJSONRepresenting(expectedPlan), func(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Name: "Some-Cookie", Value: "some-cookie-data", Path: "/", Expires: time.Now().Add(1 * time.Minute), }) }, ghttp.RespondWith(201, `{"id":128}`), ), ) atcServer.RouteToHandler("GET", "/api/v1/builds/128/events", ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/api/v1/builds/128/events"), func(w http.ResponseWriter, r *http.Request) { flusher := w.(http.Flusher) w.Header().Add("Content-Type", "text/event-stream; charset=utf-8") w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
BeforeEach(func() { sshAccessResponseCode = http.StatusInternalServerError sshAccessResponse = &authenticators.AppSSHResponse{} }) It("fails to authenticate", func() { Expect(authenErr).To(Equal(authenticators.FetchAppFailedErr)) Expect(fakeCC.ReceivedRequests()).To(HaveLen(1)) }) }) Context("when the cc ssh_access response cannot be parsed", func() { BeforeEach(func() { fakeCC.RouteToHandler("GET", "/internal/apps/app-guid/ssh_access/1", ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/internal/apps/app-guid/ssh_access/1"), ghttp.VerifyHeader(http.Header{"Authorization": []string{"bearer exchanged-token"}}), ghttp.RespondWith(http.StatusOK, "{{"), )) }) It("fails to authenticate", func() { Expect(authenErr).To(Equal(authenticators.InvalidCCResponse)) Expect(fakeCC.ReceivedRequests()).To(HaveLen(1)) }) }) Context("the the cc ssh_access check times out", func() { BeforeEach(func() { ccTempClientTimeout := httpClientTimeout fakeCC.RouteToHandler("GET", "/internal/apps/app-guid/ssh_access/1", func(w http.ResponseWriter, req *http.Request) {
listener, err := net.Listen("tcp", ip+":0") Expect(err).NotTo(HaveOccurred()) timeout = 100 * time.Millisecond serverDelay = 0 server.HTTPTestServer.Listener = listener serverAddr = listener.Addr().String() _, port, err = net.SplitHostPort(serverAddr) Expect(err).NotTo(HaveOccurred()) }) JustBeforeEach(func() { server.RouteToHandler("GET", "/api/_ping", func(http.ResponseWriter, *http.Request) { time.Sleep(serverDelay) }) server.Start() hc = healthcheck.NewHealthCheck("tcp", uri, port, timeout) }) AfterEach(func() { if server != nil { server.CloseClientConnections() server.Close() } }) Describe("check interfaces", func() { It("succeeds when there are healthy interfaces", func() {
) }) Context("when configuring with templated keys succeeds", func() { BeforeEach(func() { path, err := atc.Routes.CreatePathForRoute(atc.SaveConfig, rata.Params{"pipeline_name": "awesome-pipeline"}) Expect(err).NotTo(HaveOccurred()) atcServer.RouteToHandler("PUT", path, ghttp.CombineHandlers( ghttp.VerifyHeaderKV(atc.ConfigVersionHeader, "42"), func(w http.ResponseWriter, r *http.Request) { bodyConfig := getConfig(r) receivedConfig := atc.Config{} err = yaml.Unmarshal(bodyConfig, &receivedConfig) Expect(err).NotTo(HaveOccurred()) Expect(receivedConfig).To(Equal(config)) w.WriteHeader(http.StatusNoContent) }, ), ) }) It("parses the config file and sends it to the ATC", func() { flyCmd := exec.Command( flyPath, "-t", atcServer.URL()+"/", "set-pipeline", "--pipeline", "awesome-pipeline", "-c", "fixtures/testConfig.yml",
os.Environ(), fmt.Sprintf(`CF_INSTANCE_PORTS=[{"external":%s,"internal":%s}]`, port, "8080"), ) session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) return session } BeforeEach(func() { _, port, err = net.SplitHostPort(serverAddr) Expect(err).NotTo(HaveOccurred()) }) Context("when the healthcheck is properly invoked", func() { BeforeEach(func() { server.RouteToHandler("GET", "/api/_ping", ghttp.VerifyRequest("GET", "/api/_ping")) }) Context("when the address is listening", func() { itExitsWithCode(httpHealthCheck, 0, "healthcheck passed") }) Context("when the address returns error http code", func() { BeforeEach(func() { server.RouteToHandler("GET", "/api/_ping", ghttp.RespondWith(500, "")) }) itExitsWithCode(httpHealthCheck, 6, "failure to get valid HTTP status code: 500") }) }) })
"execution_metadata": "execution-metadata-3", "health_check_timeout_in_seconds": 123456, "etag": "3.1" }`, } fakeCC.RouteToHandler("GET", "/internal/bulk/apps", ghttp.RespondWith(200, `{ "token": {}, "fingerprints": [ { "process_guid": "process-guid-1", "etag": "1.1" }, { "process_guid": "process-guid-2", "etag": "2.1" }, { "process_guid": "process-guid-3", "etag": "3.1" } ] }`), ) fakeCC.RouteToHandler("POST", "/internal/bulk/apps", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { var processGuids []string decoder := json.NewDecoder(req.Body) err := decoder.Decode(&processGuids)
BeforeEach(func() { sessionFactory = docker_metadata_fetcher.NewDockerSessionFactory() dockerRegistryServer = ghttp.NewServer() }) AfterEach(func() { dockerRegistryServer.Close() }) Describe("creating registry sessions", func() { BeforeEach(func() { parts, err := url.Parse(dockerRegistryServer.URL()) Expect(err).NotTo(HaveOccurred()) registryHost = parts.Host dockerRegistryServer.RouteToHandler("GET", "/v1/_ping", ghttp.VerifyRequest("GET", "/v1/_ping")) dockerRegistryServer.RouteToHandler("GET", "/v2/", ghttp.VerifyRequest("GET", "/v2/")) }) Context("when connecting to a secure registry", func() { It("creates a registry session for the given repo", func() { session, err := sessionFactory.MakeSession(registryHost+"/lattice-mappppppppppppappapapa", false) Expect(err).NotTo(HaveOccurred()) registrySession, ok := session.(*registry.Session) Expect(ok).To(BeTrue()) Expect(*registrySession.GetAuthConfig(true)).To(Equal(registry.AuthConfig{})) Expect(dockerRegistryServer.ReceivedRequests()).To(HaveLen(2)) }) })
request *http.Request ) BeforeEach(func() { serviceReady = make(chan struct{}) fakeServer = ghttp.NewServer() handler = handlers.NewUnavailableHandler(fakeServer, serviceReady) var err error request, err = http.NewRequest("GET", "/test", nil) Expect(err).NotTo(HaveOccurred()) fakeServer.RouteToHandler("GET", "/test", ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/test"), ghttp.RespondWith(200, nil, nil), )) }) verifyResponse := func(expectedStatus int, handler *handlers.UnavailableHandler) { responseRecorder := httptest.NewRecorder() handler.ServeHTTP(responseRecorder, request) Expect(responseRecorder.Code).To(Equal(expectedStatus)) } It("responds with 503 until the service is ready", func() { verifyResponse(http.StatusServiceUnavailable, handler) verifyResponse(http.StatusServiceUnavailable, handler) close(serviceReady)
Tags: []string{"some", "tags"}, } fakeATC = ghttp.NewServer() registerRoute, found := atc.Routes.FindRouteByName(atc.RegisterWorker) Ω(found).Should(BeTrue()) registered := make(chan registration, 100) registrations = registered fakeATC.RouteToHandler(registerRoute.Method, registerRoute.Path, func(w http.ResponseWriter, r *http.Request) { var worker atc.Worker err := json.NewDecoder(r.Body).Decode(&worker) Ω(err).ShouldNot(HaveOccurred()) ttl, err := time.ParseDuration(r.URL.Query().Get("ttl")) Ω(err).ShouldNot(HaveOccurred()) registered <- registration{worker, ttl} }) fakeGardenClient = new(gfakes.FakeClient) }) JustBeforeEach(func() { atcEndpoint := rata.NewRequestGenerator(fakeATC.URL(), atc.Routes) heartbeater = ifrit.Invoke( NewHeartbeater( logger, interval, fakeGardenClient,
Index: 12, State: receptor.ActualLRPStateRunning, }, } tasksResponse := []receptor.TaskResponse{ {TaskGuid: "task-guid"}, } BeforeEach(func() { outputBuffer = gbytes.NewBuffer() fakeServer = ghttp.NewServer() listenerAddr = fakeServer.HTTPTestServer.Listener.Addr().String() fakeServer.RouteToHandler("GET", "/v1/desired_lrps", ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/v1/desired_lrps"), ghttp.RespondWithJSONEncoded(http.StatusOK, desiredResponse), ), ) fakeServer.RouteToHandler("GET", "/v1/actual_lrps", ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/v1/actual_lrps"), ghttp.RespondWithJSONEncoded(http.StatusOK, actualResponse), ), ) fakeServer.RouteToHandler("GET", "/v1/tasks", ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/v1/tasks"), ghttp.RespondWithJSONEncoded(http.StatusOK, tasksResponse), ), )
<D:resourcetype> <D:collection/> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 OK</D:status> </D:propstat> </D:response> </D:multistatus> ` responseBodyRoot = strings.Replace(responseBodyRoot, "http://192.168.11.11:8444", fakeServer.URL(), -1) }) Context("when the DAV blob store does not require auth", func() { It("should return authorized", func() { fakeServer.RouteToHandler("PROPFIND", "/blobs/", ghttp.CombineHandlers( ghttp.VerifyHeaderKV("Depth", "1"), ghttp.RespondWith(207, responseBodyRoot, http.Header{"Content-Type": []string{"text/xml"}}), )) config.SetBlobStore(serverHost, serverPort, "", "") authorized, err := verifier.Verify(config) Expect(err).NotTo(HaveOccurred()) Expect(authorized).To(BeTrue()) Expect(fakeServer.ReceivedRequests()).To(HaveLen(1)) }) }) Context("when the DAV blob store requires auth", func() { It("should return authorized for proper credentials", func() { fakeServer.RouteToHandler("PROPFIND", "/blobs/", ghttp.CombineHandlers( ghttp.VerifyBasicAuth("good-user", "good-pass"),
Context("setting up http client to request one time code", func() { var fakeUAA *ghttp.Server BeforeEach(func() { authRepo.RefreshToken = "bearer client-bearer-token" configRepo.SetSSLDisabled(true) configRepo.SetSSHOAuthClient("ssh-oauth-client-id") fakeUAA = ghttp.NewTLSServer() configRepo.SetUaaEndpoint(fakeUAA.URL()) fakeUAA.RouteToHandler("GET", "/oauth/authorize", ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/oauth/authorize"), ghttp.VerifyFormKV("response_type", "code"), ghttp.VerifyFormKV("client_id", "ssh-oauth-client-id"), ghttp.VerifyFormKV("grant_type", "authorization_code"), ghttp.VerifyHeaderKV("authorization", "bearer client-bearer-token"), ghttp.RespondWith(http.StatusFound, "", http.Header{ "Location": []string{"https://uaa.example.com/login?code=abc123"}, }), )) }) It("gets the access code from the token endpoint", func() { runCommand() Ω(authRepo.RefreshTokenCalled).To(BeTrue()) Ω(fakeUAA.ReceivedRequests()).To(HaveLen(1)) Ω(ui.Outputs).To(ContainSubstrings( []string{"abc123"}, )) })
Args: []string{"."}, }, }, }, }, }, } }) JustBeforeEach(func() { uploading = make(chan struct{}) atcServer.RouteToHandler("POST", "/api/v1/pipes", ghttp.CombineHandlers( ghttp.VerifyRequest("POST", "/api/v1/pipes"), ghttp.RespondWithJSONEncoded(http.StatusCreated, atc.Pipe{ ID: "some-pipe-id", }), ), ) atcServer.RouteToHandler("GET", "/api/v1/pipelines/some-pipeline/jobs/some-job/inputs", ghttp.CombineHandlers( ghttp.VerifyRequest("GET", "/api/v1/pipelines/some-pipeline/jobs/some-job/inputs"), ghttp.RespondWithJSONEncoded(http.StatusOK, []atc.BuildInput{ { Name: "some-input", Type: "git", Resource: "some-resource", Source: atc.Source{"uri": "https://internet.com"}, Params: atc.Params{"some": "params"}, Version: atc.Version{"some": "version"}, Tags: atc.Tags{"tag-1", "tag-2"},
Ω(err).ShouldNot(HaveOccurred()) Ω(string(respBody)).Should(Equal(txt)) Ω(resp.Header.Get("Content-Type")).Should(Equal("text/world")) Ω(resp.StatusCode).Should(Equal(200)) } }) It("Does many requests with random sleeps", func() { const N = 20 server.RouteToHandler("GET", regexp.MustCompile(`^/hello/`), func(w http.ResponseWriter, req *http.Request) { var i int n, err := fmt.Sscanf(req.RequestURI, "/hello/%d", &i) if n != 1 || err != nil { w.WriteHeader(400) } else { time.Sleep(time.Duration(10*i) * time.Millisecond) w.Header().Set("Content-Type", "text/world") w.WriteHeader(200) w.Write([]byte(fmt.Sprintf("/hello/%d", i))) } }) resp := make([]*http.Response, N, N) err := make([]error, N, N) wg := sync.WaitGroup{} wg.Add(N) fmt.Fprintln(os.Stderr, "Launching N concurrent requests") for i := 0; i < N; i++ { go func(i int) { txt := fmt.Sprintf("/hello/%d", i)
<D:collection/> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 OK</D:status> </D:propstat> </D:response> </D:multistatus> ` responseBodyA = strings.Replace(responseBodyA, "http://192.168.11.11:8444", fakeServer.URL(), -1) responseBodyB = strings.Replace(responseBodyB, "http://192.168.11.11:8444", fakeServer.URL(), -1) responseBodyC = strings.Replace(responseBodyC, "http://192.168.11.11:8444", fakeServer.URL(), -1) fakeServer.RouteToHandler("PROPFIND", "/blobs", ghttp.CombineHandlers( ghttp.VerifyHeaderKV("Depth", "1"), ghttp.VerifyBasicAuth("user", "pass"), ghttp.RespondWith(207, responseBodyRoot, http.Header{"Content-Type": []string{"application/xml"}}), )) fakeServer.RouteToHandler("PROPFIND", "/blobs/a", ghttp.CombineHandlers( ghttp.VerifyHeaderKV("Depth", "1"), ghttp.VerifyBasicAuth("user", "pass"), ghttp.RespondWith(207, responseBodyA, http.Header{"Content-Type": []string{"application/xml"}}), )) fakeServer.RouteToHandler("PROPFIND", "/blobs/b", ghttp.CombineHandlers( ghttp.VerifyHeaderKV("Depth", "1"), ghttp.VerifyBasicAuth("user", "pass"), ghttp.RespondWith(207, responseBodyB, http.Header{"Content-Type": []string{"application/xml"}}), ))
etcd2.Close() etcd3.Close() }) Context("when the etcd server gives valid JSON", func() { BeforeEach(func() { etcd1.RouteToHandler("GET", "/v2/stats/self", ghttp.RespondWith(200, ` { "name": "node1", "id": "node1-id", "state": "StateFollower", "leaderInfo": { "leader": "node2-id", "uptime": "17h41m45.103057785s", "startTime": "2015-02-13T01:28:26.657389108Z" }, "recvAppendRequestCnt": 1234, "recvPkgRate": 2.0, "recvBandwidthRate": 1.2, "sendAppendRequestCnt": 4321 } `)) etcd1.RouteToHandler("GET", "/v2/stats/leader", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, etcd2.URL(), 302) }) etcd2.RouteToHandler("GET", "/v2/stats/self", ghttp.RespondWith(200, `
proxyConfReader = &droplet_runner.HTTPProxyConfReader{ URL: fakeServer.URL() + "/pc.json", } }) AfterEach(func() { if fakeServer != nil { fakeServer.Close() } }) Context("#ProxyConf", func() { It("should parse JSON on 200", func() { fakeServer.RouteToHandler("GET", "/pc.json", ghttp.CombineHandlers( ghttp.RespondWith(200, `{"http_proxy": "http://proxy", "https_proxy": "https://proxy", "no_proxy": "no-proxy"}`, http.Header{"Content-Type": []string{"application/json"}}, ), )) proxyConf, err := proxyConfReader.ProxyConf() Expect(err).NotTo(HaveOccurred()) Expect(proxyConf.HTTPProxy).To(Equal("http://proxy")) Expect(proxyConf.HTTPSProxy).To(Equal("https://proxy")) Expect(proxyConf.NoProxy).To(Equal("no-proxy")) Expect(fakeServer.ReceivedRequests()).To(HaveLen(1)) }) It("should fail when it receives invalid JSON on 200", func() { fakeServer.RouteToHandler("GET", "/pc.json", ghttp.CombineHandlers(
Name: "some-other-resource", Type: "some-other-type", Source: atc.Source{ "secret_key": "verysecret", }, }, }, Jobs: atc.JobConfigs{}, } path, err := atc.Routes.CreatePathForRoute(atc.GetConfig, rata.Params{"pipeline_name": "awesome-pipeline"}) Ω(err).ShouldNot(HaveOccurred()) atcServer.RouteToHandler("GET", path, ghttp.RespondWithJSONEncoded(200, config, http.Header{atc.ConfigVersionHeader: {"42"}}), ) }) Context("when configuring with templated keys succeeds", func() { JustBeforeEach(func() { var err error payload, err = yaml.Marshal(config) Ω(err).ShouldNot(HaveOccurred()) }) BeforeEach(func() { path, err := atc.Routes.CreatePathForRoute(atc.SaveConfig, rata.Params{"pipeline_name": "awesome-pipeline"}) Ω(err).ShouldNot(HaveOccurred()) atcServer.RouteToHandler("PUT", path,
Context("when call to receptor fails", func() { It("should return the error", func() { err := errors.New("error") fakeReceptorClient.GetVersionReturns(receptor.VersionResponse{}, err) _, actualError := versionManager.ServerVersions("") Expect(actualError).To(Equal(err)) }) }) }) Describe("#SyncLTC", func() { It("should download ltc from the target and swap it with ltc", func() { fakeServer.RouteToHandler("GET", "/v1/sync/amiga/ltc", ghttp.CombineHandlers( ghttp.RespondWith(200, []byte{0x01, 0x02, 0x03}, http.Header{ "Content-Type": []string{"application/octet-stream"}, "Content-Length": []string{"3"}, }), )) tmpFile, err := ioutil.TempFile("", "") Expect(err).NotTo(HaveOccurred()) defer os.Remove(tmpFile.Name()) fakeFileSwapper.GetTempFileReturns(tmpFile, nil) versionManager.SyncLTC(ltcTempFile.Name(), "amiga", config) Expect(fakeServer.ReceivedRequests()).To(HaveLen(1)) Expect(fakeFileSwapper.GetTempFileCallCount()).To(Equal(1))
}) }) }) Describe("when a task is enqueued", func() { var ( callbackURL *url.URL statusCodes chan int reqCount chan struct{} ) BeforeEach(func() { statusCodes = make(chan int) reqCount = make(chan struct{}, task_handler.POOL_SIZE) fakeServer.RouteToHandler("POST", "/the-callback/url", func(w http.ResponseWriter, req *http.Request) { reqCount <- struct{}{} w.WriteHeader(<-statusCodes) }) var err error callbackURL, err = url.Parse(fakeServer.URL() + "/the-callback/url") Expect(err).NotTo(HaveOccurred()) }) AfterEach(func() { close(statusCodes) }) simulateTaskCompleting := func() { enqueue <- models.Task{ TaskGuid: "the-task-guid", CompletionCallbackURL: callbackURL,
Expect(err).ToNot(HaveOccurred()) client = &http.Client{ Transport: &http.Transport{}, Jar: cookieJar, } }) Describe("GET /auth/:provider", func() { var redirectTarget *ghttp.Server var request *http.Request var response *http.Response BeforeEach(func() { redirectTarget = ghttp.NewServer() redirectTarget.RouteToHandler("GET", "/", ghttp.RespondWith(http.StatusOK, "sup")) var err error request, err = http.NewRequest("GET", server.URL, nil) Expect(err).NotTo(HaveOccurred()) }) JustBeforeEach(func() { var err error response, err = client.Do(request) Expect(err).NotTo(HaveOccurred()) }) Context("to a known provider", func() {
AfterEach(func() { routingApiServer.Close() }) Describe("ListRouterGroups", func() { Context("when routing api return router groups", func() { BeforeEach(func() { routingApiServer = ghttp.NewServer() routingApiServer.RouteToHandler("GET", "/v1/router_groups", func(w http.ResponseWriter, req *http.Request) { responseBody := []byte(`[ { "guid": "bad25cff-9332-48a6-8603-b619858e7992", "name": "default-tcp", "type": "tcp" }]`) w.Header().Set("Content-Length", strconv.Itoa(len(responseBody))) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(responseBody) }) configRepo.SetRoutingApiEndpoint(routingApiServer.URL()) }) It("lists routing groups", func() { cb := func(grp models.RouterGroup) bool { Expect(grp).To(Equal(models.RouterGroup{ Guid: "bad25cff-9332-48a6-8603-b619858e7992", Name: "default-tcp", Type: "tcp",
}) Describe("vegeta library", func() { var server *ghttp.Server BeforeEach(func() { server = ghttp.NewServer() }) AfterEach(func() { server.Close() }) Context("endpoint returns 404 mimicing CF app with no instances", func() { BeforeEach(func() { server.RouteToHandler("GET", "/", ghttp.CombineHandlers( ghttp.RespondWith(http.StatusNotFound, ""), ), ) }) It("reports the requests as not successful", func() { attacker, resultChannel := loadTest(server.URL(), availabilityTestRate) defer attacker.Stop() Eventually(func() int { return len(server.ReceivedRequests()) }).Should(BeNumerically(">", 1)) attacker.Stop() for result := range resultChannel { metrics.Add(result)