1
0
mirror of https://github.com/labstack/echo.git synced 2024-11-24 08:22:21 +02:00
echo/middleware/logger_test.go
Vishal Rana 2aec0353f5 First commit to v3, #665
Signed-off-by: Vishal Rana <vr@labstack.com>
2016-09-22 22:56:00 -07:00

81 lines
1.7 KiB
Go

package middleware
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
func TestLogger(t *testing.T) {
// Note: Just for the test coverage, not a real test.
e := echo.New()
req, _ := http.NewRequest(echo.GET, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
h := Logger()(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
// Status 2xx
h(c)
// Status 3xx
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
h = Logger()(func(c echo.Context) error {
return c.String(http.StatusTemporaryRedirect, "test")
})
h(c)
// Status 4xx
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
h = Logger()(func(c echo.Context) error {
return c.String(http.StatusNotFound, "test")
})
h(c)
// Status 5xx with empty path
req, _ = http.NewRequest(echo.GET, "/", nil)
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
h = Logger()(func(c echo.Context) error {
return errors.New("error")
})
h(c)
}
func TestLoggerIPAddress(t *testing.T) {
e := echo.New()
req, _ := http.NewRequest(echo.GET, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
buf := new(bytes.Buffer)
e.Logger.SetOutput(buf)
ip := "127.0.0.1"
h := Logger()(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
// With X-Real-IP
req.Header.Add(echo.HeaderXRealIP, ip)
h(c)
assert.Contains(t, ip, buf.String())
// With X-Forwarded-For
buf.Reset()
req.Header.Del(echo.HeaderXRealIP)
req.Header.Add(echo.HeaderXForwardedFor, ip)
h(c)
assert.Contains(t, ip, buf.String())
buf.Reset()
h(c)
assert.Contains(t, ip, buf.String())
}