func TestRequestInterceptor(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Fatal("Server should not be reached!") fmt.Fprintln(w, "Hello, world") })) defer ts.Close() req := NewRequest() req.UseRequest(func(ctx *context.Context, h context.Handler) { ctx.Request.Header.Set("Client", "gentleman") ctx.Response.StatusCode = 201 ctx.Response.Status = "201 Created" ctx.Response.Header.Set("Server", "gentleman") utils.WriteBodyString(ctx.Response, "Hello, gentleman") h.Stop(ctx) }) req.UseRequest(func(ctx *context.Context, h context.Handler) { t.Fatal("middleware should not be called") h.Next(ctx) }) res, err := req.Do() st.Expect(t, err, nil) st.Expect(t, res.StatusCode, 201) st.Expect(t, res.RawRequest.Header.Get("Client"), "gentleman") st.Expect(t, res.RawResponse.Header.Get("Server"), "gentleman") st.Expect(t, res.String(), "Hello, gentleman") }
func TestResponseBytes(t *testing.T) { ctx := NewContext() utils.WriteBodyString(ctx.Response, "foo bar") res, err := buildResponse(ctx) body := res.Bytes() st.Expect(t, err, nil) st.Expect(t, string(body), "foo bar") }
func TestResponseStringError(t *testing.T) { ctx := NewContext() ctx.Error = errors.New("foo error") utils.WriteBodyString(ctx.Response, "foo bar") res, err := buildResponse(ctx) body := res.String() st.Reject(t, err, nil) st.Expect(t, body, "") }
func TestResponseSaveToFile(t *testing.T) { ctx := NewContext() utils.WriteBodyString(ctx.Response, "hello world") res, _ := buildResponse(ctx) err := res.SaveToFile("body.tmp") st.Expect(t, err, nil) defer os.Remove("body.tmp") body, err := ioutil.ReadFile("body.tmp") st.Expect(t, err, nil) st.Expect(t, string(body), "hello world") }
func TestResponseXML(t *testing.T) { type xml struct { Foo string `xml:"foo"` } xmlData := &xml{} ctx := NewContext() utils.WriteBodyString(ctx.Response, `<xml><foo>bar</foo></xml>`) res, _ := buildResponse(ctx) err := res.XML(xmlData, nil) st.Expect(t, err, nil) st.Expect(t, xmlData.Foo, "bar") }
func TestResponseJSON(t *testing.T) { type jsonData struct { Foo string `json:foo` } json := &jsonData{} ctx := NewContext() utils.WriteBodyString(ctx.Response, `{"foo":"bar"}`) res, _ := buildResponse(ctx) err := res.JSON(json) st.Expect(t, err, nil) st.Expect(t, json.Foo, "bar") }
func TestResponseReaderBuffer(t *testing.T) { ctx := NewContext() utils.WriteBodyString(ctx.Response, "foo bar") res, err := buildResponse(ctx) res.RawResponse.ContentLength = 7 body := res.Bytes() st.Expect(t, err, nil) st.Expect(t, string(body), "foo bar") st.Expect(t, res.buffer.String(), "foo bar") res.ClearInternalBuffer() st.Expect(t, string(res.Bytes()), "") }