47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
errors "codeberg.org/danjones000/responsable-errors"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestErrorMiddleware(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
_, r := gin.CreateTestContext(w)
|
|
r.Use(ErrorMiddleware())
|
|
r.Use(HandlerWithErrorWrapper(func(c *gin.Context) error {
|
|
return errors.Errorf(400, "Oops")
|
|
}))
|
|
r.GET("/", func(c *gin.Context) {
|
|
c.JSON(200, gin.H{"Hello": "World"})
|
|
})
|
|
req, _ := http.NewRequest("GET", "/", nil)
|
|
r.ServeHTTP(w, req)
|
|
|
|
assert.Equal(t, 400, w.Code)
|
|
assert.Equal(t, `{"error":"Oops"}`, w.Body.String())
|
|
}
|
|
|
|
func TestErrorNoResponseIfAlreadyWritten(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
_, r := gin.CreateTestContext(w)
|
|
r.Use(ErrorMiddleware())
|
|
|
|
r.GET("/", HandlerWithErrorWrapper(func(c *gin.Context) error {
|
|
c.JSON(200, gin.H{"Hello": "World"})
|
|
return errors.Errorf(400, "Oops")
|
|
}))
|
|
req, _ := http.NewRequest("GET", "/", nil)
|
|
r.ServeHTTP(w, req)
|
|
|
|
assert.Equal(t, 200, w.Code)
|
|
assert.Equal(t, `{"Hello":"World"}`, w.Body.String())
|
|
|
|
}
|