Improves unit tests

- Reusing much more code
- More coverage
- Cleanup
- Fixes some cases
This commit is contained in:
Manu Mtz-Almeida 2014-08-18 19:48:48 +02:00
parent e11ff5bacb
commit d85245b5aa
4 changed files with 168 additions and 306 deletions

View File

@ -11,7 +11,7 @@ func TestBasicAuthSucceed(t *testing.T) {
req, _ := http.NewRequest("GET", "/login", nil) req, _ := http.NewRequest("GET", "/login", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
accounts := Accounts{"admin": "password"} accounts := Accounts{"admin": "password"}
r.Use(BasicAuth(accounts)) r.Use(BasicAuth(accounts))
@ -36,7 +36,7 @@ func TestBasicAuth401(t *testing.T) {
req, _ := http.NewRequest("GET", "/login", nil) req, _ := http.NewRequest("GET", "/login", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
accounts := Accounts{"foo": "bar"} accounts := Accounts{"foo": "bar"}
r.Use(BasicAuth(accounts)) r.Use(BasicAuth(accounts))

View File

@ -15,7 +15,7 @@ func TestContextParamsByName(t *testing.T) {
w := httptest.NewRecorder() w := httptest.NewRecorder()
name := "" name := ""
r := Default() r := New()
r.GET("/test/:name", func(c *Context) { r.GET("/test/:name", func(c *Context) {
name = c.Params.ByName("name") name = c.Params.ByName("name")
}) })
@ -33,7 +33,7 @@ func TestContextSetGet(t *testing.T) {
req, _ := http.NewRequest("GET", "/test", nil) req, _ := http.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
r.GET("/test", func(c *Context) { r.GET("/test", func(c *Context) {
// Key should be lazily created // Key should be lazily created
if c.Keys != nil { if c.Keys != nil {
@ -61,7 +61,7 @@ func TestContextJSON(t *testing.T) {
req, _ := http.NewRequest("GET", "/test", nil) req, _ := http.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
r.GET("/test", func(c *Context) { r.GET("/test", func(c *Context) {
c.JSON(200, H{"foo": "bar"}) c.JSON(200, H{"foo": "bar"})
}) })
@ -83,7 +83,7 @@ func TestContextHTML(t *testing.T) {
req, _ := http.NewRequest("GET", "/test", nil) req, _ := http.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
templ, _ := template.New("t").Parse(`Hello {{.Name}}`) templ, _ := template.New("t").Parse(`Hello {{.Name}}`)
r.SetHTMLTemplate(templ) r.SetHTMLTemplate(templ)
@ -110,7 +110,7 @@ func TestContextString(t *testing.T) {
req, _ := http.NewRequest("GET", "/test", nil) req, _ := http.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
r.GET("/test", func(c *Context) { r.GET("/test", func(c *Context) {
c.String(200, "test") c.String(200, "test")
}) })
@ -132,7 +132,7 @@ func TestContextXML(t *testing.T) {
req, _ := http.NewRequest("GET", "/test", nil) req, _ := http.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
r.GET("/test", func(c *Context) { r.GET("/test", func(c *Context) {
c.XML(200, H{"foo": "bar"}) c.XML(200, H{"foo": "bar"})
}) })
@ -154,7 +154,7 @@ func TestContextData(t *testing.T) {
req, _ := http.NewRequest("GET", "/test/csv", nil) req, _ := http.NewRequest("GET", "/test/csv", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
r.GET("/test/csv", func(c *Context) { r.GET("/test/csv", func(c *Context) {
c.Data(200, "text/csv", []byte(`foo,bar`)) c.Data(200, "text/csv", []byte(`foo,bar`))
}) })
@ -174,7 +174,7 @@ func TestContextFile(t *testing.T) {
req, _ := http.NewRequest("GET", "/test/file", nil) req, _ := http.NewRequest("GET", "/test/file", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
r.GET("/test/file", func(c *Context) { r.GET("/test/file", func(c *Context) {
c.File("./gin.go") c.File("./gin.go")
}) })
@ -198,7 +198,7 @@ func TestHandlerFunc(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil) req, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := Default() r := New()
var stepsPassed int = 0 var stepsPassed int = 0
r.Use(func(context *Context) { r.Use(func(context *Context) {
@ -220,109 +220,95 @@ func TestHandlerFunc(t *testing.T) {
// TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers // TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers
func TestBadAbortHandlersChain(t *testing.T) { func TestBadAbortHandlersChain(t *testing.T) {
// SETUP
req, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
r := Default()
var stepsPassed int = 0 var stepsPassed int = 0
r := New()
r.Use(func(context *Context) { r.Use(func(c *Context) {
stepsPassed += 1 stepsPassed += 1
context.Next() c.Next()
stepsPassed += 1 stepsPassed += 1
// after check and abort // after check and abort
context.Abort(409) c.Abort(409)
}, })
func(context *Context) { r.Use(func(c *Context) {
stepsPassed += 1 stepsPassed += 1
context.Next() c.Next()
stepsPassed += 1 stepsPassed += 1
context.Abort(403) c.Abort(403)
}, })
)
r.ServeHTTP(w, req) // RUN
w := PerformRequest(r, "GET", "/")
if w.Code != 403 { // TEST
t.Errorf("Response code should be Forbiden, was: %s", w.Code) if w.Code != 409 {
t.Errorf("Response code should be Forbiden, was: %d", w.Code)
} }
if stepsPassed != 4 { if stepsPassed != 4 {
t.Errorf("Falied to switch context in handler function: %s", stepsPassed) t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
} }
} }
// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order // TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order
func TestAbortHandlersChain(t *testing.T) { func TestAbortHandlersChain(t *testing.T) {
// SETUP
req, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
r := Default()
var stepsPassed int = 0 var stepsPassed int = 0
r := New()
r.Use(func(context *Context) { r.Use(func(context *Context) {
stepsPassed += 1 stepsPassed += 1
context.Abort(409) context.Abort(409)
}, })
func(context *Context) { r.Use(func(context *Context) {
stepsPassed += 1 stepsPassed += 1
context.Next() context.Next()
stepsPassed += 1 stepsPassed += 1
}, })
)
r.ServeHTTP(w, req) // RUN
w := PerformRequest(r, "GET", "/")
// TEST
if w.Code != 409 { if w.Code != 409 {
t.Errorf("Response code should be Conflict, was: %s", w.Code) t.Errorf("Response code should be Conflict, was: %d", w.Code)
} }
if stepsPassed != 1 { if stepsPassed != 1 {
t.Errorf("Falied to switch context in handler function: %s", stepsPassed) t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
} }
} }
// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as // TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as
// as well as Abort // as well as Abort
func TestFailHandlersChain(t *testing.T) { func TestFailHandlersChain(t *testing.T) {
// SETUP
req, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
r := Default()
var stepsPassed int = 0 var stepsPassed int = 0
r := New()
r.Use(func(context *Context) { r.Use(func(context *Context) {
stepsPassed += 1 stepsPassed += 1
context.Fail(500, errors.New("foo")) context.Fail(500, errors.New("foo"))
}, })
func(context *Context) { r.Use(func(context *Context) {
stepsPassed += 1 stepsPassed += 1
context.Next() context.Next()
stepsPassed += 1 stepsPassed += 1
}, })
)
r.ServeHTTP(w, req) // RUN
w := PerformRequest(r, "GET", "/")
// TEST
if w.Code != 500 { if w.Code != 500 {
t.Errorf("Response code should be Server error, was: %s", w.Code) t.Errorf("Response code should be Server error, was: %d", w.Code)
} }
if stepsPassed != 1 { if stepsPassed != 1 {
t.Errorf("Falied to switch context in handler function: %s", stepsPassed) t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
} }
} }
func TestBindingJSON(t *testing.T) { func TestBindingJSON(t *testing.T) {
body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}")) body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))
r := Default() r := New()
r.POST("/binding/json", func(c *Context) { r.POST("/binding/json", func(c *Context) {
var body struct { var body struct {
Foo string `json:"foo"` Foo string `json:"foo"`
@ -355,7 +341,7 @@ func TestBindingJSONEncoding(t *testing.T) {
body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}")) body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}"))
r := Default() r := New()
r.POST("/binding/json", func(c *Context) { r.POST("/binding/json", func(c *Context) {
var body struct { var body struct {
Foo string `json:"foo"` Foo string `json:"foo"`
@ -388,7 +374,7 @@ func TestBindingJSONNoContentType(t *testing.T) {
body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}")) body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))
r := Default() r := New()
r.POST("/binding/json", func(c *Context) { r.POST("/binding/json", func(c *Context) {
var body struct { var body struct {
Foo string `json:"foo"` Foo string `json:"foo"`
@ -421,7 +407,7 @@ func TestBindingJSONMalformed(t *testing.T) {
body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n")) body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n"))
r := Default() r := New()
r.POST("/binding/json", func(c *Context) { r.POST("/binding/json", func(c *Context) {
var body struct { var body struct {
Foo string `json:"foo"` Foo string `json:"foo"`

View File

@ -10,224 +10,139 @@ import (
"testing" "testing"
) )
// TestRouterGroupGETRouteOK tests that GET route is correctly invoked. func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
func TestRouterGroupGETRouteOK(t *testing.T) { req, _ := http.NewRequest(method, path, nil)
req, _ := http.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
passed := false
r := Default()
r.GET("/test", func(c *Context) {
passed = true
})
r.ServeHTTP(w, req) r.ServeHTTP(w, req)
return w
}
// TestSingleRouteOK tests that POST route is correctly invoked.
func testRouteOK(method string, t *testing.T) {
// SETUP
passed := false
r := New()
r.Handle(method, "/test", []HandlerFunc{func(c *Context) {
passed = true
}})
// RUN
w := PerformRequest(r, method, "/test")
// TEST
if passed == false { if passed == false {
t.Errorf("GET route handler was not invoked.") t.Errorf(method + " route handler was not invoked.")
} }
if w.Code != http.StatusOK { if w.Code != http.StatusOK {
t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code) t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
} }
} }
func TestRouterGroupRouteOK(t *testing.T) {
testRouteOK("POST", t)
testRouteOK("DELETE", t)
testRouteOK("PATCH", t)
testRouteOK("PUT", t)
testRouteOK("OPTIONS", t)
testRouteOK("HEAD", t)
}
// TestRouterGroupGETNoRootExistsRouteOK tests that a GET requse to root is correctly // TestSingleRouteOK tests that POST route is correctly invoked.
// handled (404) when no root route exists. func testRouteNotOK(method string, t *testing.T) {
func TestRouterGroupGETNoRootExistsRouteOK(t *testing.T) { // SETUP
req, _ := http.NewRequest("GET", "/", nil) passed := false
w := httptest.NewRecorder() r := New()
r.Handle(method, "/test_2", []HandlerFunc{func(c *Context) {
passed = true
}})
r := Default() // RUN
r.GET("/test", func(c *Context) { w := PerformRequest(r, method, "/test")
})
r.ServeHTTP(w, req)
// TEST
if passed == true {
t.Errorf(method + " route handler was invoked, when it should not")
}
if w.Code != http.StatusNotFound { if w.Code != http.StatusNotFound {
// If this fails, it's because httprouter needs to be updated to at least f78f58a0db // If this fails, it's because httprouter needs to be updated to at least f78f58a0db
t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location")) t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))
} }
} }
// TestRouterGroupPOSTRouteOK tests that POST route is correctly invoked. // TestSingleRouteOK tests that POST route is correctly invoked.
func TestRouterGroupPOSTRouteOK(t *testing.T) { func TestRouteNotOK(t *testing.T) {
req, _ := http.NewRequest("POST", "/test", nil) testRouteNotOK("POST", t)
w := httptest.NewRecorder() testRouteNotOK("DELETE", t)
passed := false testRouteNotOK("PATCH", t)
testRouteNotOK("PUT", t)
r := Default() testRouteNotOK("OPTIONS", t)
r.POST("/test", func(c *Context) { testRouteNotOK("HEAD", t)
passed = true
})
r.ServeHTTP(w, req)
if passed == false {
t.Errorf("POST route handler was not invoked.")
}
if w.Code != http.StatusOK {
t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
}
} }
// TestRouterGroupDELETERouteOK tests that DELETE route is correctly invoked. // TestSingleRouteOK tests that POST route is correctly invoked.
func TestRouterGroupDELETERouteOK(t *testing.T) { func testRouteNotOK2(method string, t *testing.T) {
req, _ := http.NewRequest("DELETE", "/test", nil) // SETUP
w := httptest.NewRecorder()
passed := false passed := false
r := New()
r := Default() var methodRoute string
r.DELETE("/test", func(c *Context) { if method == "POST" {
methodRoute = "GET"
} else {
methodRoute = "POST"
}
r.Handle(methodRoute, "/test", []HandlerFunc{func(c *Context) {
passed = true passed = true
}) }})
r.ServeHTTP(w, req) // RUN
w := PerformRequest(r, method, "/test")
if passed == false { // TEST
t.Errorf("DELETE route handler was not invoked.") if passed == true {
t.Errorf(method + " route handler was invoked, when it should not")
} }
if w.Code != http.StatusOK {
t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
}
}
// TestRouterGroupPATCHRouteOK tests that PATCH route is correctly invoked.
func TestRouterGroupPATCHRouteOK(t *testing.T) {
req, _ := http.NewRequest("PATCH", "/test", nil)
w := httptest.NewRecorder()
passed := false
r := Default()
r.PATCH("/test", func(c *Context) {
passed = true
})
r.ServeHTTP(w, req)
if passed == false {
t.Errorf("PATCH route handler was not invoked.")
}
if w.Code != http.StatusOK {
t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
}
}
// TestRouterGroupPUTRouteOK tests that PUT route is correctly invoked.
func TestRouterGroupPUTRouteOK(t *testing.T) {
req, _ := http.NewRequest("PUT", "/test", nil)
w := httptest.NewRecorder()
passed := false
r := Default()
r.PUT("/test", func(c *Context) {
passed = true
})
r.ServeHTTP(w, req)
if passed == false {
t.Errorf("PUT route handler was not invoked.")
}
if w.Code != http.StatusOK {
t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
}
}
// TestRouterGroupOPTIONSRouteOK tests that OPTIONS route is correctly invoked.
func TestRouterGroupOPTIONSRouteOK(t *testing.T) {
req, _ := http.NewRequest("OPTIONS", "/test", nil)
w := httptest.NewRecorder()
passed := false
r := Default()
r.OPTIONS("/test", func(c *Context) {
passed = true
})
r.ServeHTTP(w, req)
if passed == false {
t.Errorf("OPTIONS route handler was not invoked.")
}
if w.Code != http.StatusOK {
t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
}
}
// TestRouterGroupHEADRouteOK tests that HEAD route is correctly invoked.
func TestRouterGroupHEADRouteOK(t *testing.T) {
req, _ := http.NewRequest("HEAD", "/test", nil)
w := httptest.NewRecorder()
passed := false
r := Default()
r.HEAD("/test", func(c *Context) {
passed = true
})
r.ServeHTTP(w, req)
if passed == false {
t.Errorf("HEAD route handler was not invoked.")
}
if w.Code != http.StatusOK {
t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
}
}
// TestRouterGroup404 tests that 404 is returned for a route that does not exist.
func TestEngine404(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
r := Default()
r.ServeHTTP(w, req)
if w.Code != http.StatusNotFound { if w.Code != http.StatusNotFound {
t.Errorf("Response code should be %v, was %d", http.StatusNotFound, w.Code) // If this fails, it's because httprouter needs to be updated to at least f78f58a0db
t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))
} }
} }
// TestSingleRouteOK tests that POST route is correctly invoked.
func TestRouteNotOK2(t *testing.T) {
testRouteNotOK2("POST", t)
testRouteNotOK2("DELETE", t)
testRouteNotOK2("PATCH", t)
testRouteNotOK2("PUT", t)
testRouteNotOK2("OPTIONS", t)
testRouteNotOK2("HEAD", t)
}
// TestHandleStaticFile - ensure the static file handles properly // TestHandleStaticFile - ensure the static file handles properly
func TestHandleStaticFile(t *testing.T) { func TestHandleStaticFile(t *testing.T) {
// SETUP file
testRoot, _ := os.Getwd() testRoot, _ := os.Getwd()
f, err := ioutil.TempFile(testRoot, "") f, err := ioutil.TempFile(testRoot, "")
defer os.Remove(f.Name())
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
defer os.Remove(f.Name())
filePath := path.Join("/", path.Base(f.Name())) filePath := path.Join("/", path.Base(f.Name()))
req, _ := http.NewRequest("GET", filePath, nil)
f.WriteString("Gin Web Framework") f.WriteString("Gin Web Framework")
f.Close() f.Close()
w := httptest.NewRecorder() // SETUP gin
r := New()
r := Default()
r.Static("./", testRoot) r.Static("./", testRoot)
r.ServeHTTP(w, req) // RUN
w := PerformRequest(r, "GET", filePath)
// TEST
if w.Code != 200 { if w.Code != 200 {
t.Errorf("Response code should be Ok, was: %s", w.Code) t.Errorf("Response code should be Ok, was: %s", w.Code)
} }
if w.Body.String() != "Gin Web Framework" { if w.Body.String() != "Gin Web Framework" {
t.Errorf("Response should be test, was: %s", w.Body.String()) t.Errorf("Response should be test, was: %s", w.Body.String())
} }
if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" { if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {
t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
} }
@ -235,30 +150,24 @@ func TestHandleStaticFile(t *testing.T) {
// TestHandleStaticDir - ensure the root/sub dir handles properly // TestHandleStaticDir - ensure the root/sub dir handles properly
func TestHandleStaticDir(t *testing.T) { func TestHandleStaticDir(t *testing.T) {
// SETUP
req, _ := http.NewRequest("GET", "/", nil) r := New()
w := httptest.NewRecorder()
r := Default()
r.Static("/", "./") r.Static("/", "./")
r.ServeHTTP(w, req) // RUN
w := PerformRequest(r, "GET", "/")
// TEST
bodyAsString := w.Body.String()
if w.Code != 200 { if w.Code != 200 {
t.Errorf("Response code should be Ok, was: %s", w.Code) t.Errorf("Response code should be Ok, was: %s", w.Code)
} }
bodyAsString := w.Body.String()
if len(bodyAsString) == 0 { if len(bodyAsString) == 0 {
t.Errorf("Got empty body instead of file tree") t.Errorf("Got empty body instead of file tree")
} }
if !strings.Contains(bodyAsString, "gin.go") { if !strings.Contains(bodyAsString, "gin.go") {
t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString) t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)
} }
if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" { if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {
t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
} }
@ -266,29 +175,24 @@ func TestHandleStaticDir(t *testing.T) {
// TestHandleHeadToDir - ensure the root/sub dir handles properly // TestHandleHeadToDir - ensure the root/sub dir handles properly
func TestHandleHeadToDir(t *testing.T) { func TestHandleHeadToDir(t *testing.T) {
// SETUP
req, _ := http.NewRequest("HEAD", "/", nil) r := New()
w := httptest.NewRecorder()
r := Default()
r.Static("/", "./") r.Static("/", "./")
r.ServeHTTP(w, req) // RUN
w := PerformRequest(r, "HEAD", "/")
// TEST
bodyAsString := w.Body.String()
if w.Code != 200 { if w.Code != 200 {
t.Errorf("Response code should be Ok, was: %s", w.Code) t.Errorf("Response code should be Ok, was: %s", w.Code)
} }
bodyAsString := w.Body.String()
if len(bodyAsString) == 0 { if len(bodyAsString) == 0 {
t.Errorf("Got empty body instead of file tree") t.Errorf("Got empty body instead of file tree")
} }
if !strings.Contains(bodyAsString, "gin.go") { if !strings.Contains(bodyAsString, "gin.go") {
t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString) t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)
} }
if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" { if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {
t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
} }

View File

@ -3,26 +3,22 @@ package gin
import ( import (
"bytes" "bytes"
"log" "log"
"net/http"
"net/http/httptest"
"os" "os"
"testing" "testing"
) )
// TestPanicInHandler assert that panic has been recovered. // TestPanicInHandler assert that panic has been recovered.
func TestPanicInHandler(t *testing.T) { func TestPanicInHandler(t *testing.T) {
req, _ := http.NewRequest("GET", "/recovery", nil) // SETUP
w := httptest.NewRecorder() log.SetOutput(bytes.NewBuffer(nil)) // Disable panic logs for testing
r := New()
// Disable panic logs for testing r.Use(Recovery())
log.SetOutput(bytes.NewBuffer(nil))
r := Default()
r.GET("/recovery", func(_ *Context) { r.GET("/recovery", func(_ *Context) {
panic("Oupps, Houston, we have a problem") panic("Oupps, Houston, we have a problem")
}) })
r.ServeHTTP(w, req) // RUN
w := PerformRequest(r, "GET", "/recovery")
// restore logging // restore logging
log.SetOutput(os.Stderr) log.SetOutput(os.Stderr)
@ -30,51 +26,27 @@ func TestPanicInHandler(t *testing.T) {
if w.Code != 500 { if w.Code != 500 {
t.Errorf("Response code should be Internal Server Error, was: %s", w.Code) t.Errorf("Response code should be Internal Server Error, was: %s", w.Code)
} }
bodyAsString := w.Body.String()
//fixme: no message provided?
if bodyAsString != "" {
t.Errorf("Response body should be empty, was %s", bodyAsString)
}
//fixme:
if len(w.HeaderMap) != 0 {
t.Errorf("No headers should be provided, was %s", w.HeaderMap)
}
} }
// TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
func TestPanicWithAbort(t *testing.T) { func TestPanicWithAbort(t *testing.T) {
req, _ := http.NewRequest("GET", "/recovery", nil) // SETUP
w := httptest.NewRecorder()
// Disable panic logs for testing
log.SetOutput(bytes.NewBuffer(nil)) log.SetOutput(bytes.NewBuffer(nil))
r := New()
r := Default() r.Use(Recovery())
r.GET("/recovery", func(c *Context) { r.GET("/recovery", func(c *Context) {
c.Abort(400) c.Abort(400)
panic("Oupps, Houston, we have a problem") panic("Oupps, Houston, we have a problem")
}) })
r.ServeHTTP(w, req) // RUN
w := PerformRequest(r, "GET", "/recovery")
// restore logging // restore logging
log.SetOutput(os.Stderr) log.SetOutput(os.Stderr)
// fixme: why not 500? // TEST
if w.Code != 400 { if w.Code != 500 {
t.Errorf("Response code should be Bad request, was: %s", w.Code) t.Errorf("Response code should be Bad request, was: %s", w.Code)
} }
bodyAsString := w.Body.String()
//fixme: no message provided?
if bodyAsString != "" {
t.Errorf("Response body should be empty, was %s", bodyAsString)
}
//fixme:
if len(w.HeaderMap) != 0 {
t.Errorf("No headers should be provided, was %s", w.HeaderMap)
}
} }