})

	Describe("listing", func() {
		BeforeEach(func() {
			do.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/v2/actions"),
					ghttp.RespondWith(http.StatusOK, doGetActions),
				),
			)
		})

		It("lists all actions", func() {
			resp, err := client.Get("/actions")
			Expect(err).NotTo(HaveOccurred())
			Ω(do.ReceivedRequests()).Should(HaveLen(1))
			var actions map[string]interface{}
			err = json.Unmarshal([]byte(doGetActions), &actions)
			Expect(err).NotTo(HaveOccurred())
			expected, err := json.Marshal(actions["actions"])
			Expect(err).NotTo(HaveOccurred())
			Ω(resp.Body).Should(MatchJSON(expected))
		})
	})

	Describe("listing empty", func() {
		BeforeEach(func() {
			do.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/v2/actions"),
					ghttp.RespondWith(http.StatusOK, doGetEmpty),
Exemplo n.º 2
0
				err := bbsClient.StartActualLRP(&lrpKey, &instanceKey, &netInfo)
				Expect(err).NotTo(HaveOccurred())

				actualLRPGroup, err := bbsClient.ActualLRPGroupByProcessGuidAndIndex(lrpKey.ProcessGuid, int(lrpKey.Index))
				Expect(err).NotTo(HaveOccurred())
				runningLRP = actualLRPGroup.GetInstance()
			})

			It("should destroy the container", func() {
				Eventually(getActualLRPGroups).Should(HaveLen(1))
				err := bbsClient.RetireActualLRP(&runningLRP.ActualLRPKey)
				Expect(err).NotTo(HaveOccurred())

				findDestroyRequest := func() bool {
					for _, req := range fakeGarden.ReceivedRequests() {
						if req.URL.Path == expectedDestroyRoute {
							return true
						}
					}
					return false
				}

				Eventually(findDestroyRequest).Should(BeTrue())
			})
		})

		Describe("cancelling tasks", func() {
			const taskGuid = "some-task-guid"
			const expectedDeleteRoute = "/containers/" + taskGuid
Exemplo n.º 3
0
		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"}`),
					),
				)
			})

			It("returns a ModelAlreadyExistsError", func() {
				err := repo.CreateServiceKey("fake-instance-guid", "exist-service-key", nil)
				Expect(err).To(BeAssignableToTypeOf(&errors.ModelAlreadyExistsError{}))
Exemplo n.º 4
0
		Expect(err).NotTo(HaveOccurred())
		Expect(proxyHostKey.PublicKey().Marshal()).To(Equal(handshakeHostKey.Marshal()))
	})

	Describe("attempting authentication without a realm", func() {
		BeforeEach(func() {
			clientConfig = &ssh.ClientConfig{
				User: processGuid + "/99",
				Auth: []ssh.AuthMethod{ssh.Password(diegoCredentials)},
			}
		})

		It("fails the authentication", func() {
			_, err := ssh.Dial("tcp", address, clientConfig)
			Expect(err).To(MatchError(ContainSubstring("ssh: handshake failed")))
			Expect(fakeBBS.ReceivedRequests()).To(HaveLen(0))
		})
	})

	Describe("attempting authentication with an unknown realm", func() {
		BeforeEach(func() {
			clientConfig = &ssh.ClientConfig{
				User: "******" + processGuid + "/99",
				Auth: []ssh.AuthMethod{ssh.Password(diegoCredentials)},
			}
		})

		It("fails the authentication", func() {
			_, err := ssh.Dial("tcp", address, clientConfig)
			Expect(err).To(MatchError(ContainSubstring("ssh: handshake failed")))
			Expect(fakeBBS.ReceivedRequests()).To(HaveLen(0))
Exemplo n.º 5
0
						{
							"route":    "zak.com",
							"port":     3,
							"ip":       "4",
							"ttl":      0,
							"log_guid": "",
						},
					}),
					ghttp.RespondWithJSONEncoded(http.StatusOK, nil),
				),
			)

			session := routeRegistrar(command...)

			Eventually(session, "2s").Should(Exit(0))
			Expect(server.ReceivedRequests()).To(HaveLen(1))
		})

		It("registers multiple routes to the routing api", func() {
			routes := `[{"route":"zak.com","port":0,"ip": "","ttl":5,"log_guid":"yo"},{"route":"jak.com","port":8,"ip":"11","ttl":0}]`
			command := buildCommand("register", flags, []string{routes})
			server.SetHandler(0,
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/v1/routes"),
					ghttp.VerifyJSONRepresenting([]map[string]interface{}{
						{
							"route":    "zak.com",
							"port":     0,
							"ip":       "",
							"ttl":      5,
							"log_guid": "yo",
				err := json.Unmarshal(jsonInput, &extInput)
				Expect(err).ToNot(HaveOccurred())

				expectedNodes := helpers.LoadNodes("../spec_assets/dummy_attached_disk_response.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),
					),
				)

				err = DetachDisk(cpiConfig, extInput)
				Expect(err).To(MatchError("Disk: valid_disk_cid_1 is detached\n"))
				Expect(len(server.ReceivedRequests())).To(Equal(1))
			})
		})

		Context("given a disk that is attached", func() {
			Context("when given a vm cid that the disk does not belong to", func() {
				It("returns an error", func() {
					jsonInput := []byte(`[
							"invalid_vm_cid_2",
							"valid_disk_cid_2"
						]`)
					var extInput bosh.MethodArguments
					err := json.Unmarshal(jsonInput, &extInput)
					Expect(err).ToNot(HaveOccurred())

					expectedNodes := helpers.LoadNodes("../spec_assets/dummy_attached_disk_response.json")
Exemplo n.º 7
0
						ghttp.VerifyRequest("GET", "/v2/stacks", "q=name%3Alinux"),
						ghttp.RespondWith(http.StatusOK, `{
							"resources": [
								{
									"metadata": { "guid": "custom-linux-guid" },
									"entity": { "name": "custom-linux" }
								}
							]
						}`),
					),
				)
			})

			It("tries to find the stack", func() {
				repo.FindByName("linux")
				Expect(testServer.ReceivedRequests()).To(HaveLen(1))
			})

			It("returns the stack", func() {
				stack, err := repo.FindByName("linux")
				Expect(err).NotTo(HaveOccurred())
				Expect(stack).To(Equal(models.Stack{
					Name: "custom-linux",
					GUID: "custom-linux-guid",
				}))
			})
		})

		Context("when the stack cannot be found", func() {
			BeforeEach(func() {
				testServer.AppendHandlers(
			})
		})

		Context("as any other node", func() {
			BeforeEach(func() {
				node = newNode(func() {
					ranThing("A")
				}, func() {
					ranThing("B")
				})

				outcome = node.Run(2, 3, server.URL())
			})

			It("should run A, and not run B", func() {
				Ω(thingsThatRan()).Should(Equal([]string{"A"}))
			})

			It("should not talk to the server", func() {
				Ω(server.ReceivedRequests()).Should(BeEmpty())
			})

			It("should report success", func() {
				Ω(outcome).Should(BeTrue())
				Ω(node.Passed()).Should(BeTrue())
				Ω(node.Summary().State).Should(Equal(types.SpecStatePassed))
			})
		})
	})
})
				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))
				})
			})

			Context("when connecting to an insecure registry", func() {
				It("creates a registry session for the given repo", func() {
					session, err := sessionFactory.MakeSession(registryHost+"/lattice-mappppppppppppappapapa", true)
					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))
				})
			})
Exemplo n.º 10
0
			addBackendRoute("/foo", "backend", "prefix")
			reloadRoutes()
		})

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

		It("should pass through most http headers to the backend", func() {
			resp := routerRequestWithHeaders("/foo", map[string]string{
				"Foo":        "bar",
				"User-Agent": "Router test suite 2.7182",
			})
			Expect(resp.StatusCode).To(Equal(200))

			Expect(recorder.ReceivedRequests()).To(HaveLen(1))
			beReq := recorder.ReceivedRequests()[0]
			Expect(beReq.Header.Get("Foo")).To(Equal("bar"))
			Expect(beReq.Header.Get("User-Agent")).To(Equal("Router test suite 2.7182"))
		})

		It("should set the Host header to the backend hostname", func() {
			resp := routerRequestWithHeaders("/foo", map[string]string{
				"Host": "www.example.com",
			})
			Expect(resp.StatusCode).To(Equal(200))

			Expect(recorder.ReceivedRequests()).To(HaveLen(1))
			beReq := recorder.ReceivedRequests()[0]
			Expect(beReq.Host).To(Equal(recorderURL.Host))
		})
Exemplo n.º 11
0
		AfterEach(func() {
			ccServer.Close()
		})

		Context("when given a non-zero positive limit", func() {
			It("should return no more than the limit number of organizations", func() {
				orgs, err := repo.ListOrgs(2)
				Expect(err).NotTo(HaveOccurred())
				Expect(len(orgs)).To(Equal(2))
			})

			It("should not make more requests than necessary to retrieve the requested number of orgs", func() {
				_, err := repo.ListOrgs(2)
				Expect(err).NotTo(HaveOccurred())
				Expect(ccServer.ReceivedRequests()).Should(HaveLen(1))
			})
		})

		Context("when given a zero limit", func() {
			It("should return all organizations", func() {
				orgs, err := repo.ListOrgs(0)
				Expect(err).NotTo(HaveOccurred())
				Expect(len(orgs)).To(Equal(3))
			})
		})
	})

	Describe(".GetManyOrgsByGuid", func() {
		It("requests each org", func() {
			firstOrgRequest := testapi.NewCloudControllerTestRequest(testnet.TestRequest{
Exemplo n.º 12
0
					})
				})
			})

			Context("and the engine returns no build", func() {
				BeforeEach(func() {
					fakeEngine.LookupBuildReturns(nil, errors.New("oh no!"))
				})

				It("returns 500", func() {
					Ω(response.StatusCode).Should(Equal(http.StatusInternalServerError))
				})
			})
		})

		Context("when not authenticated", func() {
			BeforeEach(func() {
				authValidator.IsAuthenticatedReturns(false)
			})

			It("returns 401", func() {
				Ω(response.StatusCode).Should(Equal(http.StatusUnauthorized))
			})

			It("does not abort the build", func() {
				Ω(abortTarget.ReceivedRequests()).Should(BeEmpty())
			})
		})
	})
})
			process = ginkgomon.Invoke(runner)
		})

		AfterEach(func() {
			ginkgomon.Interrupt(process)
			testServer.Close()
			testS3Server.Close()
			close(bodyChan)
			err := os.Remove(comparisonFilePath)
			Expect(err).ToNot(HaveOccurred())
		})

		It("ramps up throughput over multiple tests", func() {
			Eventually(process.Wait(), "5s").Should(Receive())
			Expect(runner.ExitCode()).To(Equal(0))
			Expect(testServer.ReceivedRequests()).To(HaveLen(24))
		})

		Context("when cpu monitor server is configured", func() {
			var (
				cpumonitorServer *ghttp.Server
			)
			BeforeEach(func() {
				cpumonitorServer = ghttp.NewServer()

				header := make(http.Header)
				header.Add("Content-Type", "application/json")

				cpumonitorServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/start"),
Exemplo n.º 14
0
					ghttp.VerifyJSON(requestJSON("disaster")),
					ghttp.RespondWith(200, ""),
				),
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/api-token"),
					ghttp.VerifyJSON(requestJSON("disaster")),
					ghttp.RespondWith(200, ""),
				),
			)
		})

		It("tries the next collector", func() {
			err := errors.New("disaster")
			client.Notify("holler.example.failed", err, data)

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

	Context("when an unexpected error occurs", func() {
		Context("when it is a transport error", func() {
			BeforeEach(func() {
				collector.Close()
				collector = nil

				otherCollector.Close()
				otherCollector = nil
			})

			It("logs the error", func() {
				err := errors.New("disaster")
		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)
				}
				metrics.Close()
				Expect(metrics.Success * 100).To(BeNumerically("==", 0))
			})
		})
	})

	Context("when runs (until the deployment is finished or error rate > 50%)", func() {
		var attacker *vegeta.Attacker
		var resultChannel <-chan *vegeta.Result
Exemplo n.º 16
0
			reloadRoutes()
		})
		AfterEach(func() {
			root.Close()
			recorder.Close()
		})

		It("should not be redirected by our simple test backend", func() {
			resp := routerRequest("//")
			Expect(readBody(resp)).To(Equal("fallthrough"))
		})

		It("should not be redirected by our recorder backend", func() {
			resp := routerRequest("/foo/bar/baz//qux")
			Expect(resp.StatusCode).To(Equal(200))
			Expect(recorder.ReceivedRequests()).To(HaveLen(1))
			Expect(recorder.ReceivedRequests()[0].URL.Path).To(Equal("/foo/bar/baz//qux"))
		})

		It("should collapse double slashes when looking up route, but pass request as-is", func() {
			resp := routerRequest("/foo//bar")
			Expect(resp.StatusCode).To(Equal(200))
			Expect(recorder.ReceivedRequests()).To(HaveLen(1))
			Expect(recorder.ReceivedRequests()[0].URL.Path).To(Equal("/foo//bar"))
		})
	})

	Describe("special characters in paths", func() {
		var recorder *ghttp.Server

		BeforeEach(func() {
Exemplo n.º 17
0
	})

	Context("GetProduct", func() {
		It("return an error if the token is not valid", func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/api/v2/products/my-prod/releases"),
					verifyHeaders,
					ghttp.RespondWith(http.StatusUnauthorized, ""),
				),
			)

			_, err := req.GetProduct("my-prod")
			Expect(err).To(HaveOccurred())

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

		It("returns an error if the response is not valid", func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/api/v2/products/my-prod/releases"),
					verifyHeaders,
					ghttp.RespondWith(http.StatusOK, ""),
				),
			)

			_, err := req.GetProduct("my-prod")
			Expect(err).To(HaveOccurred())

			Expect(server.ReceivedRequests()).To(HaveLen(1))
Exemplo n.º 18
0
					Expect(response.StatusCode).To(Equal(http.StatusNotFound))
				})
			})

			Context("when calling the database fails", func() {
				BeforeEach(func() {
					buildsDB.GetBuildReturns(db.Build{}, false, errors.New("nope"))
				})

				It("returns Internal Server Error", func() {
					Expect(response.StatusCode).To(Equal(http.StatusInternalServerError))
				})
			})
		})

		Context("when not authenticated", func() {
			BeforeEach(func() {
				authValidator.IsAuthenticatedReturns(false)
			})

			It("returns 401", func() {
				Expect(response.StatusCode).To(Equal(http.StatusUnauthorized))
			})

			It("does not abort the build", func() {
				Expect(abortTarget.ReceivedRequests()).To(BeEmpty())
			})
		})
	})
})
										ghttp.VerifyRequest("GET", tarballUrl.Path),
										ghttp.RespondWith(http.StatusOK, "source-tar-file-contents"),
									),
								)
							})

							It("succeeds", func() {
								inResponse, inErr = command.Run(destDir, inRequest)

								Expect(inErr).ToNot(HaveOccurred())
							})

							It("downloads the source tarball", func() {
								inResponse, inErr = command.Run(destDir, inRequest)

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

							It("saves the source tarball in the destination directory", func() {
								inResponse, inErr = command.Run(destDir, inRequest)

								fileContents, err := ioutil.ReadFile(filepath.Join(destDir, "source.tar.gz"))
								fContents := string(fileContents)
								Expect(err).NotTo(HaveOccurred())
								Expect(fContents).To(Equal("source-tar-file-contents"))
							})
						})

						Context("when downloading the tarball fails", func() {
							BeforeEach(func() {
								githubServer.AppendHandlers(
Exemplo n.º 20
0
						ghttp.VerifyJSON(`
							{
								"domain_guid":"my-domain-guid",
								"space_guid":"my-space-guid"
							}
						`),
						ghttp.VerifyHeader(http.Header{
							"accept": []string{"application/json"},
						}),
					),
				)
			})

			It("tries to create a route", func() {
				repo.CreateInSpace("", "", "my-domain-guid", "my-space-guid", 0, false)
				Expect(ccServer.ReceivedRequests()).To(HaveLen(1))
			})

			Context("when creating the route succeeds", func() {
				BeforeEach(func() {
					h := ccServer.GetHandler(0)
					ccServer.SetHandler(0, ghttp.CombineHandlers(
						h,
						ghttp.RespondWith(http.StatusCreated, `
								{
									"metadata": { "guid": "my-route-guid" },
									"entity": { "host": "my-cool-app" }
								}
							`),
					))
				})
Exemplo n.º 21
0
			BeforeEach(func() {
				ccServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/v2/organizations/org-guid/managers"),
						ghttp.VerifyHeader(http.Header{
							"accept": []string{"application/json"},
						}),
						ghttp.RespondWith(http.StatusOK, `{"resources":[]}`),
					),
				)
			})

			It("makes a request to CC", func() {
				_, err := client.ListUsersInOrgForRole("org-guid", models.ORG_MANAGER)
				Expect(err).NotTo(HaveOccurred())
				Expect(ccServer.ReceivedRequests()).To(HaveLen(1))
			})

			It("returns no users", func() {
				users, err := client.ListUsersInOrgForRole("org-guid", models.ORG_MANAGER)
				Expect(err).NotTo(HaveOccurred())
				Expect(len(users)).To(Equal(0))
			})
		})

		Context("when there are users in the given org with the given role", func() {
			BeforeEach(func() {
				ccServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/v2/organizations/org-guid/managers"),
						ghttp.VerifyHeader(http.Header{
Exemplo n.º 22
0
				Expect(thirdTime.Sub(secondTime)).To(BeNumerically(">", 75*time.Millisecond))
			})
		})

		Context("uploading the file, when the job fails", func() {
			BeforeEach(func() {
				postStatusCode = http.StatusCreated
				postResponseBody = pollingResponseBody("my-job-guid", "queued", fakeCloudController.URL())
				fakeCloudController.AppendHandlers(
					verifyPollingRequest("my-job-guid", "queued", timeClicker),
					verifyPollingRequest("my-job-guid", "failed", timeClicker),
				)
			})

			It("stops polling after the first fail", func() {
				Expect(fakeCloudController.ReceivedRequests()).To(HaveLen(3))

				Expect(outgoingResponse.Code).To(Equal(http.StatusInternalServerError))
			})
		})

		Context("uploading the file, when the inbound upload request is missing content length", func() {
			BeforeEach(func() {
				incomingRequest.ContentLength = -1
			})

			It("does not make the request to CC", func() {
				Expect(fakeCloudController.ReceivedRequests()).To(HaveLen(0))
			})

			It("responds with 411", func() {
Exemplo n.º 23
0
		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(
				ghttp.RespondWith(200, `{`, http.Header{"Content-Type": []string{"application/json"}}),
			))

			_, err := proxyConfReader.ProxyConf()
			Expect(err).To(MatchError("unexpected end of JSON input"))

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

		It("should return an empty ProxyConf on 404", func() {
			fakeServer.RouteToHandler("GET", "/pc.json", ghttp.CombineHandlers(
Exemplo n.º 24
0
					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"},
				))
			})

			It("dumps all the http requests and responses for logging", func() {
				var stdout *bytes.Buffer
				stdout = bytes.NewBuffer([]byte{})
				trace.SetStdout(stdout)

				trace.NewLogger("true")
				runCommand()

				result, err := ioutil.ReadAll(stdout)
				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))
		})
	})
})
		var uaaServer *ghttp.Server
		BeforeEach(func() {
			oauthServer = CreateOAuthServer()
			uaaServer = CreateUaaProtectedServer(manifestYaml, deployments, oauthServer.URL())
		})
		AfterEach(func() {
			uaaServer.Close()
			oauthServer.Close()
		})

		It("should work", func() {
			u, _ := url.Parse(uaaServer.URL())
			u.User = url.UserPassword("director", "deadbeef")
			session, outputDir = StartGeneratorWithURL(u.String())
			Eventually(session).Should(gexec.Exit(0))
			Expect(oauthServer.ReceivedRequests()).Should(HaveLen(1))
			Expect(uaaServer.ReceivedRequests()).Should(HaveLen(3))
		})
	})

	Describe("Success scenarios", func() {
		Context("when a CF manifest is supplied", func() {
			It("should work", func() {
				session, outputDir = StartGeneratorWithManifest(manifestYaml)
				Eventually(session).Should(gexec.Exit(0))
				content, err := ioutil.ReadFile(path.Join(outputDir, "install.bat"))
				Expect(err).NotTo(HaveOccurred())
				script = strings.TrimSpace(string(content))

				expectedContent := ExpectedContent(models.InstallerArguments{
					ConsulRequireSSL: true,
Exemplo n.º 27
0
							body, err := ioutil.ReadAll(r.Body)
							Ω(err).ShouldNot(HaveOccurred())

							Ω(string(body)).Should(Equal("chunk-1chunk-2"))
						},
					),
				)
			})

			It("tells garden.to stream, and then streams the content as a series of chunks", func() {
				buffer := bytes.NewBufferString("chunk-1chunk-2")

				err := connection.StreamIn("foo-handle", garden.StreamInSpec{User: "******", Path: "/bar", TarStream: buffer})
				Ω(err).ShouldNot(HaveOccurred())

				Ω(server.ReceivedRequests()).Should(HaveLen(1))
			})
		})

		Context("when streaming in returns an error response", func() {
			BeforeEach(func() {
				server.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("PUT", "/containers/foo-handle/files", "user=bob&destination=%2Fbar"),
						ghttp.RespondWith(http.StatusInternalServerError, "no."),
					),
				)
			})

			It("returns an error on close", func() {
				buffer := bytes.NewBufferString("chunk-1chunk-2")
Exemplo n.º 28
0
					)

					stdin, err := flyCmd.StdinPipe()
					Ω(err).ShouldNot(HaveOccurred())

					sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
					Ω(err).ShouldNot(HaveOccurred())

					Eventually(sess).Should(gbytes.Say(`apply configuration\? \(y/n\): `))
					fmt.Fprintln(stdin, "y")
					Eventually(sess).Should(gbytes.Say("configuration updated"))

					<-sess.Exited
					Ω(sess.ExitCode()).Should(Equal(0))

					Ω(atcServer.ReceivedRequests()).Should(HaveLen(2))
				})
			})
		})

		Describe("setting", func() {
			var (
				changedConfig atc.Config

				payload    []byte
				configFile *os.File
			)

			BeforeEach(func() {
				var err error
Exemplo n.º 29
0
							ghttp.RespondWith(200, `{"error":{},"desired_lrp_scheduling_infos":	[]}`),
						)

						fakeBBS.RouteToHandler("POST", "/v1/domains/upsert",
							ghttp.RespondWith(200, `{}`),
						)

						fakeBBS.RouteToHandler("POST", "/v1/desired_lrp/desire",
							ghttp.RespondWith(200, `{}`),
						)
					})

					It("completes the tasks and sets the state to failed", func() {
						var request *http.Request
						Eventually(func() *http.Request {
							for _, r := range fakeCC.ReceivedRequests() {
								if r.URL.Path == "/internal/v3/tasks/task-guid-1/completed" {
									request = r
									return r
								}
							}
							return nil
						}, 2*domainTTL).ShouldNot(BeNil())
					})
				})

				Context("The BBS has a task, but the CC does not", func() {
					BeforeEach(func() {
						fakeCC.RouteToHandler("GET", "/internal/v3/bulk/task_states",
							ghttp.RespondWith(200, `{ "token": {}, "task_states": [] }`),
						)
			BeforeEach(func() {
				config.RequestPayload = nil
			})

			It("should not try to marshal", func() {
				err := jsonClient.BuildAndDo(config)
				Expect(err).NotTo(HaveOccurred())

				Expect(marshaler.MarshalCallCount()).To(Equal(0))
			})

			It("should not set header content type to application json", func() {
				err := jsonClient.BuildAndDo(config)
				Expect(err).NotTo(HaveOccurred())

				requests := server.ReceivedRequests()
				Expect(requests).Should(HaveLen(1))
				Expect(requests[0].Header["Content-Type"]).To(BeEmpty())
			})
		})

		It("performs the request using the JSON representation of the request payload", func() {
			err := jsonClient.BuildAndDo(config)
			Expect(err).NotTo(HaveOccurred())

			requests := server.ReceivedRequests()
			Expect(requests).Should(HaveLen(1))
			Expect(requests[0].Method).To(Equal("POST"))
			Expect(requests[0].URL.Path).To(Equal("/some/path"))
			Expect(requests[0].Header["Content-Type"][0]).To(Equal("application/json"))
		})