recovery_test.go 2.2 KB

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