From a0ae5c296d8baf3290ffc4973cf96e526cb1efaa Mon Sep 17 00:00:00 2001 From: Alexander Nyquist Date: Fri, 4 Jul 2014 10:12:28 +0200 Subject: [PATCH 01/12] Started writing unit tests --- gin_test.go | 290 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 290 insertions(+) create mode 100644 gin_test.go diff --git a/gin_test.go b/gin_test.go new file mode 100644 index 0000000..eb6ccce --- /dev/null +++ b/gin_test.go @@ -0,0 +1,290 @@ +package gin + +import( + "testing" + "html/template" + "net/http" + "net/http/httptest" +) + +// TestRouterGroupGETRouteOK tests that GET route is correctly invoked. +func TestRouterGroupGETRouteOK(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + passed := false + + r := Default() + r.GET("/test", func (c *Context) { + passed = true + }) + + r.ServeHTTP(w, req) + + if passed == false { + t.Errorf("GET route handler was not invoked.") + } + + if w.Code != http.StatusOK { + t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code) + } +} + +// TestRouterGroupPOSTRouteOK tests that POST route is correctly invoked. +func TestRouterGroupPOSTRouteOK(t *testing.T) { + req, _ := http.NewRequest("POST", "/test", nil) + w := httptest.NewRecorder() + passed := false + + r := Default() + r.POST("/test", func (c *Context) { + 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. +func TestRouterGroupDELETERouteOK(t *testing.T) { + req, _ := http.NewRequest("DELETE", "/test", nil) + w := httptest.NewRecorder() + passed := false + + r := Default() + r.DELETE("/test", func (c *Context) { + passed = true + }) + + r.ServeHTTP(w, req) + + if passed == false { + t.Errorf("DELETE route handler was not invoked.") + } + + 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 { + t.Errorf("Response code should be %v, was %d", http.StatusNotFound, w.Code) + } +} + +// TestContextParamsGet tests that a parameter can be parsed from the URL. +func TestContextParamsByName(t *testing.T) { + req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil) + w := httptest.NewRecorder() + name := "" + + r := Default() + r.GET("/test/:name", func (c *Context) { + name = c.Params.ByName("name") + }) + + r.ServeHTTP(w, req) + + if name != "alexandernyquist" { + t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name) + } +} + +// TestContextSetGet tests that a parameter is set correctly on the +// current context and can be retrieved using Get. +func TestContextSetGet(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test", func (c *Context) { + // Key should be lazily created + if c.Keys != nil { + t.Error("Keys should be nil") + } + + // Set + c.Set("foo", "bar") + + if v := c.Get("foo"); v != "bar" { + t.Errorf("Value should be bar, was %s", v) + } + }) + + r.ServeHTTP(w, req) +} + +// TestContextJSON tests that the response is serialized as JSON +// and Content-Type is set to application/json +func TestContextJSON(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test", func (c *Context) { + c.JSON(200, H{"foo": "bar"}) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "{\"foo\":\"bar\"}\n" { + t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "application/json" { + t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestContextHTML tests that the response executes the templates +// and responds with Content-Type set to text/html +func TestContextHTML(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := Default() + r.HTMLTemplates = template.Must(template.New("t").Parse(`Hello {{.Name}}`)) + + type TestData struct { Name string } + + r.GET("/test", func (c *Context) { + c.HTML(200, "t", TestData{"alexandernyquist"}) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "Hello alexandernyquist" { + t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "text/html" { + t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestContextString tests that the response is returned +// with Content-Type set to text/plain +func TestContextString(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test", func (c *Context) { + c.String(200, "test") + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "test" { + t.Errorf("Response should be test, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "text/plain" { + t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) + } +} \ No newline at end of file From 70593e8dfe8874034a07157eaab169c948b7dd6d Mon Sep 17 00:00:00 2001 From: Alexander Nyquist Date: Fri, 4 Jul 2014 11:01:11 +0200 Subject: [PATCH 02/12] Added test for requests to / when no route for / is defined --- gin_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/gin_test.go b/gin_test.go index eb6ccce..e66c5e3 100644 --- a/gin_test.go +++ b/gin_test.go @@ -29,6 +29,24 @@ func TestRouterGroupGETRouteOK(t *testing.T) { } } +// TestRouterGroupGETNoRootExistsRouteOK tests that a GET requse to root is correctly +// handled (404) when no root route exists. +func TestRouterGroupGETNoRootExistsRouteOK(t *testing.T) { + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test", func (c *Context) { + }) + + r.ServeHTTP(w, req) + + if w.Code != http.StatusNotFound { + // 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")) + } +} + // TestRouterGroupPOSTRouteOK tests that POST route is correctly invoked. func TestRouterGroupPOSTRouteOK(t *testing.T) { req, _ := http.NewRequest("POST", "/test", nil) From f944cff1a8787874e6165d9ec9cfe119d9db7441 Mon Sep 17 00:00:00 2001 From: msoedov Date: Sat, 5 Jul 2014 18:04:11 +0300 Subject: [PATCH 03/12] Added tests for ServeFiles #37 --- gin_test.go | 116 +++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 93 insertions(+), 23 deletions(-) diff --git a/gin_test.go b/gin_test.go index e66c5e3..c853b0f 100644 --- a/gin_test.go +++ b/gin_test.go @@ -1,10 +1,14 @@ package gin -import( - "testing" +import ( "html/template" + "io/ioutil" "net/http" "net/http/httptest" + "os" + "path" + "strings" + "testing" ) // TestRouterGroupGETRouteOK tests that GET route is correctly invoked. @@ -14,7 +18,7 @@ func TestRouterGroupGETRouteOK(t *testing.T) { passed := false r := Default() - r.GET("/test", func (c *Context) { + r.GET("/test", func(c *Context) { passed = true }) @@ -34,9 +38,9 @@ func TestRouterGroupGETRouteOK(t *testing.T) { func TestRouterGroupGETNoRootExistsRouteOK(t *testing.T) { req, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder() - + r := Default() - r.GET("/test", func (c *Context) { + r.GET("/test", func(c *Context) { }) r.ServeHTTP(w, req) @@ -54,7 +58,7 @@ func TestRouterGroupPOSTRouteOK(t *testing.T) { passed := false r := Default() - r.POST("/test", func (c *Context) { + r.POST("/test", func(c *Context) { passed = true }) @@ -76,7 +80,7 @@ func TestRouterGroupDELETERouteOK(t *testing.T) { passed := false r := Default() - r.DELETE("/test", func (c *Context) { + r.DELETE("/test", func(c *Context) { passed = true }) @@ -98,7 +102,7 @@ func TestRouterGroupPATCHRouteOK(t *testing.T) { passed := false r := Default() - r.PATCH("/test", func (c *Context) { + r.PATCH("/test", func(c *Context) { passed = true }) @@ -120,7 +124,7 @@ func TestRouterGroupPUTRouteOK(t *testing.T) { passed := false r := Default() - r.PUT("/test", func (c *Context) { + r.PUT("/test", func(c *Context) { passed = true }) @@ -135,7 +139,6 @@ func TestRouterGroupPUTRouteOK(t *testing.T) { } } - // TestRouterGroupOPTIONSRouteOK tests that OPTIONS route is correctly invoked. func TestRouterGroupOPTIONSRouteOK(t *testing.T) { req, _ := http.NewRequest("OPTIONS", "/test", nil) @@ -143,7 +146,7 @@ func TestRouterGroupOPTIONSRouteOK(t *testing.T) { passed := false r := Default() - r.OPTIONS("/test", func (c *Context) { + r.OPTIONS("/test", func(c *Context) { passed = true }) @@ -158,7 +161,6 @@ func TestRouterGroupOPTIONSRouteOK(t *testing.T) { } } - // TestRouterGroupHEADRouteOK tests that HEAD route is correctly invoked. func TestRouterGroupHEADRouteOK(t *testing.T) { req, _ := http.NewRequest("HEAD", "/test", nil) @@ -166,7 +168,7 @@ func TestRouterGroupHEADRouteOK(t *testing.T) { passed := false r := Default() - r.HEAD("/test", func (c *Context) { + r.HEAD("/test", func(c *Context) { passed = true }) @@ -181,15 +183,14 @@ func TestRouterGroupHEADRouteOK(t *testing.T) { } } - // 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 { t.Errorf("Response code should be %v, was %d", http.StatusNotFound, w.Code) } @@ -202,7 +203,7 @@ func TestContextParamsByName(t *testing.T) { name := "" r := Default() - r.GET("/test/:name", func (c *Context) { + r.GET("/test/:name", func(c *Context) { name = c.Params.ByName("name") }) @@ -220,7 +221,7 @@ func TestContextSetGet(t *testing.T) { w := httptest.NewRecorder() r := Default() - r.GET("/test", func (c *Context) { + r.GET("/test", func(c *Context) { // Key should be lazily created if c.Keys != nil { t.Error("Keys should be nil") @@ -244,7 +245,7 @@ func TestContextJSON(t *testing.T) { w := httptest.NewRecorder() r := Default() - r.GET("/test", func (c *Context) { + r.GET("/test", func(c *Context) { c.JSON(200, H{"foo": "bar"}) }) @@ -268,9 +269,9 @@ func TestContextHTML(t *testing.T) { r := Default() r.HTMLTemplates = template.Must(template.New("t").Parse(`Hello {{.Name}}`)) - type TestData struct { Name string } + type TestData struct{ Name string } - r.GET("/test", func (c *Context) { + r.GET("/test", func(c *Context) { c.HTML(200, "t", TestData{"alexandernyquist"}) }) @@ -292,7 +293,7 @@ func TestContextString(t *testing.T) { w := httptest.NewRecorder() r := Default() - r.GET("/test", func (c *Context) { + r.GET("/test", func(c *Context) { c.String(200, "test") }) @@ -305,4 +306,73 @@ func TestContextString(t *testing.T) { if w.HeaderMap.Get("Content-Type") != "text/plain" { t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) } -} \ No newline at end of file +} + +// TestHandleStaticFile - ensure the static file handles properly +func TestHandleStaticFile(t *testing.T) { + + testRoot, _ := os.Getwd() + + f, err := ioutil.TempFile(testRoot, "") + defer os.Remove(f.Name()) + + if err != nil { + t.Error(err) + } + + filePath := path.Join("/", path.Base(f.Name())) + req, _ := http.NewRequest("GET", filePath, nil) + + f.WriteString("Gin Web Framework") + f.Close() + + w := httptest.NewRecorder() + + r := Default() + r.ServeFiles("/*filepath", http.Dir("./")) + + r.ServeHTTP(w, req) + + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + + if w.Body.String() != "Gin Web Framework" { + t.Errorf("Response should be test, was: %s", w.Body.String()) + } + + 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")) + } +} + +// TestHandleStaticDir - ensure the root/sub dir handles properly +func TestHandleStaticDir(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + + w := httptest.NewRecorder() + + r := Default() + r.ServeFiles("/*filepath", http.Dir("./")) + + r.ServeHTTP(w, req) + + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + + bodyAsString := w.Body.String() + + if len(bodyAsString) == 0 { + t.Errorf("Got empty body instead of file tree") + } + + if !strings.Contains(bodyAsString, "gin.go") { + t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString) + } + + 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")) + } +} From 893387458242d5c76707d5e0d8ffdb8504d04839 Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Fri, 18 Jul 2014 17:42:38 +0300 Subject: [PATCH 04/12] Fixed tests up to master branch --- gin_test.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/gin_test.go b/gin_test.go index c853b0f..5bf737c 100644 --- a/gin_test.go +++ b/gin_test.go @@ -230,7 +230,11 @@ func TestContextSetGet(t *testing.T) { // Set c.Set("foo", "bar") - if v := c.Get("foo"); v != "bar" { + v, err := c.Get("foo") + if err != nil { + t.Errorf("Error on exist key") + } + if v != "bar" { t.Errorf("Value should be bar, was %s", v) } }) @@ -267,7 +271,8 @@ func TestContextHTML(t *testing.T) { w := httptest.NewRecorder() r := Default() - r.HTMLTemplates = template.Must(template.New("t").Parse(`Hello {{.Name}}`)) + templ, _ := template.New("t").Parse(`Hello {{.Name}}`) + r.SetHTMLTemplate(templ) type TestData struct{ Name string } From 89b4c6e0d1b65514c04f1a05a13b55a1d269bde5 Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Thu, 24 Jul 2014 16:51:11 +0300 Subject: [PATCH 05/12] Replaced deprecated ServeFiles --- gin_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gin_test.go b/gin_test.go index 5bf737c..730794e 100644 --- a/gin_test.go +++ b/gin_test.go @@ -334,7 +334,7 @@ func TestHandleStaticFile(t *testing.T) { w := httptest.NewRecorder() r := Default() - r.ServeFiles("/*filepath", http.Dir("./")) + r.Static("./", testRoot) r.ServeHTTP(w, req) @@ -359,7 +359,7 @@ func TestHandleStaticDir(t *testing.T) { w := httptest.NewRecorder() r := Default() - r.ServeFiles("/*filepath", http.Dir("./")) + r.Static("/", "./") r.ServeHTTP(w, req) From 74ca5f3bd9c4a076b76adb545638480f27e15779 Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Mon, 28 Jul 2014 13:05:23 +0300 Subject: [PATCH 06/12] Added dummy tests for middleware --- gin_test.go | 157 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) diff --git a/gin_test.go b/gin_test.go index 730794e..60fa148 100644 --- a/gin_test.go +++ b/gin_test.go @@ -1,6 +1,7 @@ package gin import ( + "errors" "html/template" "io/ioutil" "net/http" @@ -381,3 +382,159 @@ func TestHandleStaticDir(t *testing.T) { t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) } } + +// TestHandleHeadToDir - ensure the root/sub dir handles properly +func TestHandleHeadToDir(t *testing.T) { + + req, _ := http.NewRequest("HEAD", "/", nil) + + w := httptest.NewRecorder() + + r := Default() + r.Static("/", "./") + + r.ServeHTTP(w, req) + + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + + bodyAsString := w.Body.String() + + if len(bodyAsString) == 0 { + t.Errorf("Got empty body instead of file tree") + } + if !strings.Contains(bodyAsString, "gin.go") { + t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString) + } + + 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")) + } +} + +// TestHandlerFunc - ensure that custom middleware works properly +func TestHandlerFunc(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := Default() + var stepsPassed int = 0 + + r.Use(func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + }) + + r.ServeHTTP(w, req) + + if w.Code != 404 { + t.Errorf("Response code should be Not found, was: %s", w.Code) + } + + if stepsPassed != 2 { + t.Errorf("Falied to switch context in handler function: %s", stepsPassed) + } +} + +// TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers +func TestBadAbortHandlersChain(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := Default() + var stepsPassed int = 0 + + r.Use(func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + // after check and abort + context.Abort(409) + }, + func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + context.Abort(403) + }, + ) + + r.ServeHTTP(w, req) + + if w.Code != 403 { + t.Errorf("Response code should be Forbiden, was: %s", w.Code) + } + + if stepsPassed != 4 { + t.Errorf("Falied to switch context in handler function: %s", stepsPassed) + } +} + +// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order +func TestAbortHandlersChain(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := Default() + var stepsPassed int = 0 + + r.Use(func(context *Context) { + stepsPassed += 1 + context.Abort(409) + }, + func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + }, + ) + + r.ServeHTTP(w, req) + + if w.Code != 409 { + t.Errorf("Response code should be Conflict, was: %s", w.Code) + } + + if stepsPassed != 1 { + t.Errorf("Falied to switch context in handler function: %s", stepsPassed) + } +} + +// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as +// as well as Abort +func TestFailHandlersChain(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := Default() + var stepsPassed int = 0 + + r.Use(func(context *Context) { + stepsPassed += 1 + + context.Fail(500, errors.New("foo")) + }, + func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + }, + ) + + r.ServeHTTP(w, req) + + if w.Code != 500 { + t.Errorf("Response code should be Server error, was: %s", w.Code) + } + + if stepsPassed != 1 { + t.Errorf("Falied to switch context in handler function: %s", stepsPassed) + } + +} From 6abe841c1fc6306f7d9f1ee6aed527dd195deb9e Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Fri, 8 Aug 2014 14:48:15 +0300 Subject: [PATCH 07/12] Splited tests into separate files --- context_test.go | 252 ++++++++++++++++++++++++++++++++++++++++++++++++ gin_test.go | 245 ---------------------------------------------- 2 files changed, 252 insertions(+), 245 deletions(-) create mode 100644 context_test.go diff --git a/context_test.go b/context_test.go new file mode 100644 index 0000000..8480127 --- /dev/null +++ b/context_test.go @@ -0,0 +1,252 @@ +package gin + +import ( + "errors" + "html/template" + "net/http" + "net/http/httptest" + "testing" +) + +// TestContextParamsGet tests that a parameter can be parsed from the URL. +func TestContextParamsByName(t *testing.T) { + req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil) + w := httptest.NewRecorder() + name := "" + + r := Default() + r.GET("/test/:name", func(c *Context) { + name = c.Params.ByName("name") + }) + + r.ServeHTTP(w, req) + + if name != "alexandernyquist" { + t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name) + } +} + +// TestContextSetGet tests that a parameter is set correctly on the +// current context and can be retrieved using Get. +func TestContextSetGet(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test", func(c *Context) { + // Key should be lazily created + if c.Keys != nil { + t.Error("Keys should be nil") + } + + // Set + c.Set("foo", "bar") + + v, err := c.Get("foo") + if err != nil { + t.Errorf("Error on exist key") + } + if v != "bar" { + t.Errorf("Value should be bar, was %s", v) + } + }) + + r.ServeHTTP(w, req) +} + +// TestContextJSON tests that the response is serialized as JSON +// and Content-Type is set to application/json +func TestContextJSON(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test", func(c *Context) { + c.JSON(200, H{"foo": "bar"}) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "{\"foo\":\"bar\"}\n" { + t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "application/json" { + t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestContextHTML tests that the response executes the templates +// and responds with Content-Type set to text/html +func TestContextHTML(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := Default() + templ, _ := template.New("t").Parse(`Hello {{.Name}}`) + r.SetHTMLTemplate(templ) + + type TestData struct{ Name string } + + r.GET("/test", func(c *Context) { + c.HTML(200, "t", TestData{"alexandernyquist"}) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "Hello alexandernyquist" { + t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "text/html" { + t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestContextString tests that the response is returned +// with Content-Type set to text/plain +func TestContextString(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test", func(c *Context) { + c.String(200, "test") + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "test" { + t.Errorf("Response should be test, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "text/plain" { + t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestHandlerFunc - ensure that custom middleware works properly +func TestHandlerFunc(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := Default() + var stepsPassed int = 0 + + r.Use(func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + }) + + r.ServeHTTP(w, req) + + if w.Code != 404 { + t.Errorf("Response code should be Not found, was: %s", w.Code) + } + + if stepsPassed != 2 { + t.Errorf("Falied to switch context in handler function: %s", stepsPassed) + } +} + +// TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers +func TestBadAbortHandlersChain(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := Default() + var stepsPassed int = 0 + + r.Use(func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + // after check and abort + context.Abort(409) + }, + func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + context.Abort(403) + }, + ) + + r.ServeHTTP(w, req) + + if w.Code != 403 { + t.Errorf("Response code should be Forbiden, was: %s", w.Code) + } + + if stepsPassed != 4 { + t.Errorf("Falied to switch context in handler function: %s", stepsPassed) + } +} + +// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order +func TestAbortHandlersChain(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := Default() + var stepsPassed int = 0 + + r.Use(func(context *Context) { + stepsPassed += 1 + context.Abort(409) + }, + func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + }, + ) + + r.ServeHTTP(w, req) + + if w.Code != 409 { + t.Errorf("Response code should be Conflict, was: %s", w.Code) + } + + if stepsPassed != 1 { + t.Errorf("Falied to switch context in handler function: %s", stepsPassed) + } +} + +// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as +// as well as Abort +func TestFailHandlersChain(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := Default() + var stepsPassed int = 0 + + r.Use(func(context *Context) { + stepsPassed += 1 + + context.Fail(500, errors.New("foo")) + }, + func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + }, + ) + + r.ServeHTTP(w, req) + + if w.Code != 500 { + t.Errorf("Response code should be Server error, was: %s", w.Code) + } + + if stepsPassed != 1 { + t.Errorf("Falied to switch context in handler function: %s", stepsPassed) + } + +} diff --git a/gin_test.go b/gin_test.go index 60fa148..61b3c35 100644 --- a/gin_test.go +++ b/gin_test.go @@ -1,8 +1,6 @@ package gin import ( - "errors" - "html/template" "io/ioutil" "net/http" "net/http/httptest" @@ -197,123 +195,6 @@ func TestEngine404(t *testing.T) { } } -// TestContextParamsGet tests that a parameter can be parsed from the URL. -func TestContextParamsByName(t *testing.T) { - req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil) - w := httptest.NewRecorder() - name := "" - - r := Default() - r.GET("/test/:name", func(c *Context) { - name = c.Params.ByName("name") - }) - - r.ServeHTTP(w, req) - - if name != "alexandernyquist" { - t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name) - } -} - -// TestContextSetGet tests that a parameter is set correctly on the -// current context and can be retrieved using Get. -func TestContextSetGet(t *testing.T) { - req, _ := http.NewRequest("GET", "/test", nil) - w := httptest.NewRecorder() - - r := Default() - r.GET("/test", func(c *Context) { - // Key should be lazily created - if c.Keys != nil { - t.Error("Keys should be nil") - } - - // Set - c.Set("foo", "bar") - - v, err := c.Get("foo") - if err != nil { - t.Errorf("Error on exist key") - } - if v != "bar" { - t.Errorf("Value should be bar, was %s", v) - } - }) - - r.ServeHTTP(w, req) -} - -// TestContextJSON tests that the response is serialized as JSON -// and Content-Type is set to application/json -func TestContextJSON(t *testing.T) { - req, _ := http.NewRequest("GET", "/test", nil) - w := httptest.NewRecorder() - - r := Default() - r.GET("/test", func(c *Context) { - c.JSON(200, H{"foo": "bar"}) - }) - - r.ServeHTTP(w, req) - - if w.Body.String() != "{\"foo\":\"bar\"}\n" { - t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String()) - } - - if w.HeaderMap.Get("Content-Type") != "application/json" { - t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type")) - } -} - -// TestContextHTML tests that the response executes the templates -// and responds with Content-Type set to text/html -func TestContextHTML(t *testing.T) { - req, _ := http.NewRequest("GET", "/test", nil) - w := httptest.NewRecorder() - - r := Default() - templ, _ := template.New("t").Parse(`Hello {{.Name}}`) - r.SetHTMLTemplate(templ) - - type TestData struct{ Name string } - - r.GET("/test", func(c *Context) { - c.HTML(200, "t", TestData{"alexandernyquist"}) - }) - - r.ServeHTTP(w, req) - - if w.Body.String() != "Hello alexandernyquist" { - t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String()) - } - - if w.HeaderMap.Get("Content-Type") != "text/html" { - t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type")) - } -} - -// TestContextString tests that the response is returned -// with Content-Type set to text/plain -func TestContextString(t *testing.T) { - req, _ := http.NewRequest("GET", "/test", nil) - w := httptest.NewRecorder() - - r := Default() - r.GET("/test", func(c *Context) { - c.String(200, "test") - }) - - r.ServeHTTP(w, req) - - if w.Body.String() != "test" { - t.Errorf("Response should be test, was: %s", w.Body.String()) - } - - if w.HeaderMap.Get("Content-Type") != "text/plain" { - t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) - } -} - // TestHandleStaticFile - ensure the static file handles properly func TestHandleStaticFile(t *testing.T) { @@ -412,129 +293,3 @@ func TestHandleHeadToDir(t *testing.T) { t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) } } - -// TestHandlerFunc - ensure that custom middleware works properly -func TestHandlerFunc(t *testing.T) { - - req, _ := http.NewRequest("GET", "/", nil) - w := httptest.NewRecorder() - - r := Default() - var stepsPassed int = 0 - - r.Use(func(context *Context) { - stepsPassed += 1 - context.Next() - stepsPassed += 1 - }) - - r.ServeHTTP(w, req) - - if w.Code != 404 { - t.Errorf("Response code should be Not found, was: %s", w.Code) - } - - if stepsPassed != 2 { - t.Errorf("Falied to switch context in handler function: %s", stepsPassed) - } -} - -// TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers -func TestBadAbortHandlersChain(t *testing.T) { - - req, _ := http.NewRequest("GET", "/", nil) - w := httptest.NewRecorder() - - r := Default() - var stepsPassed int = 0 - - r.Use(func(context *Context) { - stepsPassed += 1 - context.Next() - stepsPassed += 1 - // after check and abort - context.Abort(409) - }, - func(context *Context) { - stepsPassed += 1 - context.Next() - stepsPassed += 1 - context.Abort(403) - }, - ) - - r.ServeHTTP(w, req) - - if w.Code != 403 { - t.Errorf("Response code should be Forbiden, was: %s", w.Code) - } - - if stepsPassed != 4 { - t.Errorf("Falied to switch context in handler function: %s", stepsPassed) - } -} - -// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order -func TestAbortHandlersChain(t *testing.T) { - - req, _ := http.NewRequest("GET", "/", nil) - w := httptest.NewRecorder() - - r := Default() - var stepsPassed int = 0 - - r.Use(func(context *Context) { - stepsPassed += 1 - context.Abort(409) - }, - func(context *Context) { - stepsPassed += 1 - context.Next() - stepsPassed += 1 - }, - ) - - r.ServeHTTP(w, req) - - if w.Code != 409 { - t.Errorf("Response code should be Conflict, was: %s", w.Code) - } - - if stepsPassed != 1 { - t.Errorf("Falied to switch context in handler function: %s", stepsPassed) - } -} - -// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as -// as well as Abort -func TestFailHandlersChain(t *testing.T) { - - req, _ := http.NewRequest("GET", "/", nil) - w := httptest.NewRecorder() - - r := Default() - var stepsPassed int = 0 - - r.Use(func(context *Context) { - stepsPassed += 1 - - context.Fail(500, errors.New("foo")) - }, - func(context *Context) { - stepsPassed += 1 - context.Next() - stepsPassed += 1 - }, - ) - - r.ServeHTTP(w, req) - - if w.Code != 500 { - t.Errorf("Response code should be Server error, was: %s", w.Code) - } - - if stepsPassed != 1 { - t.Errorf("Falied to switch context in handler function: %s", stepsPassed) - } - -} From fcd997e08362409aca1d83c6fbd54c33b8857b40 Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Fri, 8 Aug 2014 15:50:52 +0300 Subject: [PATCH 08/12] Added test for recovery --- recovery_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 recovery_test.go diff --git a/recovery_test.go b/recovery_test.go new file mode 100644 index 0000000..097700c --- /dev/null +++ b/recovery_test.go @@ -0,0 +1,44 @@ +package gin + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "os" + "testing" +) + +// TestPanicInHandler assert that panic has been recovered. +func TestPanicInHandler(t *testing.T) { + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + // Disable panic logs for testing + log.SetOutput(bytes.NewBuffer(nil)) + + r := Default() + r.GET("/", func(_ *Context) { + panic("Oupps, Houston, we have a problem") + }) + + r.ServeHTTP(w, req) + + // restore logging + log.SetOutput(os.Stderr) + + if w.Code != 500 { + t.Errorf("Response code should be Internal Server Error, was: %s", w.Code) + } + bodyAsString := w.Body.String() + + // fixme: + 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) + } + +} From 80cf66cde6e4831dfb3d2ebd75e1c6aa70f670d2 Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Fri, 8 Aug 2014 16:31:01 +0300 Subject: [PATCH 09/12] Added test cases for context file, data, XML response writers. --- context_test.go | 67 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/context_test.go b/context_test.go index 8480127..9662bf5 100644 --- a/context_test.go +++ b/context_test.go @@ -125,6 +125,73 @@ func TestContextString(t *testing.T) { } } +// TestContextXML tests that the response is serialized as XML +// and Content-Type is set to application/xml +func TestContextXML(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test", func(c *Context) { + c.XML(200, H{"foo": "bar"}) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "bar" { + t.Errorf("Response should be bar, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "application/xml" { + t.Errorf("Content-Type should be application/xml, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestContextData tests that the response can be written from `bytesting` +// with specified MIME type +func TestContextData(t *testing.T) { + req, _ := http.NewRequest("GET", "/test/csv", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test/csv", func(c *Context) { + c.Data(200, "text/csv", []byte(`foo,bar`)) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "foo,bar" { + t.Errorf("Response should be foo&bar, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "text/csv" { + t.Errorf("Content-Type should be text/csv, was %s", w.HeaderMap.Get("Content-Type")) + } +} + + +func TestContextFile(t *testing.T) { + req, _ := http.NewRequest("GET", "/test/file", nil) + w := httptest.NewRecorder() + + r := Default() + r.GET("/test/file", func(c *Context) { + c.File("./gin.go") + }) + + r.ServeHTTP(w, req) + + bodyAsString := w.Body.String() + + if len(bodyAsString) == 0 { + t.Errorf("Got empty body instead of file data") + } + + if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" { + t.Errorf("Content-Type should be text/plain; charset=utf-8, was %s", w.HeaderMap.Get("Content-Type")) + } +} + // TestHandlerFunc - ensure that custom middleware works properly func TestHandlerFunc(t *testing.T) { From 685d2c99cf473e152b9a6d3a02016f7f31997436 Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Mon, 11 Aug 2014 13:25:52 +0300 Subject: [PATCH 10/12] Added tests for JSON binding. --- context_test.go | 135 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 134 insertions(+), 1 deletion(-) diff --git a/context_test.go b/context_test.go index 9662bf5..9a2394a 100644 --- a/context_test.go +++ b/context_test.go @@ -1,6 +1,7 @@ package gin import ( + "bytes" "errors" "html/template" "net/http" @@ -169,7 +170,6 @@ func TestContextData(t *testing.T) { } } - func TestContextFile(t *testing.T) { req, _ := http.NewRequest("GET", "/test/file", nil) w := httptest.NewRecorder() @@ -317,3 +317,136 @@ func TestFailHandlersChain(t *testing.T) { } } + +func TestBindingJSON(t *testing.T) { + + body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}")) + + r := Default() + r.POST("/binding/json", func(c *Context) { + var body struct { + Foo string `json:"foo"` + } + if c.Bind(&body) { + c.JSON(200, H{"parsed": body.Foo}) + } + }) + + req, _ := http.NewRequest("POST", "/binding/json", body) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + r.ServeHTTP(w, req) + + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + + if w.Body.String() != "{\"parsed\":\"bar\"}\n" { + t.Errorf("Response should be {\"parsed\":\"bar\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "application/json" { + t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +func TestBindingJSONEncoding(t *testing.T) { + + body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}")) + + r := Default() + r.POST("/binding/json", func(c *Context) { + var body struct { + Foo string `json:"foo"` + } + if c.Bind(&body) { + c.JSON(200, H{"parsed": body.Foo}) + } + }) + + req, _ := http.NewRequest("POST", "/binding/json", body) + req.Header.Set("Content-Type", "application/json; charset=utf-8") + w := httptest.NewRecorder() + + r.ServeHTTP(w, req) + + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + + if w.Body.String() != "{\"parsed\":\"嘉\"}\n" { + t.Errorf("Response should be {\"parsed\":\"嘉\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "application/json" { + t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +func TestBindingJSONNoContentType(t *testing.T) { + + body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}")) + + r := Default() + r.POST("/binding/json", func(c *Context) { + var body struct { + Foo string `json:"foo"` + } + if c.Bind(&body) { + c.JSON(200, H{"parsed": body.Foo}) + } + + }) + + req, _ := http.NewRequest("POST", "/binding/json", body) + w := httptest.NewRecorder() + + r.ServeHTTP(w, req) + + if w.Code != 400 { + t.Errorf("Response code should be Bad request, was: %s", w.Code) + } + + if w.Body.String() == "{\"parsed\":\"bar\"}\n" { + t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") == "application/json" { + t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +func TestBindingJSONMalformed(t *testing.T) { + + body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n")) + + r := Default() + r.POST("/binding/json", func(c *Context) { + var body struct { + Foo string `json:"foo"` + } + if c.Bind(&body) { + c.JSON(200, H{"parsed": body.Foo}) + } + + }) + + req, _ := http.NewRequest("POST", "/binding/json", body) + req.Header.Set("Content-Type", "application/json") + + w := httptest.NewRecorder() + + r.ServeHTTP(w, req) + + if w.Code != 400 { + t.Errorf("Response code should be Bad request, was: %s", w.Code) + } + if w.Body.String() == "{\"parsed\":\"bar\"}\n" { + t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") == "application/json" { + t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} From f2176c3100d032cff4e093503ca0aba95954308c Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Mon, 11 Aug 2014 13:37:35 +0300 Subject: [PATCH 11/12] Adjusted tests for recovery. --- recovery_test.go | 42 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/recovery_test.go b/recovery_test.go index 097700c..7383a1d 100644 --- a/recovery_test.go +++ b/recovery_test.go @@ -11,14 +11,14 @@ import ( // TestPanicInHandler assert that panic has been recovered. func TestPanicInHandler(t *testing.T) { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest("GET", "/recovery", nil) w := httptest.NewRecorder() // Disable panic logs for testing log.SetOutput(bytes.NewBuffer(nil)) r := Default() - r.GET("/", func(_ *Context) { + r.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) @@ -32,7 +32,43 @@ func TestPanicInHandler(t *testing.T) { } bodyAsString := w.Body.String() - // fixme: + //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. +func TestPanicWithAbort(t *testing.T) { + req, _ := http.NewRequest("GET", "/recovery", nil) + w := httptest.NewRecorder() + + // Disable panic logs for testing + log.SetOutput(bytes.NewBuffer(nil)) + + r := Default() + r.GET("/recovery", func(c *Context) { + c.Abort(400) + panic("Oupps, Houston, we have a problem") + }) + + r.ServeHTTP(w, req) + + // restore logging + log.SetOutput(os.Stderr) + + // fixme: why not 500? + if w.Code != 400 { + 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) } From 4c57a35441e1bf01807b6bc3b8a0d78c22fa6de6 Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Tue, 12 Aug 2014 12:32:06 +0300 Subject: [PATCH 12/12] Added tests for basic auth. --- auth_test.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 auth_test.go diff --git a/auth_test.go b/auth_test.go new file mode 100644 index 0000000..d9b4f4d --- /dev/null +++ b/auth_test.go @@ -0,0 +1,57 @@ +package gin + +import ( + "encoding/base64" + "net/http" + "net/http/httptest" + "testing" +) + +func TestBasicAuthSucceed(t *testing.T) { + req, _ := http.NewRequest("GET", "/login", nil) + w := httptest.NewRecorder() + + r := Default() + accounts := Accounts{"admin": "password"} + r.Use(BasicAuth(accounts)) + + r.GET("/login", func(c *Context) { + c.String(200, "autorized") + }) + + req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) + r.ServeHTTP(w, req) + + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + bodyAsString := w.Body.String() + + if bodyAsString != "autorized" { + t.Errorf("Response body should be `autorized`, was %s", bodyAsString) + } +} + +func TestBasicAuth401(t *testing.T) { + req, _ := http.NewRequest("GET", "/login", nil) + w := httptest.NewRecorder() + + r := Default() + accounts := Accounts{"foo": "bar"} + r.Use(BasicAuth(accounts)) + + r.GET("/login", func(c *Context) { + c.String(200, "autorized") + }) + + req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) + r.ServeHTTP(w, req) + + if w.Code != 401 { + t.Errorf("Response code should be Not autorized, was: %s", w.Code) + } + + if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" { + t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type")) + } +}