Ejemplo n.º 1
0
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
}
Ejemplo n.º 2
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`))
			}),
		),
	)
}
Ejemplo n.º 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))
			}),
		),
	)
}
Ejemplo n.º 4
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()))
				Eventually(session.Out).Should(Say("Warning: Insecure http API endpoint detected: secure https API endpoints are recommended"))
Ejemplo n.º 5
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(
						ghttp.VerifyRequest("GET", "/ping"),
Ejemplo n.º 6
0
			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)
				Expect(err).To(MatchError(ContainSubstring("parse")))
			})
		})
Ejemplo n.º 7
0
		})

		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())
			})
		})

		Describe("maintaining presence", func() {
			var cellPresence *models.CellPresence
Ejemplo n.º 8
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))
					Expect(atcServer.ReceivedRequests()).To(HaveLen(1))
Ejemplo n.º 9
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())
			Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
Ejemplo n.º 10
0
		})
	})

	Describe("delete", func() {
		var (
			httpStatusCode              int
			fakeServer                  *ghttp.Server
			fakeServerURL, sanitizedURL string
		)

		BeforeEach(func() {
			httpStatusCode = http.StatusNoContent
			fakeServer = ghttp.NewServer()
			fakeServer.AppendHandlers(ghttp.CombineHandlers(
				ghttp.VerifyRequest("DELETE", "/blobs/path"),
				ghttp.RespondWithPtr(&httpStatusCode, nil),
				ghttp.VerifyBasicAuth("user", "pass"),
			))
			fakeServerURL = fmt.Sprintf("http://%s:%s@%s%s", "user", "pass", fakeServer.Addr(), "/blobs/path")
			sanitizedURL = fmt.Sprintf("http://%s%s", fakeServer.Addr(), "/blobs/path")
		})

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

		It("does a DELETE to the DAV server to delete the file", func() {
			command := exec.Command(davtoolPath, "delete", fakeServerURL)
			session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
			Expect(err).NotTo(HaveOccurred())
Ejemplo n.º 11
0
		const cellAddr = "cell.example.com"
		var stopErr error
		var actualLRP = models.ActualLRP{
			ActualLRPKey:         models.NewActualLRPKey("some-process-guid", 2, "test-domain"),
			ActualLRPInstanceKey: models.NewActualLRPInstanceKey("some-instance-guid", "some-cell-id"),
		}

		JustBeforeEach(func() {
			stopErr = client.StopLRPInstance(actualLRP.ActualLRPKey, actualLRP.ActualLRPInstanceKey)
		})

		Context("when the request is successful", func() {
			BeforeEach(func() {
				fakeServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("POST", "/v1/lrps/some-process-guid/instances/some-instance-guid/stop"),
						ghttp.RespondWith(http.StatusAccepted, ""),
					),
				)
			})

			It("makes the request and does not return an error", func() {
				Expect(stopErr).NotTo(HaveOccurred())
				Expect(fakeServer.ReceivedRequests()).To(HaveLen(1))
			})
		})

		Context("when the request returns 500", func() {
			BeforeEach(func() {
				fakeServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("POST", "/v1/lrps/some-process-guid/instances/some-instance-guid/stop"),
Ejemplo n.º 12
0
				atcServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/api/v1/containers"),
						ghttp.RespondWithJSONEncoded(200, []atc.Container{
							{
								ID:           "handle-1",
								WorkerName:   "worker-name-1",
								PipelineName: "pipeline-name",
								StepType:     "check",
								ResourceName: "git-repo",
							},
							{
								ID:           "early-handle",
								WorkerName:   "worker-name-1",
								PipelineName: "pipeline-name",
								JobName:      "job-name-1",
								BuildName:    "3",
								BuildID:      123,
								StepType:     "get",
								StepName:     "git-repo",
								Attempts:     []int{1, 5},
							},
							{
								ID:           "other-handle",
								WorkerName:   "worker-name-2",
								PipelineName: "pipeline-name",
								JobName:      "job-name-2",
								BuildName:    "2",
								BuildID:      122,
								StepType:     "task",
								StepName:     "unit-tests",
							},
							{
								ID:         "post-handle",
								WorkerName: "worker-name-3",
								BuildID:    142,
								StepType:   "task",
								StepName:   "one-off",
							},
						}),
					),
				)
Ejemplo n.º 13
0
		server.Close()
		Ω(os.Remove(tmpFile.Name())).Should(Succeed())
	})

	It("creates SSH scripts", func() {
		server.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/api/sessions"),
				ghttp.RespondWith(204, ""),
			),
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/api/sessions"),
				ghttp.RespondWith(200, ""),
			),
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/api/server_arrays"),
				ghttp.RespondWith(200, serverArraysResponseBody),
			),
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/api/server_arrays/1/current_instances"),
				ghttp.RespondWith(200, instancesResponseBody),
			),
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/api/servers"),
				ghttp.RespondWith(200, serversResponseBody),
			),
		)
		Ω(main).ShouldNot(Panic())
		Ω(string(written)).Should(Equal(output))
	})

})
Ejemplo n.º 14
0
			fmt.Fprintf(os.Stdout, "server addr is: "+server.Addr())
			slUsername = os.Getenv("SL_USERNAME")
			slAPIKey = os.Getenv("SL_API_KEY")
			client = slclient.NewHttpClient(slUsername, slAPIKey, server.Addr(), "templates", false)
		})

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

		Context("#DoRawHttpRequest", func() {
			Context("when a successful request", func() {
				BeforeEach(func() {
					server.CloseClientConnections()
					server.AppendHandlers(
						ghttp.VerifyRequest("GET", "/test"),
						ghttp.VerifyBasicAuth(slUsername, slAPIKey),
					)
				})

				It("make a request to access /test", func() {
					client.DoRawHttpRequest("test", "GET", bytes.NewBufferString("random text"))
					Ω(err).ShouldNot(HaveOccurred())
					Ω(server.ReceivedRequests()).Should(HaveLen(1))
				})
			})
		})
	})

	Context("when the target HTTP server is not stable", func() {
		BeforeEach(func() {
			os.Setenv("SL_API_RETRY_COUNT", "10")
Ejemplo n.º 15
0
			ccServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/v2/quota_definitions"),
					ghttp.RespondWith(http.StatusOK, `{
						"next_url": "/v2/quota_definitions?page=2",
						"resources": [
							{
								"metadata": { "guid": "my-quota-guid" },
								"entity": {
									"name": "my-remote-quota",
									"memory_limit": 1024,
									"instance_memory_limit": -1,
									"total_routes": 123,
									"total_services": 321,
									"non_basic_services_allowed": true,
									"app_instance_limit": 7,
									"total_reserved_route_ports": 5
								}
							}
						]
					}`),
				),
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/v2/quota_definitions", "page=2"),
					ghttp.RespondWith(http.StatusOK, `{
						"resources": [
							{
								"metadata": { "guid": "my-quota-guid2" },
								"entity": { "name": "my-remote-quota2", "memory_limit": 1024 }
							},
							{
								"metadata": { "guid": "my-quota-guid3" },
								"entity": { "name": "my-remote-quota3", "memory_limit": 1024 }
							}
						]
					}`),
				),
			)
Ejemplo n.º 16
0
		}
	})
	AfterEach(func() {
		wstuncli.Stop()
		wstunsrv.Stop()
		server.Close()
	})

	It("Respects x-host header", func() {
		wstuncli = cliStart("http://localhost:123", `http://127\.0\.0\.[0-9]:[0-9]+`)
		server.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/hello"),
				func(w http.ResponseWriter, req *http.Request) {
					Ω(req.Header.Get("Host")).Should(Equal(""))
					Ω(req.Host).Should(Equal(strings.TrimPrefix(server.URL(), "http://")))
				},
				ghttp.RespondWith(200, `HOSTED`,
					http.Header{"Content-Type": []string{"text/world"}}),
			),
		)

		req, err := http.NewRequest("GET", wstunUrl+"/_token/"+wstunToken+"/hello", nil)
		Ω(err).ShouldNot(HaveOccurred())
		req.Header.Set("X-Host", server.URL())
		resp, err := http.DefaultClient.Do(req)
		Ω(err).ShouldNot(HaveOccurred())
		respBody, err := ioutil.ReadAll(resp.Body)
		Ω(err).ShouldNot(HaveOccurred())
		Ω(string(respBody)).Should(Equal("HOSTED"))
		Ω(resp.Header.Get("Content-Type")).Should(Equal("text/world"))
Ejemplo n.º 17
0
			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"`
					Description string `json:"description,omitempty"`
				}

				errResponse := new(apiErrResponse)
Ejemplo n.º 18
0
		err = os.RemoveAll(outputDir)
		Expect(err).NotTo(HaveOccurred())
	})

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

		atcServer.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/api/v1/pipes"),
				ghttp.RespondWithJSONEncoded(http.StatusCreated, atc.Pipe{
					ID: "some-pipe-id",
				}),
			),
			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:    "/",
Ejemplo n.º 19
0
		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},
					}),
					ghttp.RespondWithJSONEncoded(http.StatusOK, nil),
				),
			)
Ejemplo n.º 20
0
			Expect(fakeServer.ReceivedRequests()).To(HaveLen(4))
		})

		Context("when the root call fails", func() {
			It("returns an error it can't connect to the server", func() {
				fakeServer.Close()
				fakeServer = nil

				_, err := blobStore.List()
				Expect(err).To(HaveOccurred())
			})

			It("returns an error when we fail to retrieve the objects from DAV", func() {
				fakeServer.AppendHandlers(ghttp.CombineHandlers(
					ghttp.VerifyRequest("PROPFIND", "/blobs"),
					ghttp.VerifyHeaderKV("Depth", "1"),
					ghttp.VerifyBasicAuth("user", "pass"),
					ghttp.RespondWith(http.StatusInternalServerError, nil, http.Header{"Content-Type": []string{"application/xml"}}),
				))

				_, err := blobStore.List()
				Expect(err).To(MatchError(ContainSubstring("Internal Server Error")))

				Expect(fakeServer.ReceivedRequests()).To(HaveLen(1))
			})

			It("returns an error when it fails to parse the XML", func() {
				fakeServer.RouteToHandler("PROPFIND", "/blobs", ghttp.CombineHandlers(
					ghttp.VerifyHeaderKV("Depth", "1"),
					ghttp.VerifyBasicAuth("user", "pass"),
					ghttp.RespondWith(207, `<D:bad`, http.Header{"Content-Type": []string{"application/xml"}}),
				))
			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))
		})
	})
})
Ejemplo n.º 22
0
		server.Close()
	})

	Describe("FindProductForSlug", func() {
		var (
			slug = "my-product"
		)
		Context("when the product can be found", func() {
			It("returns the located product", func() {
				response := fmt.Sprintf(`{"id": 3, "slug": "%s"}`, slug)

				server.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", fmt.Sprintf(
							"%s/products/%s",
							apiPrefix,
							slug)),
						ghttp.RespondWith(http.StatusOK, response),
					),
				)

				product, err := client.FindProductForSlug(slug)
				Expect(err).NotTo(HaveOccurred())
				Expect(product.Slug).To(Equal(slug))
			})
		})

		Context("when the server responds with a non-2XX status code", func() {
			It("returns an error", func() {
				server.AppendHandlers(
					ghttp.CombineHandlers(
Ejemplo n.º 23
0
			},
		}, &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())

			Expect(responseBody).To(Equal([]byte("post-response")))
Ejemplo n.º 24
0
	BeforeEach(func() {
		server = ghttp.NewServer()
		f = &Flipkart{
			AffiliateId:   "fk-id",
			AffliateToken: "fk-secret",
			Host:          server.URL()[7:],
			Scheme:        "http",
		}
	})

	Context("TopOffers", func() {
		BeforeEach(func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/affiliate/offers/v1/top/json"),
					ghttp.VerifyHeaderKV("Fk-Affiliate-Id", "fk-id"),
					ghttp.VerifyHeaderKV("Fk-Affiliate-Token", "fk-secret"),
					ghttp.RespondWith(200, topResult),
				))
		})
		It("retrieves the top offers", func() {
			resp, err := f.TopOffers()
			Expect(err).NotTo(HaveOccurred())
			Expect(len(resp.TopOffersList)).To(Equal(14))
		})
	})

	Context("DOTDOffers", func() {
		BeforeEach(func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
Ejemplo n.º 25
0
		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())
		Ω(string(respBody)).Should(Equal("WORLD"))
		Ω(resp.Header.Get("Content-Type")).Should(Equal("text/world"))
		Ω(resp.StatusCode).Should(Equal(200))
Ejemplo n.º 26
0
		client = dotnet.NewClient(logger, serverUri)
		dotNetBackend, _ = backend.NewDotNetBackend(client, logger)
	})

	AfterEach(func() {
		//shut down the server between tests
		if server.HTTPTestServer != nil {
			server.Close()
		}
	})

	Describe("Capacity", func() {
		BeforeEach(func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/api/capacity"),
					ghttp.RespondWith(200, `{"disk_in_bytes":11111,"memory_in_bytes":22222,"max_containers":33333}`),
				),
			)
		})

		It("returns capacity", func() {
			capacity, err := dotNetBackend.Capacity()
			Expect(err).NotTo(HaveOccurred())

			Expect(capacity.DiskInBytes).To(Equal(uint64(11111)))
			Expect(capacity.MemoryInBytes).To(Equal(uint64(22222)))
			Expect(capacity.MaxContainers).To(Equal(uint64(33333)))
		})

		Context("when there is an error making the http connection", func() {
			It("returns an error", func() {
Ejemplo n.º 27
0
		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"),
						ghttp.RespondWith(http.StatusBadRequest, `{"code":360001,"description":"The service key name is taken: exist-service-key"}`),
Ejemplo n.º 28
0
				http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
					w.Write([]byte(`layer-1-data`))
				}),
			),
		)
	}

	Describe("Fetch", func() {
		BeforeEach(func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/v1/repositories/some-repo/images"),
					http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
						w.Header().Set("X-Docker-Token", "token-1,token-2")
						w.Header().Add("X-Docker-Endpoints", endpoint1.HTTPTestServer.Listener.Addr().String())
						w.Header().Add("X-Docker-Endpoints", endpoint2.HTTPTestServer.Listener.Addr().String())
						w.Write([]byte(`[
							{"id": "id-1", "checksum": "sha-1"},
							{"id": "id-2", "checksum": "sha-2"}
						]`))
					}),
				),
			)

			endpoint1.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/v1/repositories/library/some-repo/tags"),
					http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
						w.Write([]byte(`{
							"some-tag": "id-1",
							"some-other-tag": "id-2"
						}`))
Ejemplo n.º 29
0
				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,
								WorkerName:   "worker-name-1",
							},
							{
								ID:           "other-handle",
								PipelineName: "pipeline-name",
								Type:         "task",
								Name:         "unit-tests",
								BuildID:      122,
								WorkerName:   "worker-name-2",
							},
						}),
					),
				)
		ccServer = ghttp.NewServer()
		configRepo = testconfig.NewRepositoryWithDefaults()
		configRepo.SetAPIEndpoint(ccServer.URL())
		gateway := net.NewCloudControllerGateway(configRepo, time.Now, new(terminalfakes.FakeUI), new(tracefakes.FakePrinter), "")
		repo = environmentvariablegroups.NewCloudControllerRepository(configRepo, gateway)
	})

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

	Describe("ListRunning", func() {
		BeforeEach(func() {
			ccServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/v2/config/environment_variable_groups/running"),
					ghttp.RespondWith(http.StatusOK, `{ "abc": 123, "do-re-mi": "fa-sol-la-ti" }`),
				),
			)
		})

		It("lists the environment variables in the running group", func() {
			envVars, err := repo.ListRunning()
			Expect(err).NotTo(HaveOccurred())

			Expect(envVars).To(ConsistOf([]models.EnvironmentVariable{
				{Name: "abc", Value: "123"},
				{Name: "do-re-mi", Value: "fa-sol-la-ti"},
			}))
		})
	})