From 4c57a35441e1bf01807b6bc3b8a0d78c22fa6de6 Mon Sep 17 00:00:00 2001 From: Sasha Myasoedov Date: Tue, 12 Aug 2014 12:32:06 +0300 Subject: [PATCH] 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 00000000..d9b4f4d4 --- /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")) + } +}