func TestCheckResponseForErrors(t *testing.T) {
	var err error
	var resp http.Response

	resp.StatusCode = 300
	_, err = checkResponseForErrors(&resp)
	if err == nil {
		t.Error("should have returned error")
	}

	resp.StatusCode = 503
	_, err = checkResponseForErrors(&resp)
	if err == nil {
		t.Error("should have returned error")
	}

	resp.StatusCode = 404
	resp.Body = ioutil.NopCloser(strings.NewReader(`{"message":"Record Not Found","errors":[{"resource":"Activity","field":"id","code":"invalid"}]}`))
	_, err = checkResponseForErrors(&resp)
	if err == nil {
		t.Error("should have returned error")
	}

	if se, ok := err.(Error); ok {
		if len(se.Errors) == 0 {
			t.Error("Detailed errors not parsed")
		}
	} else {
		t.Error("Should have returned strava error")
	}
}
Esempio n. 2
0
// FileFetcher's Fetch() implementation
func (this *fileFetcherExtender) Fetch(u *url.URL, userAgent string, headRequest bool) (*http.Response, error) {
	var res *http.Response = new(http.Response)
	var req *http.Request
	var e error

	if req, e = http.NewRequest("GET", u.String(), nil); e != nil {
		panic(e)
	}

	// Prepare the pseudo-request
	req.Header.Add("User-Agent", userAgent)

	// Open the file specified as path in u, relative to testdata/[host]/
	f, e := os.Open(path.Join(FileFetcherBasePath, u.Host, u.Path))
	if e != nil {
		// Treat errors as 404s - file not found
		res.Status = "404 Not Found"
		res.StatusCode = 404
	} else {
		res.Status = "200 OK"
		res.StatusCode = 200
		res.Body = f
	}
	res.Request = req

	return res, e
}
Esempio n. 3
0
func TestOAuth2Provider_Non200Response(t *testing.T) {

	config := &common.Config{
		Map: objx.MSI(
			OAuth2KeyRedirectUrl, OAuth2KeyRedirectUrl,
			OAuth2KeyScope, OAuth2KeyScope,
			OAuth2KeyClientID, OAuth2KeyClientID,
			OAuth2KeySecret, OAuth2KeySecret,
			OAuth2KeyAuthURL, OAuth2KeyAuthURL,
			OAuth2KeyTokenURL, OAuth2KeyTokenURL)}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testProvider := new(test.TestProvider)

	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "text/plain")
	testResponse.StatusCode = 401
	testResponse.Body = ioutil.NopCloser(strings.NewReader("No mate"))

	testTripperFactory.On("NewTripper", common.EmptyCredentials, mock.Anything).Return(testTripper, nil)
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	data := objx.MSI(OAuth2KeyCode, []string{"123"})
	_, err := CompleteAuth(testTripperFactory, data, config, testProvider)

	if assert.Error(t, err) {
		assert.IsType(t, &common.AuthServerError{}, err)
	}

	mock.AssertExpectationsForObjects(t, testTripperFactory.Mock, testTripper.Mock, testProvider.Mock)

}
Esempio n. 4
0
func TestEventsList(t *testing.T) {
	for _, c := range eventsListCases {
		client := NewClient(ClientConfig{APIToken: "0"})
		hc := test.NewHTTPClient()
		client.httpClient = hc

		res := new(http.Response)
		res.Body = ioutil.NopCloser(strings.NewReader(c.Body))
		res.StatusCode = 200
		hc.SetResponseData(res)

		events, _, err := client.EventsList(c.App, c.PaginationOpts)
		if len(hc.Calls) != 1 {
			t.Errorf("expected 1 http request, got %v", len(hc.Calls))
		}
		if len(events) != c.EventsCount {
			t.Errorf("expected %d event, got %v", c.EventsCount, len(events))
		}
		if err != c.Error {
			t.Errorf("expected '%v' error got %v", c.Error, err)
		}

		req := hc.Calls[0]
		if c.ReqURL != "" && req.URL.String() != c.ReqURL {
			t.Errorf("expected request to URL %v, got %v", c.ReqURL, req.URL.String())
		}
		if c.ReqMethod != "" && req.Method != c.ReqMethod {
			t.Errorf("expected request with verb %v, got %v", c.ReqMethod, req.Method)
		}
	}
}
Esempio n. 5
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{"full_name":"their-name","id":"uniqueid","username":"******","avatar_url":"http://myface.com/","online":true}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {
		assert.Equal(t, user.Name(), "their-name")
		assert.Equal(t, user.AuthCode(), "")
		assert.Equal(t, user.Nickname(), "loginname")
		assert.Equal(t, user.Email(), "") // doesn't come from soundcloud
		assert.Equal(t, user.AvatarURL(), "http://myface.com/")
		assert.Equal(t, user.Data()["online"], true)
	}

}
Esempio n. 6
0
func TestRuntime_OverrideClientOperation(t *testing.T) {
	client := &http.Client{}
	rt := NewWithClient("", "/", []string{"https"}, client)
	var i int
	rt.clientOnce.Do(func() { i++ })
	assert.Equal(t, client, rt.client)
	assert.Equal(t, 0, i)

	var seen *http.Client
	rt.do = func(_ context.Context, cl *http.Client, _ *http.Request) (*http.Response, error) {
		seen = cl
		res := new(http.Response)
		res.StatusCode = 200
		res.Body = ioutil.NopCloser(bytes.NewBufferString("OK"))
		return res, nil
	}

	client2 := new(http.Client)
	client2.Timeout = 3 * time.Second
	if assert.NotEqual(t, client, client2) {
		_, err := rt.Submit(&runtime.ClientOperation{
			Client: client2,
			Params: runtime.ClientRequestWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
				return nil
			}),
			Reader: runtime.ClientResponseReaderFunc(func(_ runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) {
				return nil, nil
			}),
		})
		if assert.NoError(t, err) {

			assert.Equal(t, client2, seen)
		}
	}
}
Esempio n. 7
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{"name":"their-name","id":"uniqueid","login":"******","email":"*****@*****.**","picture":"http://myface.com/","blog":"http://blog.com/"}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {

		assert.Equal(t, user.Name(), "their-name")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from google
		assert.Equal(t, user.Email(), "*****@*****.**")
		assert.Equal(t, user.AvatarURL(), "http://myface.com/")
		assert.Equal(t, user.Data()["blog"], "http://blog.com/")

		googleCreds := user.ProviderCredentials()[googleName]
		if assert.NotNil(t, googleCreds) {
			assert.Equal(t, "uniqueid", googleCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
Esempio n. 8
0
func TestGetUser(t *testing.T) {

	testProvider := new(test.TestProvider)
	creds := new(common.Credentials)

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", creds, testProvider).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{"name":"their-name","id":"uniqueid","login":"******","email":"*****@*****.**","avatar_url":"http://myface.com/","blog":"http://blog.com/"}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	client := &http.Client{Transport: testTripper}
	testProvider.On("GetClient", creds).Return(client, nil)

	data, err := Get(testProvider, creds, "endpoint")

	if assert.NoError(t, err) && assert.NotNil(t, data) {

		assert.Equal(t, data["name"], "their-name")
		assert.Equal(t, data["id"], "uniqueid")
		assert.Equal(t, data["login"], "loginname")
		assert.Equal(t, data["email"], "*****@*****.**")
		assert.Equal(t, data["avatar_url"], "http://myface.com/")
		assert.Equal(t, data["blog"], "http://blog.com/")

	}

}
func TestRateLimitUpdating(t *testing.T) {
	var resp http.Response

	resp.StatusCode = 200
	resp.Header = http.Header{"Date": []string{"Tue, 10 Oct 2013 20:11:05 GMT"}, "X-Ratelimit-Limit": []string{"600,30000"}, "X-Ratelimit-Usage": []string{"300,10000"}}
	RateLimiting.updateRateLimits(&resp)

	if RateLimiting.RequestTime.IsZero() {
		t.Errorf("rate limiting should set request time")
	}

	if v := RateLimiting.FractionReached(); v != 0.5 {
		t.Errorf("fraction of rate limit computed incorrectly, got %v", v)
	}

	resp.Header = http.Header{"Date": []string{"Tue, 10 Oct 2013 20:11:05 GMT"}, "X-Ratelimit-Limit": []string{"600,30000"}, "X-Ratelimit-Usage": []string{"300,27000"}}
	RateLimiting.updateRateLimits(&resp)

	if RateLimiting.RequestTime.IsZero() {
		t.Errorf("rate limiting should set request time")
	}

	if v := RateLimiting.FractionReached(); v != 0.9 {
		t.Errorf("fraction of rate limit computed incorrectly, got %v", v)
	}

	// we'll feed it nonsense
	resp.Header = http.Header{"Date": []string{"Tue, 10 Oct 2013 20:11:05 GMT"}, "X-Ratelimit-Limit": []string{"xxx"}, "X-Ratelimit-Usage": []string{"zzz"}}
	RateLimiting.updateRateLimits(&resp)

	if !RateLimiting.RequestTime.IsZero() {
		t.Errorf("nonsense in rate limiting fields should set next reset to zero")
	}
}
Esempio n. 10
0
func readFakeResponse(statusCode int, file string, header http.Header) (res http.Response) {
	body, _ := os.Open(file)
	response := http.Response{}
	response.Body = body
	response.Header = header
	response.StatusCode = statusCode
	return response
}
Esempio n. 11
0
func TestHandleHttpResponseReturnsErrOnNon200StatusCode(t *testing.T) {
	var response http.Response

	response.StatusCode = 400
	_, err := handleHTTPResponse(&response, nil)

	assertEqual(t, "Non-200 status code received from server: 400", err.Error(), "The returned error was not the expected error")
}
Esempio n. 12
0
// Mocks valid http response containing bucket policy from server.
func generatePolicyResponse(resp *http.Response, policy BucketAccessPolicy) (*http.Response, error) {
	policyBytes, err := json.Marshal(policy)
	if err != nil {
		return nil, err
	}
	resp.StatusCode = http.StatusOK
	resp.Body = ioutil.NopCloser(bytes.NewBuffer(policyBytes))
	return resp, nil
}
Esempio n. 13
0
func TestResponse(t *testing.T) {
	var resp http.Response
	resp.StatusCode = http.StatusOK
	resp.Header = make(http.Header)
	resp.Header["SID"] = []string{"uuid:1337"}
	var buf bytes.Buffer
	resp.Write(&buf)
	t.Logf("%q", buf.String())
}
Esempio n. 14
0
// respFromRecorder builds an http response from a httptest recorder
func respFromRecorder(w *httptest.ResponseRecorder) *http.Response {
	resp := http.Response{}
	resp.StatusCode = w.Code
	resp.Header = w.Header()
	// TODO: fill in the rest of response

	b := w.Body.Bytes()
	resp.Body = ioutil.NopCloser(bytes.NewReader(b))
	return &resp
}
Esempio n. 15
0
func TestHandleHttpResponseReturnsErrOnZeroContentLength(t *testing.T) {
	var response http.Response

	response.StatusCode = 200
	response.ContentLength = 0

	_, err := handleHTTPResponse(&response, nil)

	assertEqual(t, "No content was returned", err.Error(), "The returned error was not the expected error")
}
Esempio n. 16
0
func MakeTestResponseWithBody(body string) (*Response, error) {

	testHTTPResponse := new(http.Response)
	testHTTPResponse.Body = ioutil.NopCloser(bytes.NewBufferString(body))
	testHTTPResponse.StatusCode = 200
	testHTTPResponse.Header = make(map[string][]string)

	return NewResponse(GetTestSession(), testHTTPResponse)

}
func updateRateHandler(w http.ResponseWriter, r *http.Request) {
	if DEBUG_WEB_SERVER {
		fmt.Println("GET AN UPDATE RATE REQUEST")
	}

	rateValueStr := r.FormValue("rate")
	rateValue, err := strconv.ParseInt(rateValueStr, 0, 0)
	var response http.Response
	if err == nil && rateValue > 0 {
		updateRate(int(rateValue))
		if DEBUG_WEB_SERVER {
			fmt.Println("Update lambda, new value =", rate)
		}
		response.StatusCode = 200
	} else {
		response.StatusCode = 400
	}
	response.Write(w)
}
Esempio n. 18
0
// Mocks XML error response from the server.
func generateErrorResponse(resp *http.Response, APIErr APIError, bucketName string) *http.Response {
	// generate error response.
	errorResponse := getAPIErrorResponse(APIErr, bucketName)
	encodedErrorResponse := encodeResponse(errorResponse)
	// write Header.
	resp.StatusCode = APIErr.HTTPStatusCode
	resp.Body = ioutil.NopCloser(bytes.NewBuffer(encodedErrorResponse))

	return resp
}
Esempio n. 19
0
func (c *URLCache) Restore(res *http.Response) {
	res.Status = c.CachedResponse.Status
	res.StatusCode = c.CachedResponse.StatusCode
	res.Header = c.CachedResponse.Header
	res.ContentLength = c.CachedResponse.ContentLength
	res.TransferEncoding = c.CachedResponse.TransferEncoding
	res.Body = &ClosableBuffer{bytes.NewReader(c.CachedBody)}
	res.Header.Set(CachedHeader, CachedHeaderVal)
	res.Header.Set(CachedMD5Header, c.MD5)
}
Esempio n. 20
0
func TestGobResponseSniff1(t *testing.T) {
	var e request
	e.embedMime = new(embedMime)
	ctx := context.Background()

	response := new(http.Response)
	response.StatusCode = 200

	b := []byte{0x37, 0xff, 0x81, 0x03, 0x01, 0x01, 0x07, 0x72, 0x65,
		0x71, 0x75, 0x65, 0x73, 0x74, 0x01, 0xff, 0x82, 0x00,
		0x01, 0x04, 0x01, 0x03, 0x53, 0x74, 0x72, 0x01, 0x0c,
		0x00, 0x01, 0x03, 0x4e, 0x75, 0x6d, 0x01, 0x08, 0x00,
		0x01, 0x04, 0x42, 0x6f, 0x6f, 0x6c, 0x01, 0x02, 0x00,
		0x01, 0x04, 0x4e, 0x75, 0x6c, 0x6c, 0x01, 0x10, 0x00,
		0x00, 0x00, 0x0e, 0xff, 0x82, 0x01, 0x03, 0x62, 0x61,
		0x72, 0x01, 0xfe, 0x24, 0x40, 0x01, 0x01, 0x00}

	buf := bytes.NewBuffer(b)

	response.Body = ioutil.NopCloser(buf)
	response.ContentLength = int64(buf.Len())

	def := encoding.Default()

	e1, err := def.DecodeResponse(&e)(ctx, response)
	if err != nil {
		t.Logf("Decode Request Failed: %s\n", err)
		t.Fail()
	}

	if e1 != &e {
		t.Logf("Returned Result is NOT the same value: %#v\n", e1)
		t.Fail()
	}

	if e.Str != "bar" {
		t.Logf("e.Str != \"bar\": \"%s\"\n", e.Str)
		t.Fail()
	}

	if e.Num != 10.0 {
		t.Logf("e.Num != 10.0: %f\n", e.Num)
		t.Fail()
	}

	if !e.Bool {
		t.Logf("!e.Bool: %f\n", e.Bool)
		t.Fail()
	}

	if e.Null != nil {
		t.Logf("e.Null != nil: %f\n", e.Null)
		t.Fail()
	}
}
Esempio n. 21
0
func RedirectResponse(req *http.Request, url string) *http.Response {
	res := new(http.Response)
	res.StatusCode = 302
	res.ProtoMajor = 1
	res.ProtoMinor = 1
	res.ContentLength = 0
	res.Request = req
	res.Header = make(map[string][]string)
	res.Header.Set("Location", url)
	return res
}
Esempio n. 22
0
// ModifyResponse sets the status code to 400 Bad Request if a loop was
// detected in the request.
func (m *viaModifier) ModifyResponse(res *http.Response) error {
	ctx := martian.NewContext(res.Request)

	if err, _ := ctx.Get(viaLoopKey); err != nil {
		res.StatusCode = 400
		res.Status = http.StatusText(400)

		return err.(error)
	}

	return nil
}
func TestDecodeCustomDecodableErrorGob(t *testing.T) {
	buf := new(bytes.Buffer)
	rw := createResponseWriter(buf)
	ctx := context.Background()

	testErr := CustomDecodableError{
		Code:   50,
		Reason: "Halp",
	}

	// server error...
	rw.WriteHeader(500)
	err := encoding.Gob(0).EncodeResponse()(ctx, rw, &testErr)
	if err != nil {
		t.Fatalf("Unable to Encode Response: %s", err)
	}

	t.Logf("Body Content: %s", buf.String())

	ro := new(http.Response)
	ro.StatusCode = rw.statusCode
	ro.Body = ioutil.NopCloser(buf)
	ro.Header = make(http.Header)
	ro.Header.Set("Content-Type", "application/gob")

	resp := new(request)
	r, err := encoding.Default().DecodeResponse(resp)(ctx, ro)
	if err != nil {
		t.Fatalf("Unable to Decode Response: %s", err)
	}

	t.Logf("Decode Result: %#v", r)
	if got, want := reflect.TypeOf(r), reflect.TypeOf(testErr); got != want {
		t.Fatalf("Type Of:\ngot:\n%s\nwant:\n%s", got, want)
	}

	castErr, ok := r.(CustomDecodableError)
	if !ok {
		t.Fatal("Unable to cast returned response into an error")
	}

	if got, want := castErr.Error(), testErr.Error(); got != want {
		t.Errorf(".Error():\ngot:\n\t%s\nwant:\n\t%s", got, want)
	}

	if got, want := castErr.Code, testErr.Code; got != want {
		t.Errorf("castErr.Code:\ngot:\n\t%d\nwant:\n\t%d", got, want)
	}

	if got, want := castErr.Reason, testErr.Reason; got != want {
		t.Errorf("castErr.Reason:\ngot:\n\t%s\nwant:\n\t%s", got, want)
	}
}
Esempio n. 24
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{
  "id": "631819186",
  "name": "their-name",
  "first_name": "Mat",
  "last_name": "Ryer",
  "link": "https://www.facebook.com/matryer",
  "username": "******",
  "bio": "http://www.stretchr.com/",
  "gender": "male",
  "email": "*****@*****.**",
  "timezone": -6,
  "locale": "en_GB",
  "verified": true,
  "updated_time": "2013-10-03T19:55:28+0000",
  "picture": {
    "url": "http://www.myface.com/"
  }
  }`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {

		assert.Equal(t, user.Name(), "their-name")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from github
		assert.Equal(t, user.Nickname(), "loginname")
		assert.Equal(t, user.Email(), "*****@*****.**")
		assert.Equal(t, user.AvatarURL(), "http://www.myface.com/")
		assert.Equal(t, user.Data()["link"], "https://www.facebook.com/matryer")

		facebookCreds := user.ProviderCredentials()[facebookName]
		if assert.NotNil(t, facebookCreds) {
			assert.Equal(t, "631819186", facebookCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
Esempio n. 25
0
func TestRuntime_CustomTransport(t *testing.T) {
	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})
	result := []task{
		{false, "task 1 content", 1},
		{false, "task 2 content", 2},
	}

	specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml")
	specDoc.Spec().BasePath = "/"
	specDoc.Spec().Host = "localhost:3245"
	specDoc.Spec().Schemes = []string{"ws", "wss", "https"}

	if assert.NoError(t, err) {
		runtime := New(specDoc)
		runtime.Transport = roundTripperFunc(func(req *http.Request) (*http.Response, error) {
			if req.URL.Scheme != "https" {
				return nil, errors.New("this was not a https request")
			}
			var resp http.Response
			resp.StatusCode = 200
			resp.Header = make(http.Header)
			resp.Header.Set("content-type", "application/json")
			buf := bytes.NewBuffer(nil)
			enc := json.NewEncoder(buf)
			enc.Encode(result)
			resp.Body = ioutil.NopCloser(buf)
			return &resp, nil
		})

		res, err := runtime.Submit(&client.Operation{
			ID:     "getTasks",
			Params: rwrtr,
			Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
				if response.Code() == 200 {
					var result []task
					if err := consumer.Consume(response.Body(), &result); err != nil {
						return nil, err
					}
					return result, nil
				}
				return nil, errors.New("Generic error")
			}),
		})

		if assert.NoError(t, err) {
			assert.IsType(t, []task{}, res)
			actual := res.([]task)
			assert.EqualValues(t, result, actual)
		}
	}
}
Esempio n. 26
0
// Mock implementation of MakeRequest. Usually returns an http.Response with
// hard-coded responseBody and statusCode. However, if the request uses a
// nonstandard method, it uses status code 405 (method not allowed)
func (c mockHTTPClient) MakeRequest(req *http.Request) (*http.Response, error) {
	resp := http.Response{}
	resp.StatusCode = c.statusCode

	// basic error checking on request method
	allowedMethods := []string{"GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT"}
	methodValid := false
	for _, method := range allowedMethods {
		if req.Method == method {
			methodValid = true
			break
		}
	}

	if !methodValid {
		resp.StatusCode = 405 // Method not allowed
	}

	resp.Body = ioutil.NopCloser(strings.NewReader(c.responseBody))
	return &resp, nil
}
Esempio n. 27
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{
  "meta":  {
    "code": 200
  },
  "data":  {
    "username": "******",
    "bio": "Programer who loves golang",
    "website": "http://website.com",
    "profile_picture": "http://myinsta.com",
    "full_name": "Raquel H",
    "counts":  {
      "media": 1232323,
      "followed_by": 123,
      "follows": 123
    },
    "id": "12345678"
  }
}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {

		assert.Equal(t, user.Name(), "Raquel H")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from instagram
		assert.Equal(t, user.Nickname(), "maggit")
		assert.Equal(t, user.AvatarURL(), "http://myinsta.com")
		assert.Equal(t, user.Data()["website"], "http://website.com")

		instagramCreds := user.ProviderCredentials()[instagramName]
		if assert.NotNil(t, instagramCreds) {
			assert.Equal(t, "uniqueid", instagramCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
Esempio n. 28
0
// ModifyResponse runs resmod.ModifyResponse and modifies the response to
// include the correct status code and headers if auth error is present.
//
// If an error is returned from resmod.ModifyResponse it is returned.
func (m *Modifier) ModifyResponse(res *http.Response) error {
	ctx := martian.NewContext(res.Request)
	actx := auth.FromContext(ctx)

	err := m.resmod.ModifyResponse(res)

	if actx.Error() != nil {
		res.StatusCode = http.StatusProxyAuthRequired
		res.Header.Set("Proxy-Authenticate", "Basic")
	}

	return err
}
Esempio n. 29
0
func (f *EtagFilter) FilterResponse(request *falcore.Request, res *http.Response) {
	request.CurrentStage.Status = 1 // Skipped (default)
	if if_none_match := request.HttpRequest.Header.Get("If-None-Match"); if_none_match != "" {
		if res.StatusCode == 200 && res.Header.Get("Etag") == if_none_match {
			res.StatusCode = 304
			res.Status = "304 Not Modified"
			res.Body.Close()
			res.Body = nil
			res.ContentLength = 0
			request.CurrentStage.Status = 0 // Success
		}
	}
}
Esempio n. 30
0
func TestHandleHttpResponseReturnsErrOnContentLengthTooLarge(t *testing.T) {
	var response http.Response

	response.StatusCode = 200
	response.ContentLength = MaxFeedSize + 1

	_, err := handleHTTPResponse(&response, nil)

	assertStartsWith(t,
		err.Error(),
		"Feed exceeds maximum size of",
		"The returned error was not the expected error")
}