recovery_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package middleware
  2. import (
  3. "path/filepath"
  4. "testing"
  5. ms "github.com/go-macaron/session"
  6. "github.com/grafana/grafana/pkg/bus"
  7. m "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/services/session"
  9. . "github.com/smartystreets/goconvey/convey"
  10. "gopkg.in/macaron.v1"
  11. )
  12. func TestRecoveryMiddleware(t *testing.T) {
  13. Convey("Given an api route that panics", t, func() {
  14. apiUrl := "/api/whatever"
  15. recoveryScenario("recovery middleware should return json", apiUrl, func(sc *scenarioContext) {
  16. sc.handlerFunc = PanicHandler
  17. sc.fakeReq("GET", apiUrl).exec()
  18. sc.req.Header.Add("content-type", "application/json")
  19. So(sc.resp.Code, ShouldEqual, 500)
  20. So(sc.respJson["message"], ShouldStartWith, "Internal Server Error - Check the Grafana server logs for the detailed error message.")
  21. So(sc.respJson["error"], ShouldStartWith, "Server Error")
  22. })
  23. })
  24. Convey("Given a non-api route that panics", t, func() {
  25. apiUrl := "/whatever"
  26. recoveryScenario("recovery middleware should return html", apiUrl, func(sc *scenarioContext) {
  27. sc.handlerFunc = PanicHandler
  28. sc.fakeReq("GET", apiUrl).exec()
  29. So(sc.resp.Code, ShouldEqual, 500)
  30. So(sc.resp.Header().Get("content-type"), ShouldEqual, "text/html; charset=UTF-8")
  31. So(sc.resp.Body.String(), ShouldContainSubstring, "<title>Grafana - Error</title>")
  32. })
  33. })
  34. }
  35. func PanicHandler(c *m.ReqContext) {
  36. panic("Handler has panicked")
  37. }
  38. func recoveryScenario(desc string, url string, fn scenarioFunc) {
  39. Convey(desc, func() {
  40. defer bus.ClearBusHandlers()
  41. sc := &scenarioContext{
  42. url: url,
  43. }
  44. viewsPath, _ := filepath.Abs("../../public/views")
  45. sc.m = macaron.New()
  46. sc.m.Use(Recovery())
  47. sc.m.Use(macaron.Renderer(macaron.RenderOptions{
  48. Directory: viewsPath,
  49. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  50. }))
  51. sc.m.Use(GetContextHandler())
  52. // mock out gc goroutine
  53. session.StartSessionGC = func() {}
  54. sc.m.Use(Sessioner(&ms.Options{}, 0))
  55. sc.m.Use(OrgRedirect())
  56. sc.m.Use(AddDefaultResponseHeaders())
  57. sc.defaultHandler = func(c *m.ReqContext) {
  58. sc.context = c
  59. if sc.handlerFunc != nil {
  60. sc.handlerFunc(sc.context)
  61. }
  62. }
  63. sc.m.Get(url, sc.defaultHandler)
  64. fn(sc)
  65. })
  66. }