Middleware: Rewrite tests to use standard library (#29535)

* middleware: Rewrite tests to use standard library

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
This commit is contained in:
Arve Knudsen
2020-12-03 08:28:54 +01:00
committed by GitHub
parent 0b6434d0e8
commit 58dbf96a12
10 changed files with 1008 additions and 898 deletions

View File

@ -2,6 +2,7 @@ package middleware
import (
"path/filepath"
"strings"
"testing"
"github.com/grafana/grafana/pkg/bus"
@ -9,52 +10,55 @@ import (
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
macaron "gopkg.in/macaron.v1"
)
func TestRecoveryMiddleware(t *testing.T) {
setting.ErrTemplateName = "error-template"
Convey("Given an api route that panics", t, func() {
t.Run("Given an API route that panics", func(t *testing.T) {
apiURL := "/api/whatever"
recoveryScenario(t, "recovery middleware should return json", apiURL, func(sc *scenarioContext) {
sc.handlerFunc = PanicHandler
sc.handlerFunc = panicHandler
sc.fakeReq("GET", apiURL).exec()
sc.req.Header.Add("content-type", "application/json")
So(sc.resp.Code, ShouldEqual, 500)
So(sc.respJson["message"], ShouldStartWith, "Internal Server Error - Check the Grafana server logs for the detailed error message.")
So(sc.respJson["error"], ShouldStartWith, "Server Error")
assert.Equal(t, 500, sc.resp.Code)
assert.Equal(t, "Internal Server Error - Check the Grafana server logs for the detailed error message.", sc.respJson["message"])
assert.True(t, strings.HasPrefix(sc.respJson["error"].(string), "Server Error"))
})
})
Convey("Given a non-api route that panics", t, func() {
t.Run("Given a non-API route that panics", func(t *testing.T) {
apiURL := "/whatever"
recoveryScenario(t, "recovery middleware should return html", apiURL, func(sc *scenarioContext) {
sc.handlerFunc = PanicHandler
sc.handlerFunc = panicHandler
sc.fakeReq("GET", apiURL).exec()
So(sc.resp.Code, ShouldEqual, 500)
So(sc.resp.Header().Get("content-type"), ShouldEqual, "text/html; charset=UTF-8")
So(sc.resp.Body.String(), ShouldContainSubstring, "<title>Grafana - Error</title>")
assert.Equal(t, 500, sc.resp.Code)
assert.Equal(t, "text/html; charset=UTF-8", sc.resp.Header().Get("content-type"))
assert.True(t, strings.Contains(sc.resp.Body.String(), "<title>Grafana - Error</title>"))
})
})
}
func PanicHandler(c *models.ReqContext) {
func panicHandler(c *models.ReqContext) {
panic("Handler has panicked")
}
func recoveryScenario(t *testing.T, desc string, url string, fn scenarioFunc) {
Convey(desc, func() {
t.Run(desc, func(t *testing.T) {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
t: t,
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
viewsPath, err := filepath.Abs("../../public/views")
require.NoError(t, err)
sc.m = macaron.New()
sc.m.Use(Recovery())