Skip to content

Commit

Permalink
Total coverage for middleware
Browse files Browse the repository at this point in the history
Signed-off-by: Vishal Rana <[email protected]>
  • Loading branch information
vishr committed May 30, 2015
1 parent b526a0d commit a9e49e2
Show file tree
Hide file tree
Showing 13 changed files with 222 additions and 229 deletions.
28 changes: 14 additions & 14 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,16 @@ func (c *Context) Param(name string) (value string) {
return
}

// Get retrieves data from the context.
func (c *Context) Get(key string) interface{} {
return c.store[key]
}

// Set saves data in the context.
func (c *Context) Set(key string, val interface{}) {
c.store[key] = val
}

// Bind binds the request body into specified type v. Default binder does it
// based on Content-Type header.
func (c *Context) Bind(i interface{}) error {
Expand All @@ -82,29 +92,29 @@ func (c *Context) Render(code int, name string, data interface{}) error {
if c.echo.renderer == nil {
return RendererNotRegistered
}
c.response.Header().Set(ContentType, TextHTML+"; charset=utf-8")
c.response.Header().Set(ContentType, TextHTML)
c.response.WriteHeader(code)
return c.echo.renderer.Render(c.response, name, data)
}

// JSON sends an application/json response with status code.
func (c *Context) JSON(code int, i interface{}) error {
c.response.Header().Set(ContentType, ApplicationJSON+"; charset=utf-8")
c.response.Header().Set(ContentType, ApplicationJSON)
c.response.WriteHeader(code)
return json.NewEncoder(c.response).Encode(i)
}

// String sends a text/plain response with status code.
func (c *Context) String(code int, s string) error {
c.response.Header().Set(ContentType, TextPlain+"; charset=utf-8")
c.response.Header().Set(ContentType, TextPlain)
c.response.WriteHeader(code)
_, err := c.response.Write([]byte(s))
return err
}

// HTML sends a text/html response with status code.
func (c *Context) HTML(code int, html string) error {
c.response.Header().Set(ContentType, TextHTML+"; charset=utf-8")
c.response.Header().Set(ContentType, TextHTML)
c.response.WriteHeader(code)
_, err := c.response.Write([]byte(html))
return err
Expand All @@ -126,16 +136,6 @@ func (c *Context) Error(err error) {
c.echo.httpErrorHandler(err, c)
}

// Get retrieves data from the context.
func (c *Context) Get(key string) interface{} {
return c.store[key]
}

// Set saves data in the context.
func (c *Context) Set(key string, val interface{}) {
c.store[key] = val
}

func (c *Context) reset(r *http.Request, w http.ResponseWriter, e *Echo) {
c.request = r
c.response.reset(w)
Expand Down
150 changes: 83 additions & 67 deletions context_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package echo

import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"text/template"

"strings"

"github.com/stretchr/testify/assert"
)

Expand All @@ -24,117 +24,133 @@ func (t *Template) Render(w io.Writer, name string, data interface{}) error {
}

func TestContext(t *testing.T) {
b, _ := json.Marshal(u1)
r, _ := http.NewRequest(POST, "/users/1", bytes.NewReader(b))
c := NewContext(r, NewResponse(httptest.NewRecorder()), New())
usr := `{"id":"1","name":"Joe"}`
req, _ := http.NewRequest(POST, "/", strings.NewReader(usr))
rec := httptest.NewRecorder()
c := NewContext(req, NewResponse(rec), New())

// Request
assert.NotEmpty(t, c.Request())
assert.NotNil(t, c.Request())

// Response
assert.NotEmpty(t, c.Response())
assert.NotNil(t, c.Response())

// Socket
assert.Nil(t, c.Socket())

//------
// Bind
//------

// JSON
r.Header.Set(ContentType, ApplicationJSON)
u2 := new(user)
if he := c.Bind(u2); he != nil {
t.Errorf("bind %#v", he)
}
verifyUser(u2, t)

// FORM
r.Header.Set(ContentType, ApplicationForm)
u2 = new(user)
if he := c.Bind(u2); he != nil {
t.Errorf("bind %#v", he)
}
// TODO: add verification

// Unsupported
r.Header.Set(ContentType, "")
u2 = new(user)
if he := c.Bind(u2); he == nil {
t.Errorf("bind %#v", he)
}
// TODO: add verification

//-------
// Param
//-------

// By id
c.pnames = []string{"id"}
c.pvalues = []string{"1"}
if c.P(0) != "1" {
t.Error("param id should be 1")
}
assert.Equal(t, "1", c.P(0))

// By name
if c.Param("id") != "1" {
t.Error("param id should be 1")
}
assert.Equal(t, "1", c.Param("id"))

// Store
c.Set("user", u1.Name)
n := c.Get("user")
if n != u1.Name {
t.Error("user name should be Joe")
}
c.Set("user", "Joe")
assert.Equal(t, "Joe", c.Get("user"))

//------
// Bind
//------

// JSON
testBind(t, c, ApplicationJSON)

// TODO: Form
c.request.Header.Set(ContentType, ApplicationForm)
u := new(user)
err := c.Bind(u)
assert.NoError(t, err)

// Unsupported
c.request.Header.Set(ContentType, "")
u = new(user)
err = c.Bind(u)
assert.Error(t, err)

//--------
// Render
//--------

tpl := &Template{
templates: template.Must(template.New("hello").Parse("{{.}}")),
templates: template.Must(template.New("hello").Parse("Hello, {{.}}!")),
}
c.echo.renderer = tpl
if he := c.Render(http.StatusOK, "hello", "Joe"); he != nil {
t.Errorf("render %#v", he.Error)
err = c.Render(http.StatusOK, "hello", "Joe")
if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "Hello, Joe!", rec.Body.String())
}

c.echo.renderer = nil
if he := c.Render(http.StatusOK, "hello", "Joe"); he.Error == nil {
t.Error("render should error out")
}
err = c.Render(http.StatusOK, "hello", "Joe")
assert.Error(t, err)

// JSON
r.Header.Set(Accept, ApplicationJSON)
c.response.committed = false
if he := c.JSON(http.StatusOK, u1); he != nil {
t.Errorf("json %#v", he)
req.Header.Set(Accept, ApplicationJSON)
rec = httptest.NewRecorder()
c = NewContext(req, NewResponse(rec), New())
err = c.JSON(http.StatusOK, user{"1", "Joe"})
if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, ApplicationJSON, rec.Header().Get(ContentType))
assert.Equal(t, usr, strings.TrimSpace(rec.Body.String()))
}

// String
r.Header.Set(Accept, TextPlain)
c.response.committed = false
if he := c.String(http.StatusOK, "Hello, World!"); he != nil {
t.Errorf("string %#v", he.Error)
req.Header.Set(Accept, TextPlain)
rec = httptest.NewRecorder()
c = NewContext(req, NewResponse(rec), New())
err = c.String(http.StatusOK, "Hello, World!")
if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, TextPlain, rec.Header().Get(ContentType))
assert.Equal(t, "Hello, World!", rec.Body.String())
}

// HTML
r.Header.Set(Accept, TextHTML)
c.response.committed = false
if he := c.HTML(http.StatusOK, "Hello, <strong>World!</strong>"); he != nil {
t.Errorf("html %v", he.Error)
req.Header.Set(Accept, TextHTML)
rec = httptest.NewRecorder()
c = NewContext(req, NewResponse(rec), New())
err = c.HTML(http.StatusOK, "Hello, <strong>World!</strong>")
if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, TextHTML, rec.Header().Get(ContentType))
assert.Equal(t, "Hello, <strong>World!</strong>", rec.Body.String())
}

// NoContent
rec = httptest.NewRecorder()
c = NewContext(req, NewResponse(rec), New())
c.NoContent(http.StatusOK)
assert.Equal(t, http.StatusOK, c.response.status)

// Redirect
c.response.committed = false
rec = httptest.NewRecorder()
c = NewContext(req, NewResponse(rec), New())
c.Redirect(http.StatusMovedPermanently, "http://labstack.github.io/echo")

// Error
c.response.committed = false
rec = httptest.NewRecorder()
c = NewContext(req, NewResponse(rec), New())
c.Error(errors.New("error"))
assert.Equal(t, http.StatusInternalServerError, c.response.status)

// reset
c.reset(r, NewResponse(httptest.NewRecorder()), New())
c.reset(req, NewResponse(httptest.NewRecorder()), New())
}

func testBind(t *testing.T, c *Context, ct string) {
c.request.Header.Set(ContentType, ct)
u := new(user)
err := c.Bind(u)
if assert.NoError(t, err) {
assert.Equal(t, "1", u.ID)
assert.Equal(t, "Joe", u.Name)
}
}
2 changes: 0 additions & 2 deletions echo.go
Original file line number Diff line number Diff line change
Expand Up @@ -489,8 +489,6 @@ func wrapMiddleware(m Middleware) MiddlewareFunc {
}
case http.Handler:
return wrapHTTPHandlerFuncMW(m.ServeHTTP)
case http.HandlerFunc:
return wrapHTTPHandlerFuncMW(m)
case func(http.ResponseWriter, *http.Request):
return wrapHTTPHandlerFuncMW(m)
default:
Expand Down
Loading

0 comments on commit a9e49e2

Please sign in to comment.