Beispiel #1
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")),
	)
}
Beispiel #2
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),
	)
}
Beispiel #3
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),
	)
}
		server.Close()
	})

	Context("with an OAuth Token", func() {
		BeforeEach(func() {
			source = Source{
				User:        "******",
				Repository:  "concourse",
				AccessToken: "abc123",
			}

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/repos/concourse/concourse/releases"),
					ghttp.RespondWith(200, "[]"),
					ghttp.VerifyHeaderKV("Authorization", "Bearer abc123"),
				),
			)
		})

		It("sends one", func() {
			_, err := client.ListReleases()
			Ω(err).ShouldNot(HaveOccurred())
		})
	})

	Context("without an OAuth Token", func() {
		BeforeEach(func() {
			source = Source{
				User:       "******",
				Repository: "concourse",
Beispiel #5
0
						Eventually(sess.Out).Should(gbytes.Say("target saved"))

						err = stdin.Close()
						Expect(err).NotTo(HaveOccurred())

						<-sess.Exited
						Expect(sess.ExitCode()).To(Equal(0))
					})

					Describe("running other commands", func() {
						BeforeEach(func() {
							atcServer.AppendHandlers(
								infoHandler(),
								ghttp.CombineHandlers(
									ghttp.VerifyRequest("GET", "/api/v1/pipelines"),
									ghttp.VerifyHeaderKV("Authorization", "Bearer some-entered-token"),
									ghttp.RespondWithJSONEncoded(200, []atc.Pipeline{
										{Name: "pipeline-1"},
									}),
								),
							)
						})

						It("uses the saved token", func() {
							otherCmd := exec.Command(flyPath, "-t", "some-target", "pipelines")

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

							<-sess.Exited
	"github.com/onsi/gomega/ghttp"
)

var _ = Describe("Releases", func() {
	var (
		req                resource.ReleaseRequester
		server             *ghttp.Server
		testRelease        *resource.Release
		testProductFiles   *resource.ProductFiles
		pivotalProductFile resource.ProductFile
		licenseProductFile resource.ProductFile
		eulaMessage        resource.EulaMessage
	)

	verifyHeaders := ghttp.CombineHandlers(
		ghttp.VerifyHeaderKV("Authorization", "Token token"),
		ghttp.VerifyHeaderKV("Content-Type", "application/json"),
		ghttp.VerifyHeaderKV("Accept", "application/json"),
	)

	BeforeEach(func() {
		server = ghttp.NewServer()
		req = resource.NewRequester(server.URL(), "token")

		testRelease = &resource.Release{
			Id:      123,
			Version: "1.1",
			Links: resource.Links{
				"product_files": resource.Link{Url: server.URL() + "/api/v2/products/my-prod/releases/123/product_files"},
			},
		}
Beispiel #7
0
			})

			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,
						ghttp.CombineHandlers(
							ghttp.VerifyHeaderKV(atc.ConfigVersionHeader, "42"),
							func(w http.ResponseWriter, r *http.Request) {
								bodyConfig, state := getConfigAndPausedState(r)
								Ω(state).Should(BeNil())

								receivedConfig := atc.Config{}
								err = yaml.Unmarshal(bodyConfig, &receivedConfig)
								Ω(err).ShouldNot(HaveOccurred())

								Ω(receivedConfig).Should(Equal(config))
							},
						),
					)
				})

				It("parses the config file and sends it to the ATC", func() {
Beispiel #8
0
			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"},
				))
			})
				respBody, ok := response.Result.(io.ReadCloser)
				Expect(ok).To(BeTrue())
				Expect(respBody.Close()).NotTo(HaveOccurred())
			})
		})

		Context("Request Headers", func() {
			BeforeEach(func() {
				atcServer = ghttp.NewServer()

				connection = NewConnection(atcServer.URL(), nil)

				atcServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/api/v1/builds/foo"),
						ghttp.VerifyHeaderKV("Accept-Encoding", "application/banana"),
						ghttp.VerifyHeaderKV("foo", "bar", "baz"),
						ghttp.RespondWithJSONEncoded(http.StatusOK, atc.Build{}),
					),
				)
			})

			It("sets the header and it's values on the request", func() {
				err := connection.Send(Request{
					RequestName: atc.GetBuild,
					Params:      rata.Params{"build_id": "foo"},
					Header: http.Header{
						"Accept-Encoding": {"application/banana"},
						"Foo":             {"bar", "baz"},
					},
				}, &Response{
Beispiel #10
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(
			UserAgent: userAgent,
		}
		client = pivnet.NewClient(newClientConfig, fakeLogger)
	})

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

	It("has authenticated headers for each request", func() {
		response := fmt.Sprintf(`{"releases": [{"version": "1234"}]}`)

		server.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", apiPrefix+"/products/my-product-id/releases"),
				ghttp.VerifyHeaderKV("Authorization", fmt.Sprintf("Token %s", token)),
				ghttp.RespondWith(http.StatusOK, response),
			),
		)

		_, err := client.ProductVersions("my-product-id")
		Expect(err).NotTo(HaveOccurred())
	})

	It("sets custom user agent", func() {
		response := fmt.Sprintf(`{"releases": [{"version": "1234"}]}`)

		server.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", apiPrefix+"/products/my-product-id/releases"),
				ghttp.VerifyHeaderKV("Authorization", fmt.Sprintf("Token %s", token)),
Beispiel #12
0
	"github.com/onsi/gomega/ghttp"
)

var _ = Describe("Releases", func() {
	var (
		req                resource.ReleaseRequester
		server             *ghttp.Server
		testRelease        *resource.Release
		testProductFiles   *resource.ProductFiles
		pivotalProductFile resource.ProductFile
		licenseProductFile resource.ProductFile
		eulaMessage        resource.EulaMessage
	)

	verifyHeaders := ghttp.CombineHandlers(
		ghttp.VerifyHeaderKV("Authorization", "Token token"),
		ghttp.VerifyHeaderKV("Content-Type", "application/json"),
		ghttp.VerifyHeaderKV("Accept", "application/json"),
		ghttp.VerifyHeaderKV("User-Agent", fmt.Sprintf("gopivnet/%s", resource.Version)),
	)

	BeforeEach(func() {
		server = ghttp.NewServer()
		req = resource.NewRequester(server.URL(), "token")

		testRelease = &resource.Release{
			Id:      123,
			Version: "1.1",
			Links: resource.Links{
				"product_files": resource.Link{Url: server.URL() + "/api/v2/products/my-prod/releases/123/product_files"},
			},
			)
			testServer.AppendHandlers(handler)
			testServer.AllowUnhandledRequests = true

			bodyChan = make(chan []byte, 3)

			testS3Server = ghttp.NewServer()

			comparisonFile, err := ioutil.TempFile("", "comparison.csv")
			Expect(err).ToNot(HaveOccurred())

			comparisonFile.WriteString(comparisonCSV)
			comparisonFilePath = comparisonFile.Name()

			bodyTestHandler = ghttp.CombineHandlers(
				ghttp.VerifyHeaderKV("X-Amz-Acl", "public-read"),
				func(rw http.ResponseWriter, req *http.Request) {
					defer GinkgoRecover()
					defer req.Body.Close()
					bodyBytes, err := ioutil.ReadAll(req.Body)
					Expect(err).ToNot(HaveOccurred())
					bodyChan <- bodyBytes
				},
				ghttp.RespondWith(http.StatusOK, nil),
			)
			testS3Server.AppendHandlers(
				bodyTestHandler,
				ghttp.CombineHandlers(
					ghttp.VerifyContentType("image/png"),
					bodyTestHandler,
				),
Beispiel #14
0
		It("Handles a very large request", func() {
			// init and fill a 12MB buffer
			reqSize := 12 * 1024 * 1024 // 12MB
			reqSizeStr := strconv.Itoa(reqSize)
			reqBody := make([]byte, reqSize)
			for i := range reqBody {
				reqBody[i] = byte(i % 256)
			}

			wstuncli = startClient(wstunToken, wstunHost, proxyUrl, server)
			waitConnected(wstuncli)

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/large-request"),
					ghttp.VerifyHeaderKV("Content-Length", reqSizeStr),
					ghttp.RespondWith(200, `WORLD`,
						http.Header{"Content-Type": []string{"text/world"}}),
				),
			)

			resp, err := http.Post(wstunUrl+"/_token/"+wstunToken+"/large-request",
				"text/binary", bytes.NewReader(reqBody))
			Ω(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))
		})
Beispiel #15
0
		var (
			httpStatusCode              int
			fakeServer                  *ghttp.Server
			httpBody                    []byte
			tmpFile                     *os.File
			fakeServerURL, sanitizedURL string
		)

		BeforeEach(func() {
			httpStatusCode = http.StatusCreated
			fakeServer = ghttp.NewServer()
			fakeServer.AppendHandlers(ghttp.CombineHandlers(
				ghttp.VerifyRequest("PUT", "/blobs/path"),
				ghttp.RespondWithPtr(&httpStatusCode, nil),
				ghttp.VerifyBasicAuth("user", "pass"),
				ghttp.VerifyHeaderKV("Content-Length", "18"),
				func(_ http.ResponseWriter, request *http.Request) {
					var err error
					httpBody, err = ioutil.ReadAll(request.Body)
					Expect(err).NotTo(HaveOccurred())
				},
			))

			fakeServerURL = fmt.Sprintf("http://%s:%s@%s%s", "user", "pass", fakeServer.Addr(), "/blobs/path")
			sanitizedURL = fmt.Sprintf("http://%s%s", fakeServer.Addr(), "/blobs/path")

			var err error
			tmpFile, err = ioutil.TempFile(os.TempDir(), "fileToUpload")
			Expect(err).NotTo(HaveOccurred())

			tmpFile.Write([]byte("some-file-contents"))
Beispiel #16
0
						Data: []byte("hello"),
					}.Write(w)

					flusher.Flush()

					Event{
						ID:   "2",
						Data: []byte("hello again"),
					}.Write(w)

					flusher.Flush()

					<-closeNotify
				},
				ghttp.CombineHandlers(
					ghttp.VerifyHeaderKV("Last-Event-ID", "2"),
					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")
						w.Header().Add("Connection", "keep-alive")

						w.WriteHeader(http.StatusOK)

						flusher.Flush()

						Event{
							ID:   "3",
							Data: []byte("welcome back"),
						}.Write(w)
Beispiel #17
0
						<D:resourcetype>
						  <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"}}),
			))
Beispiel #18
0
			defer server.Close()

			// construct list of verifiers
			url := regexp.MustCompile(`https?://[^/]+(/[^?]+)\??(.*)`).
				FindStringSubmatch(testCase.RR.URI)
			//fmt.Fprintf(os.Stderr, "URL: %#v\n", url)
			handlers := []http.HandlerFunc{
				ghttp.VerifyRequest(testCase.RR.Verb, url[1], url[2]),
			}
			if len(testCase.RR.ReqBody) > 0 {
				handlers = append(handlers,
					ghttp.VerifyJSON(testCase.RR.ReqBody))
			}
			for k := range testCase.RR.ReqHeader {
				handlers = append(handlers,
					ghttp.VerifyHeaderKV(k, testCase.RR.ReqHeader.Get(k)))
			}
			respHeader := make(http.Header)
			for k, v := range testCase.RR.RespHeader {
				respHeader[k] = v
			}
			handlers = append(handlers,
				ghttp.RespondWith(testCase.RR.Status, testCase.RR.RespBody,
					respHeader))
			server.AppendHandlers(ghttp.CombineHandlers(handlers...))

			os.Args = append([]string{
				"rsc", "--noAuth", "--dump", "debug",
				"--host", strings.TrimPrefix(server.URL(), "http://")},
				testCase.CmdArgs...)
			//fmt.Fprintf(os.Stderr, "testing \"%s\"\n", strings.Join(os.Args, `" "`))
					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)
			token string
		)

		BeforeEach(func() {
			token = "1234-abcd"
		})

		Context("Success", func() {
			It("follows redirects", func() {
				header := http.Header{}
				header.Add("Location", apiAddress+"/some-redirect-link")

				server.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("POST", "/the-first-post", ""),
						ghttp.VerifyHeaderKV("Authorization", fmt.Sprintf("Token %s", token)),
						ghttp.RespondWith(http.StatusFound, nil, header),
					),
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/some-redirect-link"),
						ghttp.RespondWith(http.StatusOK, make([]byte, 10, 14)),
					),
				)

				fileNames := map[string]string{
					"the-first-post": apiAddress + "/the-first-post",
				}

				err := downloader.Download(dir, fileNames, token)
				Expect(err).NotTo(HaveOccurred())
			})