Skip to content

Commit

Permalink
Tons of unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
manucorporat committed Apr 9, 2015
1 parent ac1ee3f commit 0a192fb
Show file tree
Hide file tree
Showing 26 changed files with 1,477 additions and 86 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
Godeps/*
!Godeps/Godeps.json
coverage.out
count.out
4 changes: 4 additions & 0 deletions auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ func TestBasicAuthSearchCredential(t *testing.T) {
user, found = pairs.searchCredential(authorizationHeader("foo", "bar "))
assert.Empty(t, user)
assert.False(t, found)

user, found = pairs.searchCredential("")
assert.Empty(t, user)
assert.False(t, found)
}

func TestBasicAuthAuthorizationHeader(t *testing.T) {
Expand Down
7 changes: 7 additions & 0 deletions binding/binding.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,10 @@ func Default(method, contentType string) Binding {
}
}
}

func Validate(obj interface{}) error {
if err := _validator.ValidateStruct(obj); err != nil {
return error(err)
}
return nil
}
79 changes: 79 additions & 0 deletions binding/binding_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package binding

import (
"bytes"
"net/http"
"testing"

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

type FooStruct struct {
Foo string `json:"foo" form:"foo" xml:"foo" binding:"required"`
}

func TestBindingDefault(t *testing.T) {
assert.Equal(t, Default("GET", ""), GETForm)
assert.Equal(t, Default("GET", MIMEJSON), GETForm)

assert.Equal(t, Default("POST", MIMEJSON), JSON)
assert.Equal(t, Default("PUT", MIMEJSON), JSON)

assert.Equal(t, Default("POST", MIMEXML), XML)
assert.Equal(t, Default("PUT", MIMEXML2), XML)

assert.Equal(t, Default("POST", MIMEPOSTForm), POSTForm)
assert.Equal(t, Default("DELETE", MIMEPOSTForm), POSTForm)
}

func TestBindingJSON(t *testing.T) {
testBinding(t,
JSON, "json",
"/", "/",
`{"foo": "bar"}`, `{"bar": "foo"}`)
}

func TestBindingPOSTForm(t *testing.T) {
testBinding(t,
POSTForm, "post_form",
"/", "/",
"foo=bar", "bar=foo")
}

func TestBindingGETForm(t *testing.T) {
testBinding(t,
GETForm, "get_form",
"/?foo=bar", "/?bar=foo",
"", "")
}

func TestBindingXML(t *testing.T) {
testBinding(t,
XML, "xml",
"/", "/",
"<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")
}

func testBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
assert.Equal(t, b.Name(), name)

obj := FooStruct{}
req := requestWithBody(path, body)
err := b.Bind(req, &obj)
assert.NoError(t, err)
assert.Equal(t, obj.Foo, "bar")

obj = FooStruct{}
req = requestWithBody(badPath, badBody)
err = JSON.Bind(req, &obj)
assert.Error(t, err)
}

func requestWithBody(path, body string) (req *http.Request) {
req, _ = http.NewRequest("POST", path, bytes.NewBufferString(body))
return
}
5 changes: 1 addition & 4 deletions binding/get_form.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,5 @@ func (_ getFormBinding) Bind(req *http.Request, obj interface{}) error {
if err := mapForm(obj, req.Form); err != nil {
return err
}
if err := _validator.ValidateStruct(obj); err != nil {
return error(err)
}
return nil
return Validate(obj)
}
5 changes: 1 addition & 4 deletions binding/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,5 @@ func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {
if err := decoder.Decode(obj); err != nil {
return err
}
if err := _validator.ValidateStruct(obj); err != nil {
return error(err)
}
return nil
return Validate(obj)
}
5 changes: 1 addition & 4 deletions binding/post_form.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,5 @@ func (_ postFormBinding) Bind(req *http.Request, obj interface{}) error {
if err := mapForm(obj, req.PostForm); err != nil {
return err
}
if err := _validator.ValidateStruct(obj); err != nil {
return error(err)
}
return nil
return Validate(obj)
}
53 changes: 53 additions & 0 deletions binding/validate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package binding

import (
"testing"

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

type struct1 struct {
Value float64 `binding:"required"`
}

type struct2 struct {
RequiredValue string `binding:"required"`
Value float64
}

type struct3 struct {
Integer int
String string
BasicSlice []int
Boolean bool

RequiredInteger int `binding:"required"`
RequiredString string `binding:"required"`
RequiredAnotherStruct struct1 `binding:"required"`
RequiredBasicSlice []int `binding:"required"`
RequiredComplexSlice []struct2 `binding:"required"`
RequiredBoolean bool `binding:"required"`
}

func createStruct() struct3 {
return struct3{
RequiredInteger: 2,
RequiredString: "hello",
RequiredAnotherStruct: struct1{1.5},
RequiredBasicSlice: []int{1, 2, 3, 4},
RequiredComplexSlice: []struct2{
{RequiredValue: "A"},
{RequiredValue: "B"},
},
RequiredBoolean: true,
}
}

func TestValidateGoodObject(t *testing.T) {
test := createStruct()
assert.Nil(t, Validate(&test))
}
5 changes: 1 addition & 4 deletions binding/xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,5 @@ func (_ xmlBinding) Bind(req *http.Request, obj interface{}) error {
if err := decoder.Decode(obj); err != nil {
return err
}
if err := _validator.ValidateStruct(obj); err != nil {
return error(err)
}
return nil
return Validate(obj)
}
5 changes: 4 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ func (c *Context) reset() {

func (c *Context) Copy() *Context {
var cp Context = *c
cp.writermem.ResponseWriter = nil
cp.Writer = &cp.writermem
cp.Input.context = &cp
cp.index = AbortIndex
cp.handlers = nil
return &cp
Expand Down Expand Up @@ -161,7 +164,7 @@ func (c *Context) MustGet(key string) interface{} {
if value, exists := c.Get(key); exists {
return value
} else {
panic("Key " + key + " does not exist")
panic("Key \"" + key + "\" does not exist")
}
}

Expand Down
33 changes: 32 additions & 1 deletion context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import (
"github.com/stretchr/testify/assert"
)

// Unit tes TODO
// func (c *Context) File(filepath string) {
// func (c *Context) Negotiate(code int, config Negotiate) {
// BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) {

func createTestContext() (c *Context, w *httptest.ResponseRecorder, r *Engine) {
w = httptest.NewRecorder()
r = New()
Expand Down Expand Up @@ -64,6 +69,25 @@ func TestContextSetGet(t *testing.T) {
assert.Panics(t, func() { c.MustGet("no_exist") })
}

func TestContextCopy(t *testing.T) {
c, _, _ := createTestContext()
c.index = 2
c.Request, _ = http.NewRequest("POST", "/hola", nil)
c.handlers = []HandlerFunc{func(c *Context) {}}
c.Params = Params{Param{Key: "foo", Value: "bar"}}
c.Set("foo", "bar")

cp := c.Copy()
assert.Nil(t, cp.handlers)
assert.Equal(t, cp.Request, c.Request)
assert.Equal(t, cp.index, AbortIndex)
assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
assert.Equal(t, cp.Input.context, cp)
assert.Equal(t, cp.Keys, c.Keys)
assert.Equal(t, cp.Engine, c.Engine)
assert.Equal(t, cp.Params, c.Params)
}

// Tests that the response is serialized as JSON
// and Content-Type is set to application/json
func TestContextRenderJSON(t *testing.T) {
Expand All @@ -79,7 +103,7 @@ func TestContextRenderJSON(t *testing.T) {
// and responds with Content-Type set to text/html
func TestContextRenderHTML(t *testing.T) {
c, w, router := createTestContext()
templ, _ := template.New("t").Parse(`Hello {{.name}}`)
templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
router.SetHTMLTemplate(templ)

c.HTML(201, "t", H{"name": "alexandernyquist"})
Expand Down Expand Up @@ -160,6 +184,7 @@ func TestContextNegotiationFormat(t *testing.T) {
c, _, _ := createTestContext()
c.Request, _ = http.NewRequest("POST", "", nil)

assert.Panics(t, func() { c.NegotiateFormat() })
assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
}
Expand Down Expand Up @@ -203,13 +228,19 @@ func TestContextAbortWithStatus(t *testing.T) {

func TestContextError(t *testing.T) {
c, _, _ := createTestContext()
assert.Nil(t, c.LastError())
assert.Empty(t, c.Errors.String())

c.Error(errors.New("first error"), "some data")
assert.Equal(t, c.LastError().Error(), "first error")
assert.Len(t, c.Errors, 1)
assert.Equal(t, c.Errors.String(), "Error #01: first error\n Meta: some data\n")

c.Error(errors.New("second error"), "some data 2")
assert.Equal(t, c.LastError().Error(), "second error")
assert.Len(t, c.Errors, 2)
assert.Equal(t, c.Errors.String(), "Error #01: first error\n Meta: some data\n"+
"Error #02: second error\n Meta: some data 2\n")

assert.Equal(t, c.Errors[0].Err, "first error")
assert.Equal(t, c.Errors[0].Meta, "some data")
Expand Down
4 changes: 4 additions & 0 deletions debug_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import (
"github.com/stretchr/testify/assert"
)

// TODO
// func debugRoute(httpMethod, absolutePath string, handlers []HandlerFunc) {
// func debugPrint(format string, values ...interface{}) {

func TestIsDebugging(t *testing.T) {
SetMode(DebugMode)
assert.True(t, IsDebugging())
Expand Down
2 changes: 1 addition & 1 deletion errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (a errorMsgs) String() string {
}
var buffer bytes.Buffer
for i, msg := range a {
text := fmt.Sprintf("Error #%02d: %s \n Meta: %v\n", (i + 1), msg.Err, msg.Meta)
text := fmt.Sprintf("Error #%02d: %s\n Meta: %v\n", (i + 1), msg.Err, msg.Meta)
buffer.WriteString(text)
}
return buffer.String()
Expand Down
49 changes: 0 additions & 49 deletions examples/pluggable_renderer/example_pongo2.go

This file was deleted.

12 changes: 0 additions & 12 deletions examples/pluggable_renderer/index.html

This file was deleted.

7 changes: 7 additions & 0 deletions gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,13 @@ func (engine *Engine) handle(method, path string, handlers []HandlerFunc) {
if path[0] != '/' {
panic("path must begin with '/'")
}
if method == "" {
panic("HTTP method can not be empty")
}
if len(handlers) == 0 {
panic("there must be at least one handler")
}

root := engine.trees[method]
if root == nil {
root = new(node)
Expand Down
Loading

0 comments on commit 0a192fb

Please sign in to comment.