浏览代码

More middleware unit test, starting to look really good

Torkel Ödegaard 10 年之前
父节点
当前提交
f416e2d1ac
共有 2 个文件被更改,包括 79 次插入15 次删除
  1. 78 14
      pkg/middleware/middleware_test.go
  2. 1 1
      pkg/setting/setting.go

+ 78 - 14
pkg/middleware/middleware_test.go

@@ -1,44 +1,68 @@
 package middleware
 
 import (
+	"encoding/json"
 	"net/http"
 	"net/http/httptest"
+	"path/filepath"
 	"testing"
 
 	"github.com/Unknwon/macaron"
+	"github.com/grafana/grafana/pkg/bus"
+	m "github.com/grafana/grafana/pkg/models"
+	"github.com/grafana/grafana/pkg/util"
 	"github.com/macaron-contrib/session"
 	. "github.com/smartystreets/goconvey/convey"
 )
 
 type scenarioContext struct {
-	m       *macaron.Macaron
-	context *Context
-	resp    *httptest.ResponseRecorder
+	m        *macaron.Macaron
+	context  *Context
+	resp     *httptest.ResponseRecorder
+	apiKey   string
+	respJson map[string]interface{}
 }
 
 func (sc *scenarioContext) PerformGet(url string) {
 	req, err := http.NewRequest("GET", "/", nil)
 	So(err, ShouldBeNil)
+	if sc.apiKey != "" {
+		req.Header.Add("Authorization", "Bearer "+sc.apiKey)
+	}
 	sc.m.ServeHTTP(sc.resp, req)
+
+	if sc.resp.Header().Get("Content-Type") == "application/json; charset=UTF-8" {
+		err := json.NewDecoder(sc.resp.Body).Decode(&sc.respJson)
+		So(err, ShouldBeNil)
+	}
 }
 
 type scenarioFunc func(c *scenarioContext)
+type reqModifier func(c *http.Request)
 
 func middlewareScenario(desc string, fn scenarioFunc) {
-	sc := &scenarioContext{}
+	Convey(desc, func() {
+		sc := &scenarioContext{}
+		viewsPath, _ := filepath.Abs("../../public/views")
 
-	sc.m = macaron.New()
-	sc.m.Use(GetContextHandler())
-	// mock out gc goroutine
-	startSessionGC = func() {}
-	sc.m.Use(Sessioner(&session.Options{}))
+		sc.m = macaron.New()
+		sc.m.Use(macaron.Renderer(macaron.RenderOptions{
+			Directory: viewsPath,
+			Delims:    macaron.Delims{Left: "[[", Right: "]]"},
+		}))
 
-	sc.m.Get("/", func(c *Context) {
-		sc.context = c
-	})
+		sc.m.Use(GetContextHandler())
+		// mock out gc goroutine
+		startSessionGC = func() {}
+		sc.m.Use(Sessioner(&session.Options{}))
 
-	sc.resp = httptest.NewRecorder()
-	fn(sc)
+		sc.m.Get("/", func(c *Context) {
+			sc.context = c
+		})
+
+		sc.resp = httptest.NewRecorder()
+		fn(sc)
+	})
 }
 
 func TestMiddlewareContext(t *testing.T) {
@@ -54,5 +78,45 @@ func TestMiddlewareContext(t *testing.T) {
 			So(sc.resp.Code, ShouldEqual, 200)
 		})
 
+		middlewareScenario("Non api request should init session", func(sc *scenarioContext) {
+			sc.PerformGet("/")
+			So(sc.resp.Header().Get("Set-Cookie"), ShouldContainSubstring, "grafana_sess")
+		})
+
+		middlewareScenario("Invalid api key", func(sc *scenarioContext) {
+			sc.apiKey = "invalid_key_test"
+			sc.PerformGet("/")
+
+			Convey("Should not init session", func() {
+				So(sc.resp.Header().Get("Set-Cookie"), ShouldBeEmpty)
+			})
+
+			Convey("Should return 401", func() {
+				So(sc.resp.Code, ShouldEqual, 401)
+				So(sc.respJson["message"], ShouldEqual, "Invalid API key")
+			})
+		})
+
+		middlewareScenario("Valid api key", func(sc *scenarioContext) {
+			sc.apiKey = "eyJrIjoidjVuQXdwTWFmRlA2em5hUzR1cmhkV0RMUzU1MTFNNDIiLCJuIjoiYXNkIiwiaWQiOjF9"
+			keyhash := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
+
+			bus.AddHandler("test", func(query *m.GetApiKeyByNameQuery) error {
+				query.Result = &m.ApiKey{OrgId: 12, Role: m.ROLE_EDITOR, Key: keyhash}
+				return nil
+			})
+
+			sc.PerformGet("/")
+
+			Convey("Should return 200", func() {
+				So(sc.resp.Code, ShouldEqual, 200)
+			})
+
+			Convey("Should init middleware context", func() {
+				So(sc.context.OrgId, ShouldEqual, 12)
+				So(sc.context.OrgRole, ShouldEqual, m.ROLE_EDITOR)
+			})
+		})
+
 	})
 }

+ 1 - 1
pkg/setting/setting.go

@@ -122,7 +122,7 @@ type CommandLineArgs struct {
 
 func init() {
 	IsWindows = runtime.GOOS == "windows"
-	//log.NewLogger(0, "console", `{"level": 0}`)
+	log.NewLogger(0, "console", `{"level": 0}`)
 }
 
 func parseAppUrlAndSubUrl(section *ini.Section) (string, string) {