func TestValidateResponse(t *testing.T) {
	valid := &http.Response{
		Request:    &http.Request{},
		StatusCode: http.StatusOK,
		Body:       ioutil.NopCloser(strings.NewReader("OK")),
	}

	if err := validateResponse(valid); err != nil {
		t.Errorf("ValidateResponse with valid response returned error %+v", err)
	}

	invalid := &http.Response{
		Request:    &http.Request{},
		StatusCode: http.StatusBadRequest,
		Body: ioutil.NopCloser(strings.NewReader(`{
			"error" : {
				"statuscode": 400,
				"statusdesc": "Bad Request",
				"errormessage": "This is an error"
			}
		}`)),
	}

	want := &PingdomError{400, "Bad Request", "This is an error"}
	if err := validateResponse(invalid); !reflect.DeepEqual(err, want) {
		t.Errorf("ValidateResponse with invalid response returned %+v, want %+v", err, want)
	}

}
示例#2
0
// Map the Path into Content based on FileContent.Name
func (v *VirtualRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	res := &http.Response{Proto: "HTTP/1.0",
		ProtoMajor: 1,
		Header:     make(http.Header),
		Close:      true,
	}
	full := req.URL.String()
	for urlPrefix, statusCode := range v.errorURLS {
		if strings.HasPrefix(full, urlPrefix) {
			res.Status = fmt.Sprintf("%d Error", statusCode)
			res.StatusCode = statusCode
			res.ContentLength = 0
			res.Body = ioutil.NopCloser(strings.NewReader(""))
			return res, nil
		}
	}
	for _, fc := range v.contents {
		if fc.Name == req.URL.Path {
			res.Status = "200 OK"
			res.StatusCode = http.StatusOK
			res.ContentLength = int64(len(fc.Content))
			res.Body = ioutil.NopCloser(strings.NewReader(fc.Content))
			return res, nil
		}
	}
	res.Status = "404 Not Found"
	res.StatusCode = http.StatusNotFound
	res.ContentLength = 0
	res.Body = ioutil.NopCloser(strings.NewReader(""))
	return res, nil
}
示例#3
0
// Will receive an input stream which would convert the response to utf-8
// The given function must close the reader r, in order to close the response body.
func HandleStringReader(f func(r io.Reader, ctx *goproxy.ProxyCtx) io.Reader) goproxy.RespHandler {
	return goproxy.FuncRespHandler(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
		if ctx.Error != nil {
			return nil
		}
		charsetName := ctx.Charset()
		if charsetName == "" {
			charsetName = "utf-8"
		}

		if strings.ToLower(charsetName) != "utf-8" {
			r, err := charset.NewReader(charsetName, resp.Body)
			if err != nil {
				ctx.Warnf("Cannot convert from %v to utf-8: %v", charsetName, err)
				return resp
			}
			tr, err := charset.TranslatorTo(charsetName)
			if err != nil {
				ctx.Warnf("Can't translate to %v from utf-8: %v", charsetName, err)
				return resp
			}
			if err != nil {
				ctx.Warnf("Cannot translate to %v: %v", charsetName, err)
				return resp
			}
			newr := charset.NewTranslatingReader(f(r, ctx), tr)
			resp.Body = &readFirstCloseBoth{ioutil.NopCloser(newr), resp.Body}
		} else {
			//no translation is needed, already at utf-8
			resp.Body = &readFirstCloseBoth{ioutil.NopCloser(f(resp.Body, ctx)), resp.Body}
		}
		return resp
	})
}
func TestTriggerHooksUpdate(t *testing.T) {
	t.Parallel()

	h := newTriggersHarness(t)

	var tr triggerHooksCmd
	h.env.In =
		ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/_foo/beforeSave\n"))
	ensure.Nil(t, tr.triggerHooksUpdate(h.env, nil))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter following details about the trigger webhook
Class name: Trigger name: URL: https://Successfully update the "beforeSave" trigger for class "foo" to point to "https://api.example.com/_foo/beforeSave"
`)

	ensure.DeepEqual(t, h.Err.String(), "WARNING: beforeSave trigger already exists for class: foo\n")

	h.Out.Reset()
	h.Err.Reset()

	h.env.In =
		ioutil.NopCloser(strings.NewReader("bar\nafterSave\napi.example.com/_bar/afterSave\n"))
	ensure.Nil(t, tr.triggerHooksUpdate(h.env, nil))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter following details about the trigger webhook
Class name: Trigger name: URL: https://Successfully update the "afterSave" trigger for class "bar" to point to "https://api.example.com/_bar/afterSave"
`)

	ensure.DeepEqual(t, h.Err.String(), "")
}
示例#5
0
func TestProjectType(t *testing.T) {
	t.Parallel()
	h := parsecli.NewHarness(t)
	defer h.Stop()

	h.MakeEmptyRoot()
	ensure.Nil(t, parsecli.CloneSampleCloudCode(h.Env, false))

	c := &configureCmd{}
	err := c.projectType(h.Env, []string{"1", "2"})
	ensure.Err(t, err, regexp.MustCompile("only an optional project type argument is expected"))

	h.Env.In = ioutil.NopCloser(strings.NewReader("invalid\n"))
	err = c.projectType(h.Env, nil)
	ensure.StringContains(t, h.Err.String(), "Invalid selection. Please enter a number")
	ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again."))
	h.Err.Reset()
	h.Out.Reset()

	h.Env.In = ioutil.NopCloser(strings.NewReader("0\n"))
	err = c.projectType(h.Env, nil)
	ensure.StringContains(t, h.Err.String(), "Please enter a number between 1 and")
	ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again."))
	h.Err.Reset()
	h.Out.Reset()

	h.Env.In = ioutil.NopCloser(strings.NewReader("1\n"))
	err = c.projectType(h.Env, nil)
	ensure.StringContains(t, h.Out.String(), "Successfully set project type to: parse")
	ensure.Nil(t, err)
}
func TestConfigureAcessToken(t *testing.T) {
	t.Parallel()

	h, _ := newAppHarness(t)
	defer h.Stop()

	c := configureCmd{login: login{tokenReader: strings.NewReader("")}}
	h.env.In = ioutil.NopCloser(strings.NewReader("n\ntoken\n"))
	ensure.Nil(t, c.accessToken(h.env))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter an access token if you already generated it.
If you do not have an access token or would like to generate a new one,
please type: "y" to open the browser or "n" to continue: Access Token: Successfully stored credentials.
`,
	)
	h.env.In = ioutil.NopCloser(strings.NewReader("n\nemail\ninvalid\n"))
	ensure.Err(t, c.accessToken(h.env), regexp.MustCompile("Please try again"))
	ensure.DeepEqual(t,
		h.Err.String(),
		`Sorry, the access token you provided is not valid.
Please follow instructions at https://www.parse.com/account_keys to generate a new access token.
`,
	)
}
func TestConfigureAcessToken(t *testing.T) {
	t.Parallel()

	h, _ := newAppHarness(t)
	defer h.Stop()

	c := configureCmd{login: login{tokenReader: strings.NewReader("")}}
	h.env.In = ioutil.NopCloser(strings.NewReader("token\n"))
	ensure.Nil(t, c.accountKey(h.env))
	ensure.DeepEqual(
		t,
		h.Out.String(),
		`
Input your account key or press enter to generate a new one.
Account Key: Successfully stored credentials.
`)
	h.env.In = ioutil.NopCloser(strings.NewReader("email\ninvalid\n"))
	ensure.Err(t, c.accountKey(h.env), regexp.MustCompile("Please try again"))
	ensure.DeepEqual(t,
		h.Err.String(),
		`Sorry, the account key you provided is not valid.
Please follow instructions at https://www.parse.com/account_keys to generate a new account key.
`,
	)
}
示例#8
0
func (t *RandomReaderTest) DoesntChangeReadsOfAppropriateSize() {
	t.object.Size = 1 << 40
	const readSize = 2 * minReadSize

	// Simulate an existing reader at a mismatched offset.
	t.rr.wrapped.reader = ioutil.NopCloser(strings.NewReader("xxx"))
	t.rr.wrapped.cancel = func() {}
	t.rr.wrapped.start = 2
	t.rr.wrapped.limit = 5

	// The bucket should be asked to read readSize bytes.
	r := strings.NewReader(strings.Repeat("x", readSize))
	rc := ioutil.NopCloser(r)

	ExpectCall(t.bucket, "NewReader")(
		Any(),
		AllOf(rangeStartIs(1), rangeLimitIs(1+readSize))).
		WillOnce(Return(rc, nil))

	// Call through.
	buf := make([]byte, readSize)
	t.rr.ReadAt(buf, 1)

	// Check the state now.
	ExpectEq(1+readSize, t.rr.wrapped.limit)
}
示例#9
0
func TestFindIDInConfigurationsPayload(t *testing.T) {
	const (
		searchedName = "search-for-this-name"
		expected     = "The-42-id"
	)
	assert := assert.New(t)

	c := Client{}

	payload := fmt.Sprintf(
		`[{"dataset_id": "1-2-3", "metadata": {"name": "test"}}, {"dataset_id": "The-42-id", "metadata": {"name": "%s"}}]`,
		searchedName,
	)

	id, err := c.findIDInConfigurationsPayload(
		ioutil.NopCloser(bytes.NewBufferString(payload)), searchedName,
	)
	assert.NoError(err)
	assert.Equal(expected, id)

	id, err = c.findIDInConfigurationsPayload(
		ioutil.NopCloser(bytes.NewBufferString(payload)), "it will not be found",
	)
	assert.Equal(errConfigurationNotFound, err)

	id, err = c.findIDInConfigurationsPayload(
		ioutil.NopCloser(bytes.NewBufferString("invalid { json")), "",
	)
	assert.Error(err)
}
示例#10
0
func (cs *clientSuite) TestParseError(c *check.C) {
	resp := &http.Response{
		Status: "404 Not Found",
	}
	err := client.ParseErrorInTest(resp)
	c.Check(err, check.ErrorMatches, `server error: "404 Not Found"`)

	h := http.Header{}
	h.Add("Content-Type", "application/json")
	resp = &http.Response{
		Status: "400 Bad Request",
		Header: h,
		Body: ioutil.NopCloser(strings.NewReader(`{
			"status-code": 400,
			"type": "error",
			"result": {
				"message": "invalid"
			}
		}`)),
	}
	err = client.ParseErrorInTest(resp)
	c.Check(err, check.ErrorMatches, "invalid")

	resp = &http.Response{
		Status: "400 Bad Request",
		Header: h,
		Body:   ioutil.NopCloser(strings.NewReader("{}")),
	}
	err = client.ParseErrorInTest(resp)
	c.Check(err, check.ErrorMatches, `server error: "400 Bad Request"`)
}
示例#11
0
func DecompressStream(archive io.Reader) (io.ReadCloser, error) {
	buf := make([]byte, 10)
	totalN := 0
	for totalN < 10 {
		n, err := archive.Read(buf[totalN:])
		if err != nil {
			if err == io.EOF {
				return nil, fmt.Errorf("Tarball too short")
			}
			return nil, err
		}
		totalN += n
		utils.Debugf("[tar autodetect] n: %d", n)
	}
	compression := DetectCompression(buf)
	wrap := io.MultiReader(bytes.NewReader(buf), archive)

	switch compression {
	case Uncompressed:
		return ioutil.NopCloser(wrap), nil
	case Gzip:
		return gzip.NewReader(wrap)
	case Bzip2:
		return ioutil.NopCloser(bzip2.NewReader(wrap)), nil
	case Xz:
		return xzDecompress(wrap)
	default:
		return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
	}
}
示例#12
0
func TestTransformResponse(t *testing.T) {
	invalid := []byte("aaaaa")
	uri, _ := url.Parse("http://localhost")
	testCases := []struct {
		Response *http.Response
		Data     []byte
		Created  bool
		Error    bool
	}{
		{Response: &http.Response{StatusCode: 200}, Data: []byte{}},
		{Response: &http.Response{StatusCode: 201}, Data: []byte{}, Created: true},
		{Response: &http.Response{StatusCode: 199}, Error: true},
		{Response: &http.Response{StatusCode: 500}, Error: true},
		{Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid},
		{Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid},
	}
	for i, test := range testCases {
		r := NewRequest(nil, "", uri, testapi.Codec())
		if test.Response.Body == nil {
			test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
		}
		response, created, err := r.transformResponse(test.Response, &http.Request{})
		hasErr := err != nil
		if hasErr != test.Error {
			t.Errorf("%d: unexpected error: %f %v", i, test.Error, err)
		}
		if !(test.Data == nil && response == nil) && !reflect.DeepEqual(test.Data, response) {
			t.Errorf("%d: unexpected response: %#v %#v", i, test.Data, response)
		}
		if test.Created != created {
			t.Errorf("%d: expected created %f, got %f", i, test.Created, created)
		}
	}
}
示例#13
0
func TestRequestWrite(t *testing.T) {
	for i := range reqWriteTests {
		tt := &reqWriteTests[i]
		if tt.Body != nil {
			tt.Req.Body = ioutil.NopCloser(bytes.NewBuffer(tt.Body))
		}
		var braw bytes.Buffer
		err := tt.Req.Write(&braw)
		if err != nil {
			t.Errorf("error writing #%d: %s", i, err)
			continue
		}
		sraw := braw.String()
		if sraw != tt.Raw {
			t.Errorf("Test %d, expecting:\n%s\nGot:\n%s\n", i, tt.Raw, sraw)
			continue
		}

		if tt.Body != nil {
			tt.Req.Body = ioutil.NopCloser(bytes.NewBuffer(tt.Body))
		}
		var praw bytes.Buffer
		err = tt.Req.WriteProxy(&praw)
		if err != nil {
			t.Errorf("error writing #%d: %s", i, err)
			continue
		}
		sraw = praw.String()
		if sraw != tt.RawProxy {
			t.Errorf("Test Proxy %d, expecting:\n%s\nGot:\n%s\n", i, tt.RawProxy, sraw)
			continue
		}
	}
}
示例#14
0
// SendHandler is a request handler to send service request using HTTP client.
func SendHandler(r *Request) {
	var err error
	r.HTTPResponse, err = r.Service.Config.HTTPClient.Do(r.HTTPRequest)
	if err != nil {
		// Capture the case where url.Error is returned for error processing
		// response. e.g. 301 without location header comes back as string
		// error and r.HTTPResponse is nil. Other url redirect errors will
		// comeback in a similar method.
		if e, ok := err.(*url.Error); ok {
			if s := reStatusCode.FindStringSubmatch(e.Error()); s != nil {
				code, _ := strconv.ParseInt(s[1], 10, 64)
				r.HTTPResponse = &http.Response{
					StatusCode: int(code),
					Status:     http.StatusText(int(code)),
					Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
				}
				return
			}
		}
		if r.HTTPRequest == nil {
			// Add a dummy request response object to ensure the HTTPResponse
			// value is consistent.
			r.HTTPResponse = &http.Response{
				StatusCode: int(0),
				Status:     http.StatusText(int(0)),
				Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
			}
		}
		// Catch all other request errors.
		r.Error = apierr.New("RequestError", "send request failed", err)
		r.Retryable.Set(true) // network errors are retryable
	}
}
示例#15
0
func TestGetResponseCorruptedRequestResponsePair(t *testing.T) {
	RegisterTestingT(t)

	server, dbClient := testTools(200, `{'message': 'here'}`)
	defer server.Close()

	requestBody := []byte("fizz=buzz")

	body := ioutil.NopCloser(bytes.NewBuffer(requestBody))

	req, err := http.NewRequest("POST", "http://capture_body.com", body)
	Expect(err).To(BeNil())

	_, err = dbClient.captureRequest(req)
	Expect(err).To(BeNil())

	fp := matching.GetRequestFingerprint(req, requestBody, false)

	dbClient.RequestCache.Set([]byte(fp), []byte("you shall not decode me!"))

	// repeating process
	bodyNew := ioutil.NopCloser(bytes.NewBuffer(requestBody))

	reqNew, err := http.NewRequest("POST", "http://capture_body.com", bodyNew)
	Expect(err).To(BeNil())

	requestDetails, err := models.NewRequestDetailsFromHttpRequest(reqNew)
	Expect(err).To(BeNil())

	response, err := dbClient.getResponse(reqNew, requestDetails)
	Expect(err).ToNot(BeNil())

	Expect(response).To(BeNil())
}
示例#16
0
func TestLogin(t *testing.T) {
	t.Parallel()

	h, _ := newAppHarness(t)
	defer h.Stop()

	l := &loginCmd{tokenReader: strings.NewReader("")}

	h.env.In = ioutil.NopCloser(strings.NewReader("n\nemail\ntoken\n"))
	ensure.Nil(t, l.run(h.env))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter the email id you used to register with Parse
and an account key if you already generated it.
If you do not have an account key or would like to generate a new one,
please type: "y" to open the browser or "n" to continue: Email: Account Key: Successfully stored credentials.
`)

	h.env.In = ioutil.NopCloser(strings.NewReader("n\nemail\ninvalid\n"))
	ensure.Err(t, l.run(h.env), regexp.MustCompile("Please try again"))
	ensure.DeepEqual(t,
		h.Err.String(),
		`Sorry, we do not have a user with this email and account key.
Please follow instructions at https://www.parse.com/account/keys to generate a new account key.
`)
}
示例#17
0
func (t *RandomReaderTest) UpgradesReadsToMinimumSize() {
	t.object.Size = 1 << 40

	const readSize = 10
	AssertLt(readSize, minReadSize)

	// Simulate an existing reader at a mismatched offset.
	t.rr.wrapped.reader = ioutil.NopCloser(strings.NewReader("xxx"))
	t.rr.wrapped.cancel = func() {}
	t.rr.wrapped.start = 2
	t.rr.wrapped.limit = 5

	// The bucket should be asked to read minReadSize bytes, even though we only
	// ask for a few bytes below.
	r := strings.NewReader(strings.Repeat("x", minReadSize))
	rc := ioutil.NopCloser(r)

	ExpectCall(t.bucket, "NewReader")(
		Any(),
		AllOf(rangeStartIs(1), rangeLimitIs(1+minReadSize))).
		WillOnce(Return(rc, nil))

	// Call through.
	buf := make([]byte, readSize)
	t.rr.ReadAt(buf, 1)

	// Check the state now.
	ExpectEq(1+readSize, t.rr.wrapped.start)
	ExpectEq(1+minReadSize, t.rr.wrapped.limit)
}
示例#18
0
func setupForDeploy(t testing.TB, info *deployInfo) *Harness {
	h := createParseProject(t)

	ht := transportFunc(func(r *http.Request) (*http.Response, error) {
		switch r.URL.Path {
		case "/1/deploy":
			return &http.Response{
				StatusCode: http.StatusOK,
				Body:       ioutil.NopCloser(strings.NewReader(jsonStr(t, info))),
			}, nil
		case "/1/scripts", "/1/hosted_files":
			return &http.Response{
				StatusCode: http.StatusOK,
				Body:       ioutil.NopCloser(strings.NewReader(`{"version":"f2"}`)),
			}, nil
		case "/1/jsVersions":
			return &http.Response{
				StatusCode: http.StatusOK,
				Body:       ioutil.NopCloser(strings.NewReader(`{"js":["1.0","2.0"]}`)),
			}, nil
		default:
			return &http.Response{
				StatusCode: http.StatusExpectationFailed,
				Body:       ioutil.NopCloser(strings.NewReader(`{"error": "something is wrong"}`)),
			}, nil
		}
	})
	h.env.ParseAPIClient = &ParseAPIClient{apiClient: &parse.Client{Transport: ht}}
	return h
}
示例#19
0
func (t *RandomReaderTest) UpgradesSequentialReads_ExistingReader() {
	t.object.Size = 1 << 40
	const readSize = 10

	// Simulate an existing reader at the correct offset, which will be exhausted
	// by the read below.
	const existingSize = 3
	r := strings.NewReader(strings.Repeat("x", existingSize))

	t.rr.wrapped.reader = ioutil.NopCloser(r)
	t.rr.wrapped.cancel = func() {}
	t.rr.wrapped.start = 1
	t.rr.wrapped.limit = 1 + existingSize

	// The bucket should be asked to read up to the end of the object.
	r = strings.NewReader(strings.Repeat("x", readSize-existingSize))
	rc := ioutil.NopCloser(r)

	ExpectCall(t.bucket, "NewReader")(
		Any(),
		AllOf(rangeStartIs(1+existingSize), rangeLimitIs(t.object.Size))).
		WillOnce(Return(rc, nil))

	// Call through.
	buf := make([]byte, readSize)
	t.rr.ReadAt(buf, 1)

	// Check the state now.
	ExpectEq(1+readSize, t.rr.wrapped.start)
	ExpectEq(t.object.Size, t.rr.wrapped.limit)
}
示例#20
0
func TestAdminAdd(t *testing.T) {
	Convey("Test Admin Add Api", t, func() {
		bf := bytes.NewBufferString("topic=foo")
		body := ioutil.NopCloser(bf)
		req, err := http.NewRequest(
			"PUT",
			"http://127.0.0.1:8800/v1/queues",
			body,
		)
		So(err, ShouldBeNil)
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

		resp, err := client.Do(req)
		So(err, ShouldBeNil)
		So(resp.StatusCode, ShouldEqual, http.StatusCreated)

		bf = bytes.NewBufferString("topic=foo&line=x&recycle=10s")
		body = ioutil.NopCloser(bf)
		req, err = http.NewRequest(
			"PUT",
			"http://127.0.0.1:8800/v1/queues",
			body,
		)
		So(err, ShouldBeNil)
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

		resp, err = client.Do(req)
		So(err, ShouldBeNil)
		So(resp.StatusCode, ShouldEqual, http.StatusCreated)
	})
}
示例#21
0
文件: gateway.go 项目: jsloyer/cli
func (gateway Gateway) doRequestHandlingAuth(request *Request) (*http.Response, error) {
	httpReq := request.HTTPReq

	if request.SeekableBody != nil {
		httpReq.Body = ioutil.NopCloser(request.SeekableBody)
	}

	// perform request
	rawResponse, err := gateway.doRequestAndHandlerError(request)
	if err == nil || gateway.authenticator == nil {
		return rawResponse, err
	}

	switch err.(type) {
	case *errors.InvalidTokenError:
		// refresh the auth token
		var newToken string
		newToken, err = gateway.authenticator.RefreshAuthToken()
		if err != nil {
			return rawResponse, err
		}

		// reset the auth token and request body
		httpReq.Header.Set("Authorization", newToken)
		if request.SeekableBody != nil {
			_, _ = request.SeekableBody.Seek(0, 0)
			httpReq.Body = ioutil.NopCloser(request.SeekableBody)
		}

		// make the request again
		rawResponse, err = gateway.doRequestAndHandlerError(request)
	}

	return rawResponse, err
}
示例#22
0
// BodyReader returns an io.ReadCloser that reads the HTTP request or response
// body. If mv.skipBody was set the reader will immediately return io.EOF.
//
// If the Decode option is passed the body will be unchunked if
// Transfer-Encoding is set to "chunked", and will decode the following
// Content-Encodings: gzip, deflate.
func (mv *MessageView) BodyReader(opts ...Option) (io.ReadCloser, error) {
	var r io.Reader

	conf := &config{}
	for _, o := range opts {
		o(conf)
	}

	br := bytes.NewReader(mv.message)
	r = io.NewSectionReader(br, mv.bodyoffset, mv.traileroffset-mv.bodyoffset)

	if !conf.decode {
		return ioutil.NopCloser(r), nil
	}

	if mv.chunked {
		r = httputil.NewChunkedReader(r)
	}
	switch mv.compress {
	case "gzip":
		gr, err := gzip.NewReader(r)
		if err != nil {
			return nil, err
		}
		return gr, nil
	case "deflate":
		return flate.NewReader(r), nil
	default:
		return ioutil.NopCloser(r), nil
	}
}
示例#23
0
func NewTokenHarness(t testing.TB) *Harness {
	h := NewHarness(t)
	ht := TransportFunc(func(r *http.Request) (*http.Response, error) {
		ensure.DeepEqual(t, r.URL.Path, "/1/accountkey")
		ensure.DeepEqual(t, r.Method, "POST")

		key := &struct {
			AccountKey string `json:"accountKey"`
		}{}
		ensure.Nil(t, json.NewDecoder(ioutil.NopCloser(r.Body)).Decode(key))

		if key.AccountKey != "token" {
			return &http.Response{
				StatusCode: http.StatusUnauthorized,
				Body:       ioutil.NopCloser(strings.NewReader(`{"error": "incorrect token"}`)),
			}, nil
		}

		return &http.Response{
			StatusCode: http.StatusOK,
			Body:       ioutil.NopCloser(strings.NewReader(`{"email": "email"}`)),
		}, nil
	})
	h.Env.ParseAPIClient = &ParseAPIClient{APIClient: &parse.Client{Transport: ht}}
	return h
}
示例#24
0
// dispatchRequest sends a request to the server, and interprets the response.
// Client-side errors will return an empty response and a non-nil error.  For
// server-side errors however (i.e. responses with a non 2XX status code), the
// returned error will be ServerError and the returned body will reflect the
// server's response.  If the server returns a 503 response with a 'Retry-after'
// header, the request will be transparenty retried.
func (client Client) dispatchRequest(request *http.Request) ([]byte, error) {
	// First, store the request's body into a byte[] to be able to restore it
	// after each request.
	bodyContent, err := readAndClose(request.Body)
	if err != nil {
		return nil, err
	}
	for retry := 0; retry < NumberOfRetries; retry++ {
		// Restore body before issuing request.
		newBody := ioutil.NopCloser(bytes.NewReader(bodyContent))
		request.Body = newBody
		body, err := client.dispatchSingleRequest(request)
		// If this is a 503 response with a non-void "Retry-After" header: wait
		// as instructed and retry the request.
		if err != nil {
			serverError, ok := err.(ServerError)
			if ok && serverError.StatusCode == http.StatusServiceUnavailable {
				retry_time_int, errConv := strconv.Atoi(serverError.Header.Get(RetryAfterHeaderName))
				if errConv == nil {
					select {
					case <-time.After(time.Duration(retry_time_int) * time.Second):
					}
					continue
				}
			}
		}
		return body, err
	}
	// Restore body before issuing request.
	newBody := ioutil.NopCloser(bytes.NewReader(bodyContent))
	request.Body = newBody
	return client.dispatchSingleRequest(request)
}
func TestReadTriggerParams(t *testing.T) {
	t.Parallel()

	h := newHarness(t)
	defer h.Stop()

	h.env.In = ioutil.NopCloser(strings.NewReader("\n"))
	_, err := readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Class name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\n"))
	_, err = readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Trigger name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave"))
	hook, err := readTriggerName(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{ClassName: "foo", TriggerName: "beforeSave"})

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/foo/beforeSave\n"))
	hook, err = readTriggerParams(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{
		ClassName:   "foo",
		TriggerName: "beforeSave",
		URL:         "https://api.example.com/foo/beforeSave",
	})
}
示例#26
0
func (s *S) TestDeployKind(c *check.C) {
	var tests = []struct {
		input    DeployOptions
		expected DeployKind
	}{
		{
			DeployOptions{Rollback: true},
			DeployRollback,
		},
		{
			DeployOptions{Image: "quay.io/tsuru/python"},
			DeployImage,
		},
		{
			DeployOptions{File: ioutil.NopCloser(bytes.NewBuffer(nil))},
			DeployUpload,
		},
		{
			DeployOptions{File: ioutil.NopCloser(bytes.NewBuffer(nil)), Build: true},
			DeployUploadBuild,
		},
		{
			DeployOptions{Commit: "abcef48439"},
			DeployGit,
		},
		{
			DeployOptions{},
			DeployArchiveURL,
		},
	}
	for _, t := range tests {
		c.Check(t.input.GetKind(), check.Equals, t.expected)
		c.Check(t.input.Kind, check.Equals, t.expected)
	}
}
示例#27
0
func (t *logTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	var buf bytes.Buffer

	os.Stdout.Write([]byte("\n[request]\n"))
	if req.Body != nil {
		req.Body = ioutil.NopCloser(&readButCopy{req.Body, &buf})
	}
	req.Write(os.Stdout)
	if req.Body != nil {
		req.Body = ioutil.NopCloser(&buf)
	}
	os.Stdout.Write([]byte("\n[/request]\n"))

	res, err := t.rt.RoundTrip(req)

	fmt.Printf("[response]\n")
	if err != nil {
		fmt.Printf("ERROR: %v", err)
	} else {
		body := res.Body
		res.Body = nil
		res.Write(os.Stdout)
		if body != nil {
			res.Body = ioutil.NopCloser(&echoAsRead{body})
		}
	}

	return res, err
}
示例#28
0
// Request returns a HTTP Response with Header and Body
// from fcgi responder
func (this *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Response, err error) {

	r, err := this.Do(p, req)
	if err != nil {
		return
	}

	rb := bufio.NewReader(r)
	tp := textproto.NewReader(rb)
	resp = new(http.Response)

	// Parse the response headers.
	mimeHeader, err := tp.ReadMIMEHeader()
	if err != nil {
		return
	}
	resp.Header = http.Header(mimeHeader)

	// TODO: fixTransferEncoding ?
	resp.TransferEncoding = resp.Header["Transfer-Encoding"]
	resp.ContentLength, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)

	if chunked(resp.TransferEncoding) {
		resp.Body = ioutil.NopCloser(httputil.NewChunkedReader(rb))
	} else {
		resp.Body = ioutil.NopCloser(rb)
	}

	return
}
示例#29
0
文件: api.go 项目: polluks/client
func (api *BaseAPIEngine) PreparePost(url url.URL, arg APIArg, sendJSON bool) (*http.Request, error) {
	ruri := url.String()
	G.Log.Debug(fmt.Sprintf("+ API Post request to %s", ruri))

	var body io.Reader

	if sendJSON {
		if len(arg.getHTTPArgs()) > 0 {
			panic("PreparePost:  sending JSON, but http args exist and they will be ignored.  Fix your APIArg.")
		}
		jsonString, err := json.Marshal(arg.JSONPayload)
		if err != nil {
			return nil, err
		}
		body = ioutil.NopCloser(strings.NewReader(string(jsonString)))
	} else {
		body = ioutil.NopCloser(strings.NewReader(arg.getHTTPArgs().Encode()))
	}

	req, err := http.NewRequest("POST", ruri, body)
	if err != nil {
		return nil, err
	}

	var typ string
	if sendJSON {
		typ = "application/json"
	} else {
		typ = "application/x-www-form-urlencoded; charset=utf-8"
	}

	req.Header.Add("Content-Type", typ)
	return req, nil
}
示例#30
0
func (self *ProcessorMiddlewareHttpClient) HandleMessage(request **http.Request, response **http.Response) {
	reqBody := RogueRead(&(*request).Body)

	httpClient := &http.Client{}
	resp, err := httpClient.Do(*request)
	(*request).Body = ioutil.NopCloser(bytes.NewBuffer([]byte(reqBody)))
	if err != nil {
		err = errors.New(fmt.Sprintf("Sending message to Target failed: %s", err))
		Log.Warning(err.Error())
		return
	}

	respBody, err := ioutil.ReadAll(resp.Body)
	resp.Body = ioutil.NopCloser(bytes.NewBuffer(respBody))
	*response = resp

	if err != nil {
		err = errors.New(fmt.Sprintf("Could not read response body from Target: %s", err))
		Log.Warning(err.Error())
		return
	}

	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		err = errors.New(fmt.Sprintf("Target sent negative response code (%d). Response body: %s", resp.StatusCode, respBody))
		Log.Warning(err.Error())
		return
	}

	if self.next != nil {
		self.next.HandleMessage(request, response)
	}
}