hmn/src/website/routes_test.go

59 lines
1.3 KiB
Go
Raw Normal View History

2021-05-05 18:44:19 +00:00
package website
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
2021-05-06 04:04:58 +00:00
"regexp"
2021-05-05 18:44:19 +00:00
"testing"
"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
)
func TestLogContextErrors(t *testing.T) {
err1 := errors.New("test error 1")
err2 := errors.New("test error 2")
2022-05-07 14:43:41 +00:00
defer zerolog.SetGlobalLevel(zerolog.GlobalLevel())
zerolog.SetGlobalLevel(zerolog.TraceLevel)
2021-05-05 18:44:19 +00:00
var buf bytes.Buffer
logger := zerolog.New(&buf)
logger.Print("sanity check")
assert.Contains(t, buf.String(), "sanity check")
router := &Router{}
routes := RouteBuilder{
Router: router,
Middleware: func(h Handler) Handler {
return func(c *RequestContext) (res ResponseData) {
c.Logger = &logger
defer logContextErrorsMiddleware(c, &res)
2021-05-05 18:44:19 +00:00
return h(c)
}
},
}
2021-05-06 04:04:58 +00:00
routes.GET(regexp.MustCompile("^/test$"), func(c *RequestContext) ResponseData {
2021-08-28 12:21:03 +00:00
return c.ErrorResponse(http.StatusInternalServerError, err1, err2)
2021-05-05 18:44:19 +00:00
})
srv := httptest.NewServer(router)
defer srv.Close()
res, err := http.Get(srv.URL + "/test")
if assert.Nil(t, err) {
defer res.Body.Close()
t.Logf("Log contents: %s", buf.String())
assert.Equal(t, http.StatusInternalServerError, res.StatusCode)
assert.Contains(t, buf.String(), err1.Error())
assert.Contains(t, buf.String(), err2.Error())
}
}