<commit_before>package handlers_test

import (
	"bytes"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"net/url"

	"github.com/cloudfoundry-incubator/bbs/fake_bbs"
	"github.com/cloudfoundry-incubator/bbs/models"
	"github.com/cloudfoundry-incubator/runtime-schema/cc_messages"
	"github.com/cloudfoundry-incubator/stager/backend"
	"github.com/cloudfoundry-incubator/stager/backend/fake_backend"
	"github.com/cloudfoundry-incubator/stager/cc_client/fakes"
	"github.com/cloudfoundry-incubator/stager/handlers"
	fake_metric_sender "github.com/cloudfoundry/dropsonde/metric_sender/fake"
	"github.com/cloudfoundry/dropsonde/metrics"
	"github.com/pivotal-golang/lager"
	"github.com/pivotal-golang/lager/lagertest"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
)

var _ = Describe("StagingHandler", func() {

	var (
		fakeMetricSender *fake_metric_sender.FakeMetricSender

		logger          lager.Logger
		fakeDiegoClient *fake_bbs.FakeClient
		fakeCcClient    *fakes.FakeCcClient
		fakeBackend     *fake_backend.FakeBackend

		responseRecorder *httptest.ResponseRecorder
		handler          handlers.StagingHandler
	)

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

		fakeMetricSender = fake_metric_sender.NewFakeMetricSender()
		metrics.Initialize(fakeMetricSender, nil)

		fakeCcClient = &fakes.FakeCcClient{}

		fakeBackend = &fake_backend.FakeBackend{}
		fakeBackend.BuildRecipeReturns(&models.TaskDefinition{}, "", "", nil)

		fakeDiegoClient = &fake_bbs.FakeClient{}

		responseRecorder = httptest.NewRecorder()
		handler = handlers.NewStagingHandler(logger, map[string]backend.Backend{"fake-backend": fakeBackend}, fakeCcClient, fakeDiegoClient)
	})

	Describe("Stage", func() {
		var (
			stagingRequestJson []byte
		)

		JustBeforeEach(func() {
			req, err := http.NewRequest("PUT", "/v1/staging/a-staging-guid", bytes.NewReader(stagingRequestJson))
			Expect(err).NotTo(HaveOccurred())

			req.Form = url.Values{":staging_guid": {"a-staging-guid"}}

			handler.Stage(responseRecorder, req)
		})

		Context("when a staging request is received for a registered backend", func() {
			var stagingRequest cc_messages.StagingRequestFromCC

			BeforeEach(func() {
				stagingRequest = cc_messages.StagingRequestFromCC{
					AppId:     "myapp",
					Lifecycle: "fake-backend",
				}

				var err error
				stagingRequestJson, err = json.Marshal(stagingRequest)
				Expect(err).NotTo(HaveOccurred())
			})

			It("increments the counter to track arriving staging messages", func() {
				Expect(fakeMetricSender.GetCounter("StagingStartRequestsReceived")).To(Equal(uint64(1)))
			})

			It("returns an Accepted response", func() {
				Expect(responseRecorder.Code).To(Equal(http.StatusAccepted))
			})

			It("builds a staging recipe", func() {
				Expect(fakeBackend.BuildRecipeCallCount()).To(Equal(1))

				guid, request := fakeBackend.BuildRecipeArgsForCall(0)
				Expect(guid).To(Equal("a-staging-guid"))
				Expect(request).To(Equal(stagingRequest))
			})

			Context("when the recipe was built successfully", func() {
				var fakeTaskDef = &models.TaskDefinition{Annotation: "test annotation"}
				BeforeEach(func() {
					fakeBackend.BuildRecipeReturns(fakeTaskDef, "a-guid", "a-domain", nil)
				})

				It("does not send a staging complete message", func() {
					Expect(fakeCcClient.StagingCompleteCallCount()).To(Equal(0))
				})

				It("creates a task on Diego", func() {
					Expect(fakeDiegoClient.DesireTaskCallCount()).To(Equal(1))
					_, _, resultingTaskDef := fakeDiegoClient.DesireTaskArgsForCall(0)
					Expect(resultingTaskDef).To(Equal(fakeTaskDef))
				})

				Context("when creating the task succeeds", func() {
					It("does not send a staging failure response", func() {
						Expect(fakeCcClient.StagingCompleteCallCount()).To(Equal(0))
					})
				})

				Context("when the task has already been created", func() {
					BeforeEach(func() {
						fakeDiegoClient.DesireTaskReturns(&models.Error{
							Type:    models.ResourceExists,
							Message: "ok, this task already exists",
						})
					})

					It("does not log a failure", func() {
						Expect(logger).NotTo(gbytes.Say("staging-failed"))
					})
				})
<commit_msg>Use NewError constructor instead of creating it manually<commit_after>package handlers_test

import (
	"bytes"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"net/url"

	"github.com/cloudfoundry-incubator/bbs/fake_bbs"
	"github.com/cloudfoundry-incubator/bbs/models"
	"github.com/cloudfoundry-incubator/runtime-schema/cc_messages"
	"github.com/cloudfoundry-incubator/stager/backend"
	"github.com/cloudfoundry-incubator/stager/backend/fake_backend"
	"github.com/cloudfoundry-incubator/stager/cc_client/fakes"
	"github.com/cloudfoundry-incubator/stager/handlers"
	fake_metric_sender "github.com/cloudfoundry/dropsonde/metric_sender/fake"
	"github.com/cloudfoundry/dropsonde/metrics"
	"github.com/pivotal-golang/lager"
	"github.com/pivotal-golang/lager/lagertest"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
)

var _ = Describe("StagingHandler", func() {

	var (
		fakeMetricSender *fake_metric_sender.FakeMetricSender

		logger          lager.Logger
		fakeDiegoClient *fake_bbs.FakeClient
		fakeCcClient    *fakes.FakeCcClient
		fakeBackend     *fake_backend.FakeBackend

		responseRecorder *httptest.ResponseRecorder
		handler          handlers.StagingHandler
	)

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

		fakeMetricSender = fake_metric_sender.NewFakeMetricSender()
		metrics.Initialize(fakeMetricSender, nil)

		fakeCcClient = &fakes.FakeCcClient{}

		fakeBackend = &fake_backend.FakeBackend{}
		fakeBackend.BuildRecipeReturns(&models.TaskDefinition{}, "", "", nil)

		fakeDiegoClient = &fake_bbs.FakeClient{}

		responseRecorder = httptest.NewRecorder()
		handler = handlers.NewStagingHandler(logger, map[string]backend.Backend{"fake-backend": fakeBackend}, fakeCcClient, fakeDiegoClient)
	})

	Describe("Stage", func() {
		var (
			stagingRequestJson []byte
		)

		JustBeforeEach(func() {
			req, err := http.NewRequest("PUT", "/v1/staging/a-staging-guid", bytes.NewReader(stagingRequestJson))
			Expect(err).NotTo(HaveOccurred())

			req.Form = url.Values{":staging_guid": {"a-staging-guid"}}

			handler.Stage(responseRecorder, req)
		})

		Context("when a staging request is received for a registered backend", func() {
			var stagingRequest cc_messages.StagingRequestFromCC

			BeforeEach(func() {
				stagingRequest = cc_messages.StagingRequestFromCC{
					AppId:     "myapp",
					Lifecycle: "fake-backend",
				}

				var err error
				stagingRequestJson, err = json.Marshal(stagingRequest)
				Expect(err).NotTo(HaveOccurred())
			})

			It("increments the counter to track arriving staging messages", func() {
				Expect(fakeMetricSender.GetCounter("StagingStartRequestsReceived")).To(Equal(uint64(1)))
			})

			It("returns an Accepted response", func() {
				Expect(responseRecorder.Code).To(Equal(http.StatusAccepted))
			})

			It("builds a staging recipe", func() {
				Expect(fakeBackend.BuildRecipeCallCount()).To(Equal(1))

				guid, request := fakeBackend.BuildRecipeArgsForCall(0)
				Expect(guid).To(Equal("a-staging-guid"))
				Expect(request).To(Equal(stagingRequest))
			})

			Context("when the recipe was built successfully", func() {
				var fakeTaskDef = &models.TaskDefinition{Annotation: "test annotation"}
				BeforeEach(func() {
					fakeBackend.BuildRecipeReturns(fakeTaskDef, "a-guid", "a-domain", nil)
				})

				It("does not send a staging complete message", func() {
					Expect(fakeCcClient.StagingCompleteCallCount()).To(Equal(0))
				})

				It("creates a task on Diego", func() {
					Expect(fakeDiegoClient.DesireTaskCallCount()).To(Equal(1))
					_, _, resultingTaskDef := fakeDiegoClient.DesireTaskArgsForCall(0)
					Expect(resultingTaskDef).To(Equal(fakeTaskDef))
				})

				Context("when creating the task succeeds", func() {
					It("does not send a staging failure response", func() {
						Expect(fakeCcClient.StagingCompleteCallCount()).To(Equal(0))
					})
				})

				Context("when the task has already been created", func() {
					BeforeEach(func() {
						fakeDiegoClient.DesireTaskReturns(models.NewError(models.Error_ResourceExists, "ok, this task already exists"))
					})

					It("does not log a failure", func() {
						Expect(logger).NotTo(gbytes.Say("staging-failed"))
					})
				})

{'fraction_non_alphanumeric': 0.1314420803782506, 'fraction_numerical': 0.002364066193853428, 'mean_word_length': 4.490590525632706, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7036516', 'n_tokens_mistral': 3223, 'n_tokens_neox': 2771, 'n_words': 430}