Ejemplo n.º 1
0
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")
	}
}
Ejemplo n.º 2
0
func SimpleResponse(req *http.Request, status int, headers http.Header, body string) *http.Response {
	res := new(http.Response)
	body_rdr := (*fixedResBody)(strings.NewReader(body))
	res.StatusCode = status
	res.ProtoMajor = 1
	res.ProtoMinor = 1
	res.ContentLength = int64((*strings.Reader)(body_rdr).Len())
	res.Request = req
	res.Header = make(map[string][]string)
	res.Body = body_rdr
	if headers != nil {
		res.Header = headers
	}
	return res
}
Ejemplo n.º 3
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())
		}

	}

}
Ejemplo n.º 4
0
func TestNtlmHeaderParseInvalid(t *testing.T) {
	res := http.Response{}
	res.Header = make(map[string][]string)
	res.Header.Add("Www-Authenticate", base64.StdEncoding.EncodeToString([]byte("NTLM I am a moose")))
	_, err := parseChallengeResponse(&res)
	assert.NotEqual(t, err, nil)
}
Ejemplo n.º 5
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/")

	}

}
Ejemplo n.º 6
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)

}
Ejemplo 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(`{"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)
	}

}
Ejemplo n.º 8
0
func NewTestResponse(status float64, data interface{}, errors []map[string]interface{}, context string, changeInfo api.ChangeInfo) *api.Response {

	httpResponse := new(http.Response)

	sro := map[string]interface{}{common.ResponseObjectFieldStatusCode: status,
		common.ResponseObjectFieldData:       data,
		common.ResponseObjectFieldErrors:     errors,
		common.ResponseObjectFieldChangeInfo: changeInfo,
		common.ResponseObjectFieldContext:    context}

	session := api.NewSession("project", "company", "apiKey")

	responseBytes, _ := session.Codec().Marshal(sro, nil)
	httpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(responseBytes))
	httpResponse.Header = make(map[string][]string)

	response, newResponseErr := api.NewResponse(session, httpResponse)

	if newResponseErr != nil {
		panic(fmt.Sprintf("NewTestResponse: %s", newResponseErr))
	}

	return response

}
Ejemplo n.º 9
0
// SetResponseHeaderValues adds a header containing all the passed string values.
func SetResponseHeaderValues(resp *http.Response, h string, values []string) {
	if resp.Header == nil {
		resp.Header = make(http.Header)
	}
	for _, v := range values {
		resp.Header.Add(h, v)
	}
}
Ejemplo n.º 10
0
func TestNtlmHeaderParseValid(t *testing.T) {
	res := http.Response{}
	res.Header = make(map[string][]string)
	res.Header.Add("Www-Authenticate", "NTLM "+base64.StdEncoding.EncodeToString([]byte("I am a moose")))
	bytes, err := parseChallengeResponse(&res)
	assert.Equal(t, err, nil)
	assert.Equal(t, strings.HasPrefix(string(bytes), "NTLM"), false)
}
Ejemplo n.º 11
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
}
Ejemplo n.º 12
0
// Generate an http.Response using the basic fields
func SimpleResponse(req *http.Request, status int, headers http.Header, contentLength int64, body io.Reader) *http.Response {
	res := new(http.Response)
	res.StatusCode = status
	res.ProtoMajor = 1
	res.ProtoMinor = 1
	res.ContentLength = contentLength
	res.Request = req
	res.Header = make(map[string][]string)
	if body_rdr, ok := body.(io.ReadCloser); ok {
		res.Body = body_rdr
	} else if body != nil {
		res.Body = ioutil.NopCloser(body)
	}
	if headers != nil {
		res.Header = headers
	}
	return res
}
Ejemplo 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())
}
Ejemplo n.º 14
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)
}
Ejemplo n.º 15
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)

}
Ejemplo n.º 16
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
}
Ejemplo n.º 17
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
}
Ejemplo n.º 18
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())
		}

	}

}
Ejemplo n.º 19
0
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)
	}
}
Ejemplo n.º 20
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)
		}
	}
}
Ejemplo n.º 21
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())
		}

	}

}
Ejemplo n.º 22
0
func (res *HTTPResponseEvent) ToResponse(body bool) *http.Response {
	raw := new(http.Response)
	raw.Header = res.Headers
	raw.ProtoMajor = 1
	raw.ProtoMinor = 1
	raw.StatusCode = int(res.StatusCode)
	raw.Status = http.StatusText(raw.StatusCode)
	raw.TransferEncoding = res.Headers["TransferEncoding"]
	if body {
		raw.Body = NewHTTPBody(res.GetContentLength(), res.Content)
	}
	return raw
}
Ejemplo n.º 23
0
func TestNtlmHeaderParseInvalidLength(t *testing.T) {
	res := http.Response{}
	res.Header = make(map[string][]string)
	res.Header.Add("Www-Authenticate", "NTL")
	ret, err := parseChallengeResponse(&res)
	if ret != nil {
		t.Errorf("Unexpected challenge response: %v", ret)
	}

	if err == nil {
		t.Errorf("Expected error, got none!")
	}
}
Ejemplo 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(`{
  "display_name":"JMWizzler",
  "email":"*****@*****.**",
  "external_urls":{
    "spotify":"https://open.spotify.com/user/wizzler"
  },
  "href":"https://api.spotify.com/v1/users/wizzler",
  "id":"wizzler",
  "images":[{
    "height":null,
    "url":"https://fbcdn.example.com/2330_n.jpg",
    "width":null
  }],
  "type":"user",
  "uri":"spotify:user:wizzler"
}`))
	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(), "JMWizzler")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from spotify
		assert.Equal(t, user.Nickname(), "") // doesn't come from spotify
		assert.Equal(t, user.Email(), "*****@*****.**")
		assert.Equal(t, user.AvatarURL(), "https://fbcdn.example.com/2330_n.jpg")
		assert.Equal(t, user.Data()["href"], "https://api.spotify.com/v1/users/wizzler")

		spotifyCreds := user.ProviderCredentials()[spotifyName]
		if assert.NotNil(t, spotifyCreds) {
			assert.Equal(t, "wizzler", spotifyCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
Ejemplo n.º 25
0
func (c *filterContext) Serve(res *http.Response) {
	res.Request = c.Request()

	if res.Header == nil {
		res.Header = make(http.Header)
	}

	if res.Body == nil {
		res.Body = &bodyBuffer{&bytes.Buffer{}}
	}

	c.servedWithResponse = true
	c.res = res
}
Ejemplo n.º 26
0
func TestResponse(t *testing.T) {
	under := new(http.Response)
	under.Status = "the status message"
	under.StatusCode = 392
	under.Header = make(http.Header)
	under.Header.Set("Blah", "blah blah")
	under.Body = ioutil.NopCloser(bytes.NewBufferString("some content"))

	var resp runtime.ClientResponse = response{under}
	assert.EqualValues(t, under.StatusCode, resp.Code())
	assert.Equal(t, under.Status, resp.Message())
	assert.Equal(t, "blah blah", resp.GetHeader("blah"))
	assert.Equal(t, under.Body, resp.Body())
}
Ejemplo n.º 27
0
func TestRuntime_CustomTransport(t *testing.T) {
	rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
		return nil
	})
	result := []task{
		{false, "task 1 content", 1},
		{false, "task 2 content", 2},
	}

	rt := New("localhost:3245", "/", []string{"ws", "wss", "https"})
	rt.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 := rt.Submit(&runtime.ClientOperation{
		ID:          "getTasks",
		Method:      "GET",
		PathPattern: "/",
		Schemes:     []string{"ws", "wss", "https"},
		Params:      rwrtr,
		Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.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)
	}
}
Ejemplo n.º 28
0
func TestResponse_HTTPStatusCode(t *testing.T) {

	session := GetTestSession()

	httpResponse := new(http.Response)
	httpResponse.Body = ioutil.NopCloser(bytes.NewBufferString(`{}`))
	httpResponse.StatusCode = http.StatusNotAcceptable
	httpResponse.Header = make(map[string][]string)

	response, err := NewResponse(session, httpResponse)

	if assert.Nil(t, err) {
		assert.Equal(t, http.StatusNotAcceptable, response.HTTPStatusCode())
	}

}
Ejemplo n.º 29
0
func (t *BadJSONTransport) RoundTrip(r *http.Request) (*http.Response, error) {
	resp := http.Response{
		StatusCode: 200,
		Proto:      "HTTP/1.0",
		ProtoMajor: 1,
		ProtoMinor: 0,
	}

	header := http.Header{}
	header.Set("Content-Type", "text/javascript; charset=\"UTF-8\"")
	resp.Header = header

	resp.Body = ioutil.NopCloser(bytes.NewBuffer([]byte("i'm bad")))

	return &resp, nil
}
Ejemplo n.º 30
0
func (res *HTTPResponseEvent) ToResponse() *http.Response {
	raw := new(http.Response)
	raw.Proto = "HTTP"
	raw.ProtoMajor = 1
	raw.ProtoMinor = 1
	//raw.Close = true
	raw.ContentLength = int64(res.Content.Len())
	raw.Header = make(http.Header)
	raw.StatusCode = int(res.Status)
	res.SetHeader("Content-Length", strconv.Itoa(res.Content.Len()))
	for i := 0; i < len(res.Headers); i++ {
		header := res.Headers[i]
		if strings.EqualFold(header.Name, "Set-Cookie") || strings.EqualFold(header.Name, "Set-Cookie2") {
			tmp := strings.Split(header.Value, ",")
			if len(tmp) > 1 {
				var vlist list.List
				for _, v := range tmp {
					if (!strings.Contains(v, "=") || strings.Index(v, "=") > strings.Index(v, ";")) && vlist.Len() > 0 {
						v = vlist.Back().Value.(string) + "," + v
						vlist.Remove(vlist.Back())
						vlist.PushBack(v)
						//headerValues.add(headerValues.removeLast() + "," + v);
					} else {
						vlist.PushBack(v)
					}
				}
				e := vlist.Front()
				for {
					if e == nil {
						break
					}
					raw.Header.Add(header.Name, e.Value.(string))
					e = e.Next()
				}
			} else {
				raw.Header.Add(header.Name, header.Value)
			}
		} else {
			raw.Header.Add(header.Name, header.Value)
		}
	}
	if raw.ContentLength > 0 {
		raw.Body = ioutil.NopCloser(&res.Content)
	}
	return raw
}