🧪 Add integration test

This commit is contained in:
Dan Jones 2024-02-07 08:21:43 -06:00
commit 8e8a8079c5

47
int_test.go Normal file
View file

@ -0,0 +1,47 @@
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())
}