recovery_test.go 2.1 KB

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