recovery_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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/setting"
  8. . "github.com/smartystreets/goconvey/convey"
  9. macaron "gopkg.in/macaron.v1"
  10. )
  11. func TestRecoveryMiddleware(t *testing.T) {
  12. setting.ERR_TEMPLATE_NAME = "error-template"
  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.userAuthTokenService = newFakeUserAuthTokenService()
  52. sc.m.Use(GetContextHandler(sc.userAuthTokenService))
  53. // mock out gc goroutine
  54. sc.m.Use(OrgRedirect())
  55. sc.m.Use(AddDefaultResponseHeaders())
  56. sc.defaultHandler = func(c *m.ReqContext) {
  57. sc.context = c
  58. if sc.handlerFunc != nil {
  59. sc.handlerFunc(sc.context)
  60. }
  61. }
  62. sc.m.Get(url, sc.defaultHandler)
  63. fn(sc)
  64. })
  65. }