Example #1
0
func testContentType(t *testing.T, r *http.Request, rec *httptest.ResponseRecorder, expected string) {
	ct := rec.Header().Get("content-type")
	if !strings.EqualFold(ct, expected) {
		t.Errorf("Unexpected content-type for %q: %s, expected: %s",
			r.URL.String(), ct, expected)
	}
}
func recorderToResponse(recorder *httptest.ResponseRecorder) *http.Response {
	return &http.Response{
		StatusCode: recorder.Code,
		Body:       jsh.CreateReadCloser(recorder.Body.Bytes()),
		Header:     recorder.Header(),
	}
}
Example #3
0
// checkIndex is like assertIndex but returns an error
func checkIndex(resp *httptest.ResponseRecorder) error {
	header := resp.Header().Get("X-Consul-Index")
	if header == "" || header == "0" {
		return fmt.Errorf("Bad: %v", header)
	}
	return nil
}
Example #4
0
func (m *MockRender) Header() http.Header {

	r := httptest.ResponseRecorder{}
	m.Called()

	return r.Header()
}
Example #5
0
func ReadHeadersFromResponse(writer *httptest.ResponseRecorder) map[string]string {
	headers := map[string]string{}
	for k, v := range writer.Header() {
		log.Println(k, v)
		headers[k] = strings.Join(v, " ")
	}
	return headers
}
Example #6
0
// Write the contents of a ResponseRecorder to a ResponseWriter
func writeRecorder(w http.ResponseWriter, recorder *httptest.ResponseRecorder) {
	for key, values := range recorder.HeaderMap {
		for _, value := range values {
			w.Header().Set(key, value)
		}
	}
	recorder.Body.WriteTo(w)
	recorder.Flush()
}
Example #7
0
func (s *Stack) Write(response *Response, rec *httptest.ResponseRecorder) {
	for key, values := range rec.Header() {
		for _, value := range values {
			response.header.Add(key, value)
		}
	}
	response.buffer.Write(rec.Body.Bytes())
	response.code = rec.Code
}
Example #8
0
// Test that the headers and body match.
func assertHttpMatchRecorder(t *testing.T, recorder *httptest.ResponseRecorder,
	expectedStatus int, expectedHeaders http.Header, expectedBody string) {
	assert.Equal(t, expectedStatus, recorder.Code)

	// Verify that headers match. Order shouldn't matter.
	assert.Equal(t, recorder.Header(), expectedHeaders)

	// Convert the body to a string.
	assert.Equal(t, expectedBody, recorder.Body.String())
}
Example #9
0
func assertJSONResponse(t *testing.T, expectedCode int, expectedResponse string, w *httptest.ResponseRecorder) {
	assert.Equal(t, expectedCode, w.Code)
	assert.Equal(t, "application/json", w.Header().Get("content-type"))

	var expected, actual interface{}
	require.NoError(t, json.Unmarshal([]byte(expectedResponse), &expected))
	require.NoError(t, json.Unmarshal(w.Body.Bytes(), &actual))

	assert.Equal(t, expected, actual)
}
Example #10
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
}
func assertResponseWithStatusAndMessage(t *testing.T, res *httptest.ResponseRecorder, code int, status, message string) {
	var apiMessage responses.APIMessage
	json.NewDecoder(res.Body).Decode(&apiMessage)

	assert.Equal(t, code, res.Code)
	assert.Equal(t, "application/json; charset=UTF-8", res.Header().Get("Content-Type"))

	assert.Equal(t, status, apiMessage.Status)
	assert.Equal(t, message, apiMessage.Message)
}
Example #12
0
// copyResponse copies all relevant info from rec to rw.
func copyResponse(rw http.ResponseWriter, rec *httptest.ResponseRecorder) {

	// copy the headers
	for k, v := range rec.Header() {
		rw.Header()[k] = v
	}
	// copy the code
	rw.WriteHeader(rec.Code)
	// copy the body
	rw.Write(rec.Body.Bytes())
}
Example #13
0
// DoRequest invokes a request on the given handler with the given
// parameters.
func DoRequest(c *gc.C, p DoRequestParams) *httptest.ResponseRecorder {
	if p.Method == "" {
		p.Method = "GET"
	}
	if p.Do == nil {
		p.Do = http.DefaultClient.Do
	}
	srv := httptest.NewServer(p.Handler)
	defer srv.Close()

	if p.JSONBody != nil {
		data, err := json.Marshal(p.JSONBody)
		c.Assert(err, jc.ErrorIsNil)
		p.Body = bytes.NewReader(data)
	}
	// Note: we avoid NewRequest's odious reader wrapping by using
	// a custom nopCloser function.
	req, err := http.NewRequest(p.Method, srv.URL+p.URL, nopCloser(p.Body))
	c.Assert(err, jc.ErrorIsNil)
	if p.JSONBody != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	for key, val := range p.Header {
		req.Header[key] = val
	}
	if p.ContentLength != 0 {
		req.ContentLength = p.ContentLength
	} else {
		req.ContentLength = bodyContentLength(p.Body)
	}
	if p.Username != "" || p.Password != "" {
		req.SetBasicAuth(p.Username, p.Password)
	}
	for _, cookie := range p.Cookies {
		req.AddCookie(cookie)
	}
	resp, err := p.Do(req)
	if p.ExpectError != "" {
		c.Assert(err, gc.ErrorMatches, p.ExpectError)
		return nil
	}
	c.Assert(err, jc.ErrorIsNil)
	defer resp.Body.Close()

	// TODO(rog) don't return a ResponseRecorder because we're not actually
	// using httptest.NewRecorder ?
	var rec httptest.ResponseRecorder
	rec.HeaderMap = resp.Header
	rec.Code = resp.StatusCode
	rec.Body = new(bytes.Buffer)
	_, err = io.Copy(rec.Body, resp.Body)
	c.Assert(err, jc.ErrorIsNil)
	return &rec
}
Example #14
0
// getIndex parses X-Consul-Index
func getIndex(t *testing.T, resp *httptest.ResponseRecorder) uint64 {
	header := resp.Header().Get("X-Consul-Index")
	if header == "" {
		t.Fatalf("Bad: %v", header)
	}
	val, err := strconv.Atoi(header)
	if err != nil {
		t.Fatalf("Bad: %v", header)
	}
	return uint64(val)
}
Example #15
0
func ReadHeadersFromResponse(writer *httptest.ResponseRecorder) (map[string]string, []models.YaagAnnotationHeader) {
	headers := map[string]string{}
	yaagAnnotations := []models.YaagAnnotationHeader{}
	for k, v := range writer.Header() {
		if strings.HasPrefix(k, "Yaag-Annotation") {
			yaagAnnotations = append(yaagAnnotations, annotations.New(k, strings.Join(v, " ")))
		} else {
			headers[k] = strings.Join(v, " ")
		}
	}
	return headers, yaagAnnotations
}
Example #16
0
func (m mockCacher) Put(key string, r *httptest.ResponseRecorder) *CachedResponse {
	specHeaders := make(map[string]string)
	for k, v := range r.Header() {
		specHeaders[k] = strings.Join(v, ", ")
	}

	m.data[key] = &CachedResponse{
		StatusCode: r.Code,
		Body:       r.Body.Bytes(),
		Headers:    specHeaders,
	}
	return m.data[key]
}
Example #17
0
func compressedRequest(w *httptest.ResponseRecorder, compression string) {
	CompressHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Length", strconv.Itoa(9*1024))
		for i := 0; i < 1024; i++ {
			io.WriteString(w, "Gorilla!\n")
		}
	})).ServeHTTP(w, &http.Request{
		Method: "GET",
		Header: http.Header{
			"Accept-Encoding": []string{compression},
		},
	})

}
Example #18
0
File: http.go Project: cmars/oo
// DoRequest is the same as Do except that it returns
// an httptest.ResponseRecorder instead of an http.Response.
// This function exists for backward compatibility reasons.
func DoRequest(c *gc.C, p DoRequestParams) *httptest.ResponseRecorder {
	resp := Do(c, p)
	if p.ExpectError != "" {
		return nil
	}
	defer resp.Body.Close()
	var rec httptest.ResponseRecorder
	rec.HeaderMap = resp.Header
	rec.Code = resp.StatusCode
	rec.Body = new(bytes.Buffer)
	_, err := io.Copy(rec.Body, resp.Body)
	c.Assert(err, jc.ErrorIsNil)
	return &rec
}
Example #19
0
func checkResponseRecorder(t *testing.T, rr *httptest.ResponseRecorder, code int, header map[string][]string, body string) {
	if !rr.Flushed {
		t.Fatal("ResponseRecorder not flushed")
	}

	if a, e := rr.Code, code; a != e {
		t.Error(a, "!=", e)
	}
	if a, e := map[string][]string(rr.Header()), header; !reflect.DeepEqual(a, e) {
		t.Error(a, "!=", e)
	}
	if a, e := rr.Body.Bytes(), []byte(body); !bytes.Equal(a, e) {
		t.Error(a, "!=", e)
	}
}
func checkHeaders(t *testing.T, res *httptest.ResponseRecorder, requiredHeaders map[string]string) {
	for headerKey, expectedHeaderValue := range requiredHeaders {
		actualHeaderValue := res.Header().Get(headerKey)
		if actualHeaderValue != expectedHeaderValue {
			// N.B. the http library does not distinguish between header
			// entries that have an empty "" value, and non-existing entries
			if expectedHeaderValue != "" {
				t.Errorf("Expected header %q to be %q but it was %q", headerKey, expectedHeaderValue, actualHeaderValue)
				t.Logf("Full headers: %q", res.Header())
			} else {
				t.Errorf("Expected header %q to not be present, or to be an empty string (\"\"), but it was %q", headerKey, actualHeaderValue)
			}
		}
	}
}
Example #21
0
func TestWildcardCompeting(t *testing.T) {
	var (
		method       string = "GET"
		mux          *Mux   = New()
		patternOne   string = "/*"
		pathOne      string = "/bar/baz"
		wantOne      string = "bar/baz"
		patternTwo   string = "/foo/*"
		pathTwo      string = "/foo/baz"
		wantTwo      string = "baz"
		patternThree string = "/foo/bar/*"
		pathThree    string = "/foo/bar/bar/baz"
		wantThree    string = "bar/baz"
		req          *http.Request
		res          *httptest.ResponseRecorder
	)
	handler := func(res http.ResponseWriter, _ *http.Request, ctx *Context) {
		res.WriteHeader(http.StatusOK)
		res.Write([]byte(ctx.Params["*"]))
	}
	mux.On(method, patternOne, handler)
	mux.On(method, patternTwo, handler)
	mux.On(method, patternThree, handler)
	req, _ = http.NewRequest(method, pathOne, nil)
	res = httptest.NewRecorder()
	mux.ServeHTTP(res, req)
	if body := res.Body.String(); body != wantOne {
		t.Errorf(
			"%s %s (%s) got %s want %s",
			method, pathOne, patternOne, body, wantOne)
	}
	req, _ = http.NewRequest(method, pathTwo, nil)
	res = httptest.NewRecorder()
	mux.ServeHTTP(res, req)
	if body := res.Body.String(); body != wantTwo {
		t.Errorf(
			"%s %s (%s) got %s want %s",
			method, pathTwo, patternTwo, body, wantTwo)
	}
	req, _ = http.NewRequest(method, pathThree, nil)
	res = httptest.NewRecorder()
	mux.ServeHTTP(res, req)
	if body := res.Body.String(); body != wantThree {
		t.Errorf(
			"%s %s (%s) got %s want %s",
			method, pathThree, patternThree, body, wantThree)
	}
}
Example #22
0
// AssertJSONResponse asserts that the given response recorder has
// recorded the given HTTP status, response body and content type. If
// expectBody is of type BodyAsserter it will be called with the response
// body to ensure the response is correct.
func AssertJSONResponse(c *gc.C, rec *httptest.ResponseRecorder, expectStatus int, expectBody interface{}) {
	c.Assert(rec.Code, gc.Equals, expectStatus, gc.Commentf("body: %s", rec.Body.Bytes()))

	// Ensure the response includes the expected body.
	if expectBody == nil {
		c.Assert(rec.Body.Bytes(), gc.HasLen, 0)
		return
	}
	c.Assert(rec.Header().Get("Content-Type"), gc.Equals, "application/json")
	if assertBody, ok := expectBody.(BodyAsserter); ok {
		var data json.RawMessage
		err := json.Unmarshal(rec.Body.Bytes(), &data)
		c.Assert(err, jc.ErrorIsNil, gc.Commentf("body: %s", rec.Body.Bytes()))
		assertBody(c, data)
		return
	}
	c.Assert(rec.Body.String(), jc.JSONEquals, expectBody)
}
func checkStatusCode(t *testing.T, res *httptest.ResponseRecorder, statusCode int) {
	respBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatalf("Could not read response body: %v", err)
	}
	// make sure we get at least a few bytes of a response body...
	// even http 303 should have some body, see
	// https://tools.ietf.org/html/rfc7231#section-6.4.4
	if len(respBody) < 20 {
		t.Error("Expected a response body (at least 20 bytes), but get less (or none).")
		t.Logf("Headers: %s", res.Header())
		t.Logf("Response received:\n%s", string(respBody))
	}
	if res.Code != statusCode {
		t.Errorf("Expected status code %v but got %v", statusCode, res.Code)
		t.Logf("Headers: %s", res.Header())
		t.Logf("Response received:\n%s", string(respBody))
	}
}
Example #24
0
func TestWildcardParams(t *testing.T) {
	var (
		method  string = "GET"
		mux     *Mux   = New()
		pattern string = "/foo/{bar}/*"
		path    string = "/foo/ABC/baz"
		want    string = "ABC"
		req     *http.Request
		res     *httptest.ResponseRecorder
	)
	handler := func(res http.ResponseWriter, _ *http.Request, ctx *Context) {
		res.WriteHeader(http.StatusOK)
		res.Write([]byte(ctx.Params["bar"]))
	}
	mux.On(method, pattern, handler)
	req, _ = http.NewRequest(method, path, nil)
	res = httptest.NewRecorder()
	mux.ServeHTTP(res, req)
	if body := res.Body.String(); body != want {
		t.Errorf("%s %s (%s) got %s want %s", method, path, pattern, body, want)
	}
}
Example #25
0
func TestNotFoundCustom(t *testing.T) {
	var (
		method       string = "GET"
		mux          *Mux   = New()
		pathFound    string = "/foo/bar"
		pathLost     string = "/foo/bar/baz"
		patternFound string = "/foo/bar"
		patternLost  string = "/*"
		req          *http.Request
		res          *httptest.ResponseRecorder
		wantFound    int = http.StatusOK
		wantLost     int = http.StatusTeapot
	)
	handlerFound := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		res.WriteHeader(http.StatusOK)
		res.Write([]byte("found!"))
	})
	handlerLost := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		res.WriteHeader(http.StatusTeapot)
		res.Write([]byte("not found!"))
	})
	// Test found to make sure wildcard doesn't overtake everything.
	req, _ = http.NewRequest(method, pathFound, nil)
	res = httptest.NewRecorder()
	mux.On(method, patternFound, handlerFound)
	mux.ServeHTTP(res, req)
	if res.Code != wantFound {
		t.Errorf(
			"%s %s (%s) got %d want %d",
			method, pathFound, patternFound, res.Code, wantFound)
	}
	// Test lost to make sure wildcard can gets non-pattern-matching paths.
	req, _ = http.NewRequest(method, pathLost, nil)
	res = httptest.NewRecorder()
	mux.On(method, patternLost, handlerLost)
	mux.ServeHTTP(res, req)
	if res.Code != wantLost {
		t.Errorf(
			"%s %s (%s) got %d want %d",
			method, pathLost, patternLost, res.Code, wantLost)
	}
}
Example #26
0
func NewResponse(resp *httptest.ResponseRecorder) *Response {
	content := resp.Body.Bytes()
	contentType := resp.Header().Get("Content-Type")
	contentEncoding := resp.Header().Get("Content-Encoding")

	return &Response{
		StatusCode: resp.Code,
		Header:     NewHeader(resp.Header()),
		Body:       NewBody(content, contentType, contentEncoding),
	}
}
Example #27
0
// Put stores a CachedResponse for a given key and response
func (c DiskCacher) Put(key string, resp *httptest.ResponseRecorder) *CachedResponse {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	skipDisk := resp.Header().Get("_chameleon-seeded-skip-disk") != ""
	if skipDisk {
		resp.Header().Del("_chameleon-seeded-skip-disk")
	}
	skipDisk = skipDisk || c.memory

	specHeaders := make(map[string]string)
	for k, v := range resp.Header() {
		specHeaders[k] = strings.Join(v, ", ")
	}

	if !skipDisk {
		specs := c.loadSpecs()

		newSpec := Spec{
			Key: key,
			SpecResponse: SpecResponse{
				StatusCode:  resp.Code,
				ContentFile: key,
				Headers:     specHeaders,
			},
		}

		specs = append(specs, newSpec)

		contentFilePath := path.Join(c.dataDir, key)
		err := c.FileSystem.WriteFile(contentFilePath, resp.Body.Bytes())
		if err != nil {
			panic(err)
		}

		specBytes, err := json.MarshalIndent(specs, "", "    ")
		err = c.FileSystem.WriteFile(c.specPath, specBytes)
		if err != nil {
			panic(err)
		}
	}

	c.cache[key] = &CachedResponse{
		StatusCode: resp.Code,
		Headers:    specHeaders,
		Body:       resp.Body.Bytes(),
	}

	return c.cache[key]
}
Example #28
0
func (m prettyJSONContentMarshaler) Unmarshal(data []byte, i interface{}) error {
	return json.Unmarshal(data, i)
}

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

	var usePointerResources bool

	requestHandlingTests := func() {

		var (
			source          *fixtureSource
			post1Json       map[string]interface{}
			post1LinkedJSON []map[string]interface{}
			post2Json       map[string]interface{}
			post3Json       map[string]interface{}

			api *API
			rec *httptest.ResponseRecorder
		)

		BeforeEach(func() {
			source = &fixtureSource{map[string]*Post{
				"1": &Post{
					ID:    "1",
					Title: "Hello, World!",
					Author: &User{
						ID:   "1",
						Name: "Dieter",
					},
					Comments: []Comment{Comment{
Example #29
0
	"github.com/cloudfoundry-incubator/notifications/testing/mocks"
	"github.com/cloudfoundry-incubator/notifications/v2/collections"
	"github.com/cloudfoundry-incubator/notifications/v2/web/senders"
	"github.com/ryanmoran/stack"

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

var _ = Describe("GetHandler", func() {
	var (
		handler           senders.GetHandler
		sendersCollection *mocks.SendersCollection
		context           stack.Context
		writer            *httptest.ResponseRecorder
		request           *http.Request
		database          *mocks.Database
		conn              *mocks.Connection
	)

	BeforeEach(func() {
		conn = mocks.NewConnection()
		database = mocks.NewDatabase()
		database.ConnectionCall.Returns.Connection = conn

		context = stack.NewContext()
		context.Set("client_id", "some-client-id")
		context.Set("database", database)

		sendersCollection = mocks.NewSendersCollection()
Example #30
0
// assertIndex tests that X-Consul-Index is set and non-zero
func assertIndex(t *testing.T, resp *httptest.ResponseRecorder) {
	header := resp.Header().Get("X-Consul-Index")
	if header == "" || header == "0" {
		t.Fatalf("Bad: %v", header)
	}
}