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
}
func Create401Server() *ghttp.Server {
	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments"),
			ghttp.RespondWith(401, "Not authorized"),
		),
	)

	return server
}
Ejemplo n.º 4
0
func startRecordingServer(tls bool) (server *ghttp.Server) {
	if tls {
		server = ghttp.NewTLSServer()
	} else {
		server = ghttp.NewServer()
	}

	server.AllowUnhandledRequests = true
	server.UnhandledRequestStatusCode = http.StatusOK
	return server
}
func SetUp(cpiRequestType string) (*ghttp.Server, *strings.Reader, config.Cpi, bosh.CpiRequest) {

	var err error
	server := ghttp.NewServer()
	jsonReader := strings.NewReader(fmt.Sprintf(`{"api_url":"%s", "agent":{"blobstore": {"provider":"local","some": "options"}, "mbus":"localhost"}, "max_reserve_node_attempts":1}`, server.URL()))
	request := bosh.CpiRequest{Method: cpiRequestType}
	cpiConfig, err := config.New(jsonReader, request)
	Expect(err).ToNot(HaveOccurred())

	return server, jsonReader, cpiConfig, request
}
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
}
Ejemplo n.º 7
0
// NewTestEnvironment creates and configures a new test environment with a
// ghttp test server along with a PagerDuty client to talk to the server. Tests
// should register handlers on the server which provide mock responses for the
// API method being tested.
func NewTestEnvironment() *TestEnvironment {
	server := ghttp.NewServer()

	// PagerDuty client configured to use the test server
	client := NewClient(nil, subdomain, apiKey)
	url, _ := url.Parse(server.URL())
	client.BaseURL = url
	client.EventsURL = url

	return &TestEnvironment{
		Server: server,
		Client: client,
	}
}
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
}
Ejemplo n.º 9
0
	. "github.com/vito/warden-docker/container_pool/repository_fetcher"
	"github.com/vito/warden-docker/fake_graph"
)

var _ = Describe("RepositoryFetcher", func() {
	var graph *fake_graph.FakeGraph
	var fetcher RepositoryFetcher

	var server *ghttp.Server
	var endpoint1 *ghttp.Server
	var endpoint2 *ghttp.Server

	BeforeEach(func() {
		graph = fake_graph.New()

		server = ghttp.NewServer()

		endpoint1 = ghttp.NewServer()
		endpoint2 = ghttp.NewServer()

		registry, err := registry.NewRegistry(nil, nil, server.URL()+"/v1/")
		Ω(err).ShouldNot(HaveOccurred())

		fetcher = New(registry, graph)
	})

	setupSuccessfulFetch := func(endpoint *ghttp.Server) {
		endpoint.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/v1/images/layer-3/json"),
				http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
Ejemplo n.º 10
0
	"github.com/cloudfoundry-incubator/ltc/droplet_runner"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/ghttp"
)

var _ = Describe("HTTPProxyConfReader", func() {
	var (
		proxyConfReader *droplet_runner.HTTPProxyConfReader
		fakeServer      *ghttp.Server
		badURL          string
	)

	BeforeEach(func() {
		fakeServer = ghttp.NewServer()

		badServer := ghttp.NewServer()
		badURL = badServer.URL()
		badServer.Close()

		proxyConfReader = &droplet_runner.HTTPProxyConfReader{
			URL: fakeServer.URL() + "/pc.json",
		}
	})

	AfterEach(func() {
		if fakeServer != nil {
			fakeServer.Close()
		}
	})
Ejemplo n.º 11
0
		uaaPassword                 string
		uaaUsername                 string
		allowedCiphers              string
		allowedMACs                 string
		allowedKeyExchanges         string
		expectedGetActualLRPRequest *models.ActualLRPGroupByProcessGuidAndIndexRequest
		actualLRPGroupResponse      *models.ActualLRPGroupResponse
		getDesiredLRPRequest        *models.DesiredLRPByProcessGuidRequest
		desiredLRPResponse          *models.DesiredLRPResponse

		processGuid  string
		clientConfig *ssh.ClientConfig
	)

	BeforeEach(func() {
		fakeBBS = ghttp.NewServer()
		fakeUAA = ghttp.NewTLSServer()
		fakeCC = ghttp.NewTLSServer()

		privateKey, err := ssh.ParsePrivateKey([]byte(hostKeyPem))
		Expect(err).NotTo(HaveOccurred())
		hostKeyFingerprint = helpers.MD5Fingerprint(privateKey.PublicKey())

		address = fmt.Sprintf("127.0.0.1:%d", sshProxyPort)
		bbsAddress = fakeBBS.URL()
		ccAPIURL = fakeCC.URL()
		diegoCredentials = "some-creds"
		enableCFAuth = true
		enableDiegoAuth = true
		hostKey = hostKeyPem
		skipCertVerify = true
Ejemplo n.º 12
0
		"http",
	)

	etcdRunner.Start()
	consulRunner.Start()

	bbsAddress := fmt.Sprintf("127.0.0.1:%d", 13000+GinkgoParallelNode())

	bbsURL = &url.URL{
		Scheme: "http",
		Host:   bbsAddress,
	}

	bbsClient = bbs.NewClient(bbsURL.String())

	auctioneerServer = ghttp.NewServer()
	auctioneerServer.UnhandledRequestStatusCode = http.StatusAccepted
	auctioneerServer.AllowUnhandledRequests = true

	etcdUrl := fmt.Sprintf("http://127.0.0.1:%d", etcdPort)
	bbsArgs = bbstestrunner.Args{
		Address:           bbsAddress,
		AdvertiseURL:      bbsURL.String(),
		AuctioneerAddress: auctioneerServer.URL(),
		EtcdCluster:       etcdUrl,
		ConsulCluster:     consulRunner.ConsulCluster(),

		EncryptionKeys: []string{"label:key"},
		ActiveKeyLabel: "label",
	}
})
Ejemplo n.º 13
0
	var (
		testServer *ghttp.Server
		configRepo coreconfig.ReadWriter
		repo       StackRepository
	)

	BeforeEach(func() {
		configRepo = testconfig.NewRepositoryWithDefaults()
		configRepo.SetAccessToken("BEARER my_access_token")

		gateway := net.NewCloudControllerGateway(configRepo, time.Now, new(terminalfakes.FakeUI), new(tracefakes.FakePrinter))
		repo = NewCloudControllerStackRepository(configRepo, gateway)
	})

	BeforeEach(func() {
		testServer = ghttp.NewServer()
		configRepo.SetAPIEndpoint(testServer.URL())
	})

	AfterEach(func() {
		if testServer != nil {
			testServer.Close()
		}
	})

	Describe("FindByName", func() {
		Context("when a stack exists", func() {
			BeforeEach(func() {
				testServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/v2/stacks", "q=name%3Alinux"),
	})

	Context("when the report interval elapses", func() {
		JustBeforeEach(func() {
			fakeClock.Increment(reportInterval)
		})

		Context("when the etcd cluster is around", func() {
			var (
				etcd1 *ghttp.Server
				etcd2 *ghttp.Server
				etcd3 *ghttp.Server
			)

			BeforeEach(func() {
				etcd1 = ghttp.NewServer()
				etcd2 = ghttp.NewServer()
				etcd3 = ghttp.NewServer()

				etcdOptions.ClusterUrls = []string{
					etcd1.URL(),
					etcd2.URL(),
					etcd3.URL(),
				}
			})

			AfterEach(func() {
				etcd1.Close()
				etcd2.Close()
				etcd3.Close()
			})
Ejemplo n.º 15
0
	var buildCommand = func(cmd string, flags []string, args []string) []string {
		command := []string{cmd}
		command = append(command, flags...)
		command = append(command, args...)
		return command
	}

	Context("Given reasonable arguments", func() {
		var (
			server     *ghttp.Server
			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"},
					}),
Ejemplo n.º 16
0
				"-bbsAddress", fakeBBS.URL(),
				"-privilegedContainers", "false",
			),
		})

		if !check {
			runner.StartCheck = ""
		}

		return ginkgomon.Invoke(runner)
	}

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")

		fakeCC = ghttp.NewServer()

		pollingInterval = 500 * time.Millisecond
		domainTTL = 1 * time.Second
		heartbeatInterval = 30 * time.Second

		desiredAppResponses := map[string]string{
			"process-guid-1": `{
					"disk_mb": 1024,
					"environment": [
						{ "name": "env-key-1", "value": "env-value-1" },
						{ "name": "env-key-2", "value": "env-value-2" }
					],
					"file_descriptors": 16,
					"num_instances": 42,
					"log_guid": "log-guid-1",
Ejemplo n.º 17
0
				extensions := []*schema.Extension{extension}
				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}
		uaaUsername string
		uaaPassword string
	)

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")

		httpClientTimeout = time.Second
		httpClient = &http.Client{Timeout: httpClientTimeout}

		permissionsBuilder = &fake_authenticators.FakePermissionsBuilder{}
		permissionsBuilder.BuildReturns(&ssh.Permissions{}, nil)

		metadata = &fake_ssh.FakeConnMetadata{}

		fakeCC = ghttp.NewServer()
		ccURL = fakeCC.URL()

		fakeUAA = ghttp.NewServer()
		u, err := url.Parse(fakeUAA.URL())
		Expect(err).NotTo(HaveOccurred())
		uaaUsername = "******"
		uaaPassword = "******"^&'"

		u.Path = "/oauth/token"
		uaaTokenURL = u.String()
	})

	JustBeforeEach(func() {
		authenticator = authenticators.NewCFAuthenticator(logger, httpClient, ccURL, uaaTokenURL, uaaUsername, uaaPassword, permissionsBuilder)
		permissions, authenErr = authenticator.Authenticate(metadata, password)
Ejemplo n.º 19
0
		uploadedBytes    []byte
		uploadedFileName string
		uploadedHeaders  http.Header
	)

	BeforeEach(func() {
		var err error

		logger = lagertest.NewTestLogger("test")

		buffer := bytes.NewBufferString("the file I'm uploading")
		incomingRequest, err = http.NewRequest("POST", "", buffer)
		Expect(err).NotTo(HaveOccurred())
		incomingRequest.Header.Set("Content-MD5", "the-md5")

		fakeCloudController = ghttp.NewServer()

		uploader := ccclient.NewUploader(logger, http.DefaultClient)
		poller := ccclient.NewPoller(logger, http.DefaultClient, 100*time.Millisecond)

		handler, err = handlers.New(uploader, poller, logger)
		Expect(err).NotTo(HaveOccurred())

		postStatusCode = http.StatusCreated
		uploadedBytes = nil
		uploadedFileName = ""
		uploadedHeaders = nil
	})

	AfterEach(func() {
		fakeCloudController.Close()
Ejemplo n.º 20
0
	BeforeEach(func() {
		configRepo = testconfig.NewRepositoryWithDefaults()
		gateway := net.NewCloudControllerGateway(configRepo, time.Now, &testterm.FakeUI{})

		repo = api.NewRoutingApiRepository(configRepo, gateway)
	})

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

	Describe("ListRouterGroups", func() {

		Context("when routing api return router groups", func() {
			BeforeEach(func() {
				routingApiServer = ghttp.NewServer()
				routingApiServer.RouteToHandler("GET", "/v1/router_groups",
					func(w http.ResponseWriter, req *http.Request) {
						responseBody := []byte(`[
			{
				  "guid": "bad25cff-9332-48a6-8603-b619858e7992",
					"name": "default-tcp",
					"type": "tcp"
			}]`)
						w.Header().Set("Content-Length", strconv.Itoa(len(responseBody)))
						w.Header().Set("Content-Type", "application/json")
						w.WriteHeader(http.StatusOK)
						w.Write(responseBody)
					})
				configRepo.SetRoutingApiEndpoint(routingApiServer.URL())
			})
Ejemplo n.º 21
0
})

var _ = BeforeEach(func() {
	logger := lagertest.NewTestLogger("test")

	auctionRep = &repfakes.FakeClient{}
	fakeLRPStopper = &fake_lrp_stopper.FakeLRPStopper{}
	fakeExecutorClient = &executorfakes.FakeClient{}
	fakeEvacuatable = &fake_evacuation_context.FakeEvacuatable{}

	handler, err := rata.NewRouter(rep.Routes, handlers.New(auctionRep, fakeLRPStopper, fakeExecutorClient, fakeEvacuatable, logger))
	Expect(err).NotTo(HaveOccurred())
	server = httptest.NewServer(handler)

	client = rep.NewClient(&http.Client{}, server.URL)

	serverThatErrors = ghttp.NewServer()
	erroringHandler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		serverThatErrors.CloseClientConnections()
	})
	//5 erroringHandlers should be more than enough: none of the individual tests should make more than 5 requests to this server
	serverThatErrors.AppendHandlers(erroringHandler, erroringHandler, erroringHandler, erroringHandler, erroringHandler)

	clientForServerThatErrors = rep.NewClient(&http.Client{}, serverThatErrors.URL())
})

var _ = AfterEach(func() {
	server.Close()
	serverThatErrors.Close()
})
Ejemplo n.º 22
0
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/ghttp"
)

var _ = Describe("TaskWorker", func() {
	var (
		fakeServer *ghttp.Server
		logger     *lagertest.TestLogger
		timeout    time.Duration
	)

	BeforeEach(func() {
		timeout = 1 * time.Second
		cf_http.Initialize(timeout)
		fakeServer = ghttp.NewServer()

		logger = lagertest.NewTestLogger("test")
		logger.RegisterSink(lager.NewWriterSink(GinkgoWriter, lager.INFO))
	})

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

	Describe("HandleCompletedTask", func() {
		var (
			callbackURL string
			taskDB      *dbfakes.FakeTaskDB
			statusCodes chan int
			reqCount    chan struct{}
Ejemplo n.º 23
0
					Expect(apiErr).NotTo(BeNil())
				})
			})
		})
	})

	Describe("Authorize", func() {
		var (
			uaaServer *ghttp.Server
			gateway   net.Gateway
			config    core_config.ReadWriter
			authRepo  AuthenticationRepository
		)

		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"},
Ejemplo n.º 24
0
			Expect(routes[0].GUID).To(Equal("route-1-guid"))
			Expect(routes[0].Space.GUID).To(Equal("space-1-guid"))
			Expect(routes[0].ServiceInstance.GUID).To(Equal("service-guid"))
			Expect(routes[0].ServiceInstance.Name).To(Equal("test-service"))
			Expect(routes[1].GUID).To(Equal("route-2-guid"))
			Expect(routes[1].Space.GUID).To(Equal("space-2-guid"))

			Expect(handler).To(HaveAllRequestsCalled())
			Expect(apiErr).NotTo(HaveOccurred())
		})
	})

	Describe("Find", func() {
		var ccServer *ghttp.Server
		BeforeEach(func() {
			ccServer = ghttp.NewServer()
			configRepo.SetAPIEndpoint(ccServer.URL())
		})

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

		Context("when the port is not specified", func() {
			BeforeEach(func() {
				v := url.Values{}
				v.Set("inline-relations-depth", "1")
				v.Set("q", "host:my-cool-app;domain_guid:my-domain-guid;path:/somepath")

				ccServer.AppendHandlers(
					ghttp.CombineHandlers(
Ejemplo n.º 25
0
		cookieJar, err = cookiejar.New(nil)
		Expect(err).ToNot(HaveOccurred())

		client = &http.Client{
			Transport: &http.Transport{},
			Jar:       cookieJar,
		}
	})

	Describe("GET /auth/:provider", func() {
		var redirectTarget *ghttp.Server
		var request *http.Request
		var response *http.Response

		BeforeEach(func() {
			redirectTarget = ghttp.NewServer()
			redirectTarget.RouteToHandler("GET", "/", ghttp.RespondWith(http.StatusOK, "sup"))

			var err error

			request, err = http.NewRequest("GET", server.URL, nil)
			Expect(err).NotTo(HaveOccurred())
		})

		JustBeforeEach(func() {
			var err error

			response, err = client.Do(request)
			Expect(err).NotTo(HaveOccurred())
		})
Ejemplo n.º 26
0
	Timezone string `json:"dateFormat:tz,omitempty"`
}

var _ = Describe("KibanaSetUtc", func() {
	const (
		KibanaConfigPath = "/.kibana/config/4.4.0"
		KibanaIndexPath  = "/.kibana"
	)

	var (
		server  *ghttp.Server
		command *exec.Cmd
	)

	BeforeEach(func() {
		server = ghttp.NewServer()

		host, port, err := net.SplitHostPort(server.Addr())
		Expect(err).ToNot(HaveOccurred())

		command = exec.Command("./kibana_set_utc.rb")
		command.Env = os.Environ()
		command.Env = append(command.Env, fmt.Sprintf("ES_HOST=%s", host))
		command.Env = append(command.Env, fmt.Sprintf("ES_PORT=%s", port))
	})

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

	Context("no index exists", func() {
Ejemplo n.º 27
0
		"http",
	)

	logger = lagertest.NewTestLogger("test")

	bbsPath = string(binaries["bbs"])
	bbsAddress := fmt.Sprintf("127.0.0.1:%d", 13000+GinkgoParallelNode())

	bbsURL = &url.URL{
		Scheme: "http",
		Host:   bbsAddress,
	}

	bbsClient = bbs.NewClient(bbsURL.String())

	auctioneerServer = ghttp.NewServer()
	auctioneerServer.UnhandledRequestStatusCode = http.StatusAccepted
	auctioneerServer.AllowUnhandledRequests = true

	bbsArgs = bbstestrunner.Args{
		Address:           bbsAddress,
		AdvertiseURL:      bbsURL.String(),
		AuctioneerAddress: auctioneerServer.URL(),
		EtcdCluster:       strings.Join(etcdRunner.NodeURLS(), ","),
		ConsulCluster:     consulRunner.ConsulCluster(),

		EncryptionKeys: []string{"label:key"},
		ActiveKeyLabel: "label",
	}
})
Ejemplo n.º 28
0
	"net/http"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/ghttp"

	"github.com/rosenhouse/proctor/client"
	"github.com/rosenhouse/proctor/mocks"
)

var _ = Describe("AtlasClient", func() {
	Describe("#GetLatestAMI", func() {
		It("should return the AMI used by the box each different regions ", func() {
			gzippedBoxData, err := ioutil.ReadFile("fixtures/test-box.gz")
			Expect(err).NotTo(HaveOccurred())
			fakeDownloadServer := ghttp.NewServer()
			fakeDownloadRoute := "/some/download/url"
			fakeDownloadServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", fakeDownloadRoute),
					ghttp.RespondWith(http.StatusOK, gzippedBoxData),
				),
			)
			fakeDownloadURL := fakeDownloadServer.URL() + fakeDownloadRoute

			jsonClient := &mocks.JSONClient{}
			jsonClient.GetCall.ResponseJSON = fmt.Sprintf(`{
				"versions" : [
					{
						"providers": [
							{
Ejemplo n.º 29
0
	"github.com/onsi/gomega/gexec"
	"github.com/onsi/gomega/ghttp"
)

var _ = Describe("Fly CLI", func() {
	var (
		atcServer *ghttp.Server
	)

	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,
		githubServer *ghttp.Server

		inRequest resource.InRequest

		inResponse resource.InResponse
		inErr      error

		tmpDir  string
		destDir string
	)

	BeforeEach(func() {
		var err error

		githubClient = &fakes.FakeGitHub{}
		githubServer = ghttp.NewServer()
		command = resource.NewInCommand(githubClient, ioutil.Discard)

		tmpDir, err = ioutil.TempDir("", "github-release")
		Ω(err).ShouldNot(HaveOccurred())

		destDir = filepath.Join(tmpDir, "destination")

		githubClient.DownloadReleaseAssetReturns(ioutil.NopCloser(bytes.NewBufferString("some-content")), nil)

		inRequest = resource.InRequest{}
	})

	AfterEach(func() {
		Ω(os.RemoveAll(tmpDir)).Should(Succeed())
	})