forked from ziflex/lecho
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware_test.go
100 lines (79 loc) · 2.35 KB
/
middleware_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package lecho_test
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/content-services/lecho/v3"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
)
func TestMiddleware(t *testing.T) {
t.Run("should not trigger error handler when HandleError is false", func(t *testing.T) {
var called bool
e := echo.New()
e.HTTPErrorHandler = func(err error, c echo.Context) {
called = true
c.JSON(http.StatusInternalServerError, err.Error())
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
m := lecho.Middleware(lecho.Config{})
next := func(c echo.Context) error {
return errors.New("error")
}
handler := m(next)
err := handler(c)
assert.Error(t, err, "should return error")
assert.False(t, called, "should not call error handler")
})
t.Run("should trigger error handler when HandleError is true", func(t *testing.T) {
var called bool
e := echo.New()
e.HTTPErrorHandler = func(err error, c echo.Context) {
called = true
c.JSON(http.StatusInternalServerError, err.Error())
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
m := lecho.Middleware(lecho.Config{
HandleError: true,
})
next := func(c echo.Context) error {
return errors.New("error")
}
handler := m(next)
err := handler(c)
assert.Error(t, err, "should return error")
assert.Truef(t, called, "should call error handler")
})
t.Run("should use enricher", func(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
b := &bytes.Buffer{}
l := lecho.New(b)
m := lecho.Middleware(lecho.Config{
Logger: l,
Enricher: func(c echo.Context, logger zerolog.Context) zerolog.Context {
return logger.Str("test", "test")
},
})
next := func(c echo.Context) error {
return nil
}
handler := m(next)
err := handler(c)
assert.NoError(t, err, "should not return error")
str := b.String()
assert.Contains(t, str, `"test":"test"`)
})
}