func CreateUaaProtectedServer(manifest string, deployments []models.IndexDeployment, uaaEndpoint string) *ghttp.Server {
	yaml, err := ioutil.ReadFile(manifest)
	Expect(err).ToNot(HaveOccurred())

	diegoDeployment := models.ShowDeployment{
		Manifest: string(yaml),
	}
	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/info"),
			ghttp.RespondWith(200, fmt.Sprintf(`{"user_authentication":{"type":"uaa","options":{"url":"%s"}}}`, uaaEndpoint)),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments"),
			ghttp.VerifyHeader(http.Header{"Authorization": []string{"bearer the token"}}),
			ghttp.RespondWithJSONEncoded(200, deployments),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments/cf-warden-diego"),
			ghttp.VerifyHeader(http.Header{"Authorization": []string{"bearer the token"}}),
			ghttp.RespondWithJSONEncoded(200, diegoDeployment),
		),
	)
	return server
}
func CreateServer(manifest string, deployments []models.IndexDeployment) *ghttp.Server {
	yaml, err := ioutil.ReadFile(manifest)
	Expect(err).ToNot(HaveOccurred())

	diegoDeployment := models.ShowDeployment{
		Manifest: string(yaml),
	}

	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/info"),
			ghttp.RespondWith(200, `{"user_authentication":{"type":"basic"}}`),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments"),
			ghttp.RespondWithJSONEncoded(200, deployments),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments/cf-warden-diego"),
			ghttp.RespondWithJSONEncoded(200, diegoDeployment),
		),
	)

	return server
}
Пример #3
0
func setupSuccessfulV2Fetch(server *ghttp.Server, layer1Cached bool) {
	layer1Data := "banana-1-flan"
	layer1Dgst, _ := digest.FromBytes([]byte(layer1Data))

	layer2Data := "banana-2-flan"
	layer2Dgst, _ := digest.FromBytes([]byte(layer2Data))

	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/v2/some-repo/manifests/some-tag"),
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				w.Write([]byte(fmt.Sprintf(`
					{
					   "name":"some-repo",
					   "tag":"some-tag",
					   "fsLayers":[
						  {
							 "blobSum":"%s"
						  },
						  {
							 "blobSum":"%s"
						  }
					   ],
					   "history":[
						  {
							 "v1Compatibility": "{\"id\":\"banana-pie-2\", \"parent\":\"banana-pie-1\"}"
						  },
						  {
							 "v1Compatibility": "{\"id\":\"banana-pie-1\"}"
						  }
					   ]
					}
					`, layer2Dgst.String(), layer1Dgst.String())))
			}),
		),
	)

	if !layer1Cached {
		server.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", fmt.Sprintf("/v2/some-repo/blobs/%s", layer1Dgst)),
				http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
					w.Write([]byte(layer1Data))
				}),
			),
		)
	}

	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/v2/some-repo/blobs/%s", layer2Dgst)),
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				w.Write([]byte(layer2Data))
			}),
		),
	)
}
func Create401Server() *ghttp.Server {
	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/info"),
			ghttp.RespondWithJSONEncoded(200, `{"user_authentication":{"type":"basic"}}`),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments"),
			ghttp.RespondWith(401, "Not authorized"),
		),
	)

	return server
}
Пример #5
0
func listStoriesHandler(trackerToken string) http.HandlerFunc {
	return ghttp.CombineHandlers(
		ghttp.VerifyRequest("GET", "/services/v5/projects/1234/stories"),
		ghttp.VerifyHeaderKV("X-TrackerToken", trackerToken),
		ghttp.RespondWith(http.StatusOK, Fixture("stories.json")),
	)
}
func MakeWorkflowHandlers(workflow string, requestID string, nodeID string) []http.HandlerFunc {
	taskStubData := []byte(fmt.Sprintf("[{\"injectableName\": \"Task.BOSH.%s.Node.%s\"}]", workflow, requestID))
	workflowStubData := []byte(fmt.Sprintf("[{\"injectableName\": \"Graph.BOSH.%sNode.%s\"}]", workflow, requestID))
	nodeStubData := []byte(`{"obmSettings": [{"service": "fake-obm-service"}]}`)
	completedWorkflowResponse := []byte(fmt.Sprintf("{\"id\": \"%s\", \"_status\": \"succeeded\"}", requestID))

	return []http.HandlerFunc{
		ghttp.VerifyRequest("PUT", "/api/1.1/workflows/tasks"),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/api/1.1/workflows/tasks/library"),
			ghttp.RespondWith(http.StatusOK, taskStubData),
		),
		ghttp.VerifyRequest("PUT", "/api/1.1/workflows"),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/api/1.1/workflows/library"),
			ghttp.RespondWith(http.StatusOK, workflowStubData),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/common/nodes/%s", nodeID)),
			ghttp.RespondWith(http.StatusOK, nodeStubData),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("POST", fmt.Sprintf("/api/1.1/nodes/%s/workflows/", nodeID)),
			ghttp.RespondWith(http.StatusCreated, completedWorkflowResponse),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/common/workflows/%s", requestID)),
			ghttp.RespondWith(http.StatusOK, completedWorkflowResponse),
		),
	}
}
Пример #7
0
func verifyPollingRequest(jobGuid, status string, timeClicker chan time.Time) http.HandlerFunc {
	return ghttp.CombineHandlers(
		ghttp.VerifyRequest("GET", urljoiner.Join("/v2/jobs/", jobGuid)),
		ghttp.RespondWith(http.StatusOK, pollingResponseBody(jobGuid, status, "")),
		func(w http.ResponseWriter, r *http.Request) {
			timeClicker <- time.Now()
		},
	)
}
Пример #8
0
func deliverStoryHandler(token string, projectId string, storyId int) http.HandlerFunc {
	body := `{"current_state":"delivered"}`
	return ghttp.CombineHandlers(
		ghttp.VerifyRequest(
			"PUT",
			fmt.Sprintf("/services/v5/projects/%s/stories/%d", projectId, storyId),
		), ghttp.VerifyHeaderKV("X-TrackerToken", token),
		ghttp.VerifyJSON(body),
	)
}
Пример #9
0
func deliverStoryCommentHandler(token string, projectId string, storyId int, comment string) http.HandlerFunc {
	body := fmt.Sprintf(`{"text":"%s"}`, comment)
	return ghttp.CombineHandlers(
		ghttp.VerifyRequest(
			"POST",
			fmt.Sprintf("/services/v5/projects/%s/stories/%d/comments", projectId, storyId),
		), ghttp.VerifyHeaderKV("X-TrackerToken", token),
		ghttp.VerifyJSON(body),
	)
}
func Create401Server() *ghttp.Server {
	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments"),
			ghttp.RespondWith(401, "Not authorized"),
		),
	)

	return server
}
func CreateOAuthServer() *ghttp.Server {
	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("POST", "/oauth/token"),
			ghttp.VerifyBasicAuth("bosh_cli", ""),
			ghttp.RespondWith(200, `{"access_token":"the token","expires_in":3600}`,
				http.Header{"Content-Type": []string{"application/json"}}),
		),
	)
	return server
}
func MakeTryReservationHandlers(requestID string, nodeID string, expectedNodesPath string, expectedNodeCatalogPath string) []http.HandlerFunc {
	expectedNodes := LoadNodes(expectedNodesPath)
	expectedNodesData, err := json.Marshal(expectedNodes)
	Expect(err).ToNot(HaveOccurred())
	var expectedNode rackhdapi.Node
	for n := range expectedNodes {
		if expectedNodes[n].ID == nodeID {
			expectedNode = expectedNodes[n]
		}
	}
	Expect(expectedNode).ToNot(BeNil())
	expectedNodeData, err := json.Marshal(expectedNode)
	Expect(err).ToNot(HaveOccurred())
	expectedNodeCatalog := LoadNodeCatalog(expectedNodeCatalogPath)
	expectedNodeCatalogData, err := json.Marshal(expectedNodeCatalog)
	Expect(err).ToNot(HaveOccurred())

	reservationHandlers := []http.HandlerFunc{
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/api/common/nodes"),
			ghttp.RespondWith(http.StatusOK, expectedNodesData),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/common/nodes/%s/catalogs/ohai", nodeID)),
			ghttp.RespondWith(http.StatusOK, expectedNodeCatalogData),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/1.1/nodes/%s/workflows/active", nodeID)),
			ghttp.RespondWith(http.StatusOK, nil),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/common/nodes/%s", nodeID)),
			ghttp.RespondWith(http.StatusOK, expectedNodeData),
		),
	}

	return append(reservationHandlers, MakeWorkflowHandlers("Reserve", requestID, nodeID)...)
}
Пример #13
0
func (f *FakeCC) newHandleStagingRequest() http.HandlerFunc {
	return ghttp.CombineHandlers(
		ghttp.VerifyRequest("POST", MatchRegexp("/internal/staging/(.*)/completed")),
		ghttp.VerifyBasicAuth(CC_USERNAME, CC_PASSWORD),
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			var msg cc_messages.StagingResponseForCC
			err := json.NewDecoder(r.Body).Decode(&msg)
			Expect(err).NotTo(HaveOccurred())
			r.Body.Close()
			f.lock.Lock()
			defer f.lock.Unlock()
			guid := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/internal/staging/"), "/completed")
			f.stagingGuids = append(f.stagingGuids, guid)
			f.stagingResponses = append(f.stagingResponses, msg)
		}),
		ghttp.RespondWithPtr(&f.stagingResponseStatusCode, &f.stagingResponseBody),
	)
}
Пример #14
0
func stream(handle string, route string, processid, attachid int, fn func(net.Conn)) http.HandlerFunc {
	return ghttp.CombineHandlers(
		ghttp.VerifyRequest("GET",
			fmt.Sprintf("/containers/%s/processes/%d/attaches/%d/%s",
				handle,
				processid,
				attachid,
				route,
			)),

		func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusOK)

			conn, _, err := w.(http.Hijacker).Hijack()
			Ω(err).ShouldNot(HaveOccurred())
			defer conn.Close()

			fn(conn)
		},
	)
}
Пример #15
0
func setupSuccessfulFetch(server *ghttp.Server) {
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/v1/images/layer-3/json"),
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				w.Header().Add("X-Docker-Size", "123")
				w.Write([]byte(`{"id":"layer-3","parent":"parent-3","Config":{"env": ["env2=env2Value", "malformedenvvar"]}}`))
			}),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/v1/images/layer-3/layer"),
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				w.Write([]byte(`layer-3-data`))
			}),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/v1/images/layer-2/json"),
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				w.Header().Add("X-Docker-Size", "456")
				w.Write([]byte(`{"id":"layer-2","parent":"parent-2","Config":{"volumes": { "/tmp": {}, "/another": {} }, "env": ["env1=env1Value", "env2=env2NewValue"]}}`))
			}),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/v1/images/layer-2/layer"),
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				w.Write([]byte(`layer-2-data`))
			}),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/v1/images/layer-1/json"),
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				w.Header().Add("X-Docker-Size", "789")
				w.Write([]byte(`{"id":"layer-1","parent":"parent-1"}`))
			}),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/v1/images/layer-1/layer"),
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				w.Write([]byte(`layer-1-data`))
			}),
		),
	)
}
Пример #16
0
				env := gohanscript.NewEnvironment(timelimit)
				Expect(env.LoadExtensionsForPath(extensions, "test_path")).To(Succeed())

				context := map[string]interface{}{
					"id": "test",
				}
				Expect(env.HandleEvent("test_event", context)).To(Succeed())
				Expect(context["person"]).ToNot(BeNil())
			})
		})

		Context("When extension URL uses http:// protocol", func() {
			It("should download and run the extension", func() {
				server := ghttp.NewServer()
				server.AppendHandlers(ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/extension.yaml"),
					ghttp.RespondWith(200, `tasks:
                         - vars:
                             person: John
                         `),
				))

				extension, err := schema.NewExtension(map[string]interface{}{
					"id":   "test_extension",
					"url":  server.URL() + "/extension.yaml",
					"path": ".*",
				})
				Expect(err).ToNot(HaveOccurred())
				extensions := []*schema.Extension{extension}
				env := gohanscript.NewEnvironment(timelimit)
				Expect(env.LoadExtensionsForPath(extensions, "test_path")).To(Succeed())
Пример #17
0
			Nice:       rlimits.Nice,
			Nofile:     rlimits.Nofile,
			Nproc:      rlimits.Nproc,
			Rss:        rlimits.Rss,
			Rtprio:     rlimits.Rtprio,
			Sigpending: rlimits.Sigpending,
			Stack:      rlimits.Stack,
		}
	})

	Describe("Ping", func() {
		Context("when the response is successful", func() {
			BeforeEach(func() {
				server.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/ping"),
						ghttp.RespondWith(200, "{}"),
					),
				)
			})

			It("should ping the server", func() {
				err := connection.Ping()
				Ω(err).ShouldNot(HaveOccurred())
			})
		})

		Context("when the request fails", func() {
			BeforeEach(func() {
				server.AppendHandlers(
					ghttp.CombineHandlers(
Пример #18
0
		server = ghttp.NewServer()

		c = &client.JSONClient{
			BaseURL: server.URL(),
		}

		route = "/some/route"
	})
	AfterEach(func() {
		server.Close()
	})

	Describe("Get", func() {
		BeforeEach(func() {
			serverHandler = ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", route),
				ghttp.RespondWith(http.StatusOK, `{ "SomeResponseField": "some value" }`),
			)
			server.AppendHandlers(serverHandler)
		})

		It("should make a get request to the given route", func() {
			err := c.Get(route, &responseStruct)
			Expect(err).NotTo(HaveOccurred())
			Expect(server.ReceivedRequests()).To(HaveLen(1))
			Expect(responseStruct.SomeResponseField).To(Equal("some value"))
		})

		Context("when the request cannot be created", func() {
			It("should return an error", func() {
				err := c.Get("%%%", &responseStruct)
Пример #19
0
	// Perform the test by running main() with the command line args set
	It("Errors non-existing tunnels", func() {
		resp, err := http.Get(wstunUrl + "/_token/badtokenbadtoken/hello")
		Ω(err).ShouldNot(HaveOccurred())
		respBody, err := ioutil.ReadAll(resp.Body)
		Ω(err).ShouldNot(HaveOccurred())
		Ω(string(respBody)).Should(ContainSubstring("long time"))
		Ω(resp.Header.Get("Content-Type")).Should(ContainSubstring("text/plain"))
		Ω(resp.StatusCode).Should(Equal(404))
	})

	It("Reconnects the websocket", func() {
		server.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/hello"),
				ghttp.RespondWith(200, `WORLD`,
					http.Header{"Content-Type": []string{"text/world"}}),
			),
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/hello"),
				ghttp.RespondWith(200, `AGAIN`,
					http.Header{"Content-Type": []string{"text/world"}}),
			),
		)

		// first request
		resp, err := http.Get(wstunUrl + "/_token/" + wstunToken + "/hello")
		Ω(err).ShouldNot(HaveOccurred())
		respBody, err := ioutil.ReadAll(resp.Body)
		Ω(err).ShouldNot(HaveOccurred())
Пример #20
0
			It("starts", func() {
				Consistently(runner.Session).ShouldNot(Exit())
			})
		})

		Context("when starting", func() {
			var deleteChan chan struct{}
			BeforeEach(func() {
				fakeGarden.RouteToHandler("GET", "/containers",
					ghttp.RespondWithJSONEncoded(http.StatusOK, map[string][]string{"handles": []string{"cnr1", "cnr2"}}),
				)

				deleteChan = make(chan struct{}, 2)
				fakeGarden.AppendHandlers(
					ghttp.CombineHandlers(ghttp.VerifyRequest("DELETE", "/containers/cnr1"),
						func(http.ResponseWriter, *http.Request) {
							deleteChan <- struct{}{}
						},
						ghttp.RespondWithJSONEncoded(http.StatusOK, &struct{}{})),
					ghttp.CombineHandlers(ghttp.VerifyRequest("DELETE", "/containers/cnr2"),
						func(http.ResponseWriter, *http.Request) {
							deleteChan <- struct{}{}
						},
						ghttp.RespondWithJSONEncoded(http.StatusOK, &struct{}{})),
				)
			})

			It("destroys any existing containers", func() {
				Eventually(deleteChan).Should(Receive())
				Eventually(deleteChan).Should(Receive())
Пример #21
0
				DisableKeepAlives:   true,
			},
		}, &logger)

		server = ghttp.NewServer()
	})

	AfterEach(func() {
		server.Close()
	})

	Describe("Post/PostCustomized", func() {
		It("makes a POST request with given payload", func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/path"),
					ghttp.VerifyBody([]byte("post-request")),
					ghttp.RespondWith(http.StatusOK, []byte("post-response")),
				),
			)

			url := server.URL() + "/path"

			response, err := httpClient.Post(url, []byte("post-request"))
			Expect(err).ToNot(HaveOccurred())

			defer response.Body.Close()

			responseBody, err := ioutil.ReadAll(response.Body)
			Expect(err).ToNot(HaveOccurred())
			cid := "vm-5678"
			metadata := map[string]interface{}{
				"stuff":  "definitely",
				"thing1": 3563456,
				"thing2": "bloop",
			}

			var metadataInput bosh.MethodArguments
			metadataInput = append(metadataInput, cid)
			metadataInput = append(metadataInput, metadata)

			expectedNodes := helpers.LoadNodes("../spec_assets/dummy_all_nodes_are_vms.json")
			expectedNodesData, err := json.Marshal(expectedNodes)
			Expect(err).ToNot(HaveOccurred())

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/api/common/nodes"),
					ghttp.RespondWith(http.StatusOK, expectedNodesData),
				),
				ghttp.VerifyRequest("PATCH", fmt.Sprintf("/api/common/nodes/%s", id)),
			)

			err = cpi.SetVMMetadata(cpiConfig, metadataInput)
			Expect(err).ToNot(HaveOccurred())

			Expect(server.ReceivedRequests()).To(HaveLen(2))
		})
	})
})
Пример #23
0
				},
			}),
		})
	})

	AfterEach(func() {
		os.RemoveAll(tmpdir)
	})

	JustBeforeEach(func() {
		uploading := make(chan struct{})
		uploadingBits = uploading

		atcServer.RouteToHandler("POST", "/api/v1/pipes",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/api/v1/pipes"),
				ghttp.RespondWithJSONEncoded(http.StatusCreated, atc.Pipe{
					ID:       "some-pipe-id",
					ReadURL:  atcServer.URL() + "/api/v1/pipes/some-pipe-id",
					WriteURL: atcServer.URL() + "/api/v1/pipes/some-pipe-id",
				}),
			),
		)
		atcServer.RouteToHandler("POST", "/api/v1/builds",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/api/v1/builds"),
				VerifyPlan(expectedPlan),
				func(w http.ResponseWriter, r *http.Request) {
					http.SetCookie(w, &http.Cookie{
						Name:    "Some-Cookie",
						Value:   "some-cookie-data",
Пример #24
0
		Context("when the pipeline name is specified", func() {
			var (
				path string
				err  error
			)
			BeforeEach(func() {
				path, err = atc.Routes.CreatePathForRoute(atc.PausePipeline, rata.Params{"pipeline_name": "awesome-pipeline"})
				Expect(err).NotTo(HaveOccurred())
			})

			Context("when the pipeline exists", func() {
				BeforeEach(func() {
					atcServer.AppendHandlers(
						ghttp.CombineHandlers(
							ghttp.VerifyRequest("PUT", path),
							ghttp.RespondWith(http.StatusOK, nil),
						),
					)
				})

				It("pauses the pipeline", func() {
					flyCmd := exec.Command(flyPath, "-t", atcServer.URL(), "pause-pipeline", "-p", "awesome-pipeline")

					sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
					Expect(err).NotTo(HaveOccurred())

					Eventually(sess).Should(gbytes.Say(`paused 'awesome-pipeline'`))

					<-sess.Exited
					Expect(sess.ExitCode()).To(Equal(0))
Пример #25
0
			authServer *ghttp.Server
			token      string
		)

		BeforeEach(func() {
			server = ghttp.NewServer()
			authServer = ghttp.NewServer()
			token = uuid.NewUUID().String()
			responseBody := &token_fetcher.Token{
				AccessToken: token,
				ExpireTime:  20,
			}

			authServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/oauth/token"),
					ghttp.VerifyBasicAuth("some-name", "some-secret"),
					ghttp.VerifyContentType("application/x-www-form-urlencoded; charset=UTF-8"),
					ghttp.VerifyHeader(http.Header{
						"Accept": []string{"application/json; charset=utf-8"},
					}),
					verifyBody("grant_type=client_credentials"),
					ghttp.RespondWithJSONEncoded(http.StatusOK, responseBody),
				))

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/v1/routes"),
					ghttp.VerifyHeader(http.Header{
						"Authorization": []string{"bearer " + token},
					}),
Пример #26
0
					"description":"",
					"authorization_endpoint":"https://login.APISERVER",
					"token_endpoint":"https://uaa.APISERVER",
					"min_cli_version":null,
					"min_recommended_cli_version":null,
					"api_version":"2.59.0",
					"app_ssh_endpoint":"ssh.APISERVER",
					"app_ssh_host_key_fingerprint":"a6:d1:08:0b:b0:cb:9b:5f:c4:ba:44:2a:97:26:19:8a",
					"app_ssh_oauth_client":"ssh-proxy",
					"logging_endpoint":"wss://loggregator.APISERVER",
					"doppler_logging_endpoint":"wss://doppler.APISERVER"
				}`
				response = strings.Replace(response, "APISERVER", serverAPIURL, -1)
				server.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/v2/info"),
						ghttp.RespondWith(http.StatusOK, response),
					),
				)
			})

			AfterEach(func() {
				server.Close()
			})

			It("falls back to http and gives a warning", func() {
				command := exec.Command("cf", "api", server.URL(), "--skip-ssl-validation")
				session, err := Start(command, GinkgoWriter, GinkgoWriter)
				Expect(err).NotTo(HaveOccurred())

				Eventually(session.Out).Should(Say("Setting api endpoint to %s...", server.URL()))
Пример #27
0
		ccServer = ghttp.NewServer()
		configRepo.SetApiEndpoint(ccServer.URL())

		gateway := net.NewCloudControllerGateway(configRepo, time.Now, &testterm.FakeUI{})
		repo = NewCloudControllerServiceKeyRepository(configRepo, gateway)
	})

	AfterEach(func() {
		ccServer.Close()
	})

	Describe("CreateServiceKey", func() {
		It("tries to create the service key", func() {
			ccServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/v2/service_keys"),
					ghttp.RespondWith(http.StatusCreated, nil),
					ghttp.VerifyJSON(`{"service_instance_guid": "fake-instance-guid", "name": "fake-key-name"}`),
				),
			)

			err := repo.CreateServiceKey("fake-instance-guid", "fake-key-name", nil)
			Expect(err).NotTo(HaveOccurred())
			Expect(ccServer.ReceivedRequests()).To(HaveLen(1))
		})

		Context("when the service key exists", func() {
			BeforeEach(func() {
				ccServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("POST", "/v2/service_keys"),
Пример #28
0
	Describe("PerformRequestForJSONResponse()", func() {
		BeforeEach(func() {
			ccServer = ghttp.NewServer()
			config.SetAPIEndpoint(ccServer.URL())
		})

		AfterEach(func() {
			ccServer.Close()
		})

		Context("When CC response with an api error", func() {
			BeforeEach(func() {
				ccServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/v2/some-endpoint"),
						ghttp.VerifyHeader(http.Header{
							"accept": []string{"application/json"},
						}),
						ghttp.RespondWith(http.StatusUnauthorized, `{
  "code": 10003,
  "description": "You are not authorized to perform the requested action",
  "error_code": "CF-NotAuthorized"
}`),
					),
				)
			})

			It("tries to unmarshal error response into provided resource", func() {
				type apiErrResponse struct {
					Code        int    `json:"code,omitempty"`
Пример #29
0
	Describe("containers", func() {
		var (
			flyCmd *exec.Cmd
		)

		BeforeEach(func() {
			atcServer = ghttp.NewServer()
			flyCmd = exec.Command(flyPath, "-t", atcServer.URL(), "containers")
		})

		Context("when containers are returned from the API", func() {
			BeforeEach(func() {
				atcServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/api/v1/containers"),
						ghttp.RespondWithJSONEncoded(200, []atc.Container{
							{
								ID:           "handle-1",
								PipelineName: "pipeline-name",
								Type:         "check",
								Name:         "git-repo",
								BuildID:      0,
								WorkerName:   "worker-name-1",
							},
							{
								ID:           "early-handle",
								PipelineName: "pipeline-name",
								Type:         "get",
								Name:         "git-repo",
								BuildID:      123,
Пример #30
0
		)

		BeforeEach(func() {
			uaaServer = ghttp.NewServer()
			config = testconfig.NewRepository()
			config.SetAuthenticationEndpoint(uaaServer.URL())
			config.SetSSHOAuthClient("ssh-oauth-client")

			gateway = net.NewUAAGateway(config, &testterm.FakeUI{})
			authRepo = NewUAAAuthenticationRepository(gateway, config)

			uaaServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyHeader(http.Header{"authorization": []string{"auth-token"}}),
					ghttp.VerifyRequest("GET", "/oauth/authorize",
						"response_type=code&grant_type=authorization_code&client_id=ssh-oauth-client",
					),
					ghttp.RespondWith(http.StatusFound, ``, http.Header{
						"Location": []string{"https://www.cloudfoundry.example.com?code=F45jH"},
					}),
				),
			)
		})

		AfterEach(func() {
			uaaServer.Close()
		})

		It("requests the one time code", func() {
			_, err := authRepo.Authorize("auth-token")
			Expect(err).NotTo(HaveOccurred())