Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
meysamhadeli committed Oct 7, 2022
1 parent 239c10f commit 7fc05ee
Show file tree
Hide file tree
Showing 4 changed files with 165 additions and 2 deletions.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ require (
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.10.0 // indirect
github.com/goccy/go-json v0.9.7 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/labstack/gommon v0.3.1 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
Expand All @@ -26,6 +27,7 @@ require (
github.com/pelletier/go-toml/v2 v2.0.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
github.com/urfave/negroni v1.0.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.1 // indirect
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGF
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
Expand Down Expand Up @@ -60,6 +62,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M=
github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=
github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
github.com/urfave/negroni v1.0.0 h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc=
github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.1 h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52WA1u4=
Expand Down
9 changes: 7 additions & 2 deletions problem_details.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"net/http"
"net/http/httptest"
"reflect"
)

Expand Down Expand Up @@ -143,10 +144,14 @@ func ResolveProblemDetails(w http.ResponseWriter, r *http.Request, err error) er
statusCode = err.(*echo.HTTPError).Code
err = err.(*echo.HTTPError).Message.(error)
} else if errors.As(err, &ginError) {
var rw = w.(gin.ResponseWriter)
if rw.Written() {
var rw, ok = w.(gin.ResponseWriter)
if ok && rw.Written() {
statusCode = rw.Status()
}
if gin.Mode() == gin.TestMode {
var rw = w.(*httptest.ResponseRecorder)
statusCode = rw.Code
}
err = err.(*gin.Error).Err.(error)
}

Expand Down
152 changes: 152 additions & 0 deletions problem_details_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package problem

import (
"errors"
"github.com/gin-gonic/gin"
"github.com/labstack/echo/v4"
custom_errors "github.com/meysamhadeli/problem-details/samples/custom-errors"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)

func Test_BadRequest_Err(t *testing.T) {
badRequestErr := New(http.StatusBadRequest, "bad-request", "We have a bad request error")

assert.Equal(t, "We have a bad request error", badRequestErr.GetDetails())
assert.Equal(t, "bad-request", badRequestErr.GetTitle())
assert.Equal(t, "https://httpstatuses.io/400", badRequestErr.GetType())
assert.Equal(t, http.StatusBadRequest, badRequestErr.GetStatus())
}

func TestMap_CustomType_Echo(t *testing.T) {

e := echo.New()
req := httptest.NewRequest(http.MethodGet, "http://echo_endpoint1", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

err := echo_endpoint1(c)

var problemErr ProblemDetailErr

Map[custom_errors.BadRequestError](func() ProblemDetailErr {
problemErr = New(http.StatusBadRequest, "bad-request", err.Error())
return problemErr
})

_ = ResolveProblemDetails(c.Response(), c.Request(), err)

assert.Equal(t, c.Response().Status, http.StatusBadRequest)
assert.Equal(t, err.Error(), problemErr.GetDetails())
assert.Equal(t, "bad-request", problemErr.GetTitle())
assert.Equal(t, "https://httpstatuses.io/400", problemErr.GetType())
assert.Equal(t, http.StatusBadRequest, problemErr.GetStatus())
}

func TestMap_Status_Echo(t *testing.T) {

e := echo.New()
req := httptest.NewRequest(http.MethodGet, "http://echo_endpoint2", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

err := echo_endpoint2(c)

var problemErr ProblemDetailErr

// map status code to problem details error
MapStatus(http.StatusBadGateway, func() ProblemDetailErr {
problemErr = New(http.StatusUnauthorized, "unauthorized", err.Error())
return problemErr
})

_ = ResolveProblemDetails(c.Response(), c.Request(), err)

assert.Equal(t, c.Response().Status, http.StatusUnauthorized)
assert.Equal(t, err.(*echo.HTTPError).Message.(error).Error(), problemErr.GetDetails())
assert.Equal(t, "unauthorized", problemErr.GetTitle())
assert.Equal(t, "https://httpstatuses.io/401", problemErr.GetType())
assert.Equal(t, http.StatusUnauthorized, problemErr.GetStatus())
}

func TestMap_CustomType_Gin(t *testing.T) {

gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
r := gin.Default()

r.GET("/gin_endpoint1", func(ctx *gin.Context) {
err := errors.New("We have a custom type error in our endpoint")
customBadRequestError := custom_errors.BadRequestError{InternalError: err}
_ = c.Error(customBadRequestError)
})

req, _ := http.NewRequest(http.MethodGet, "/gin_endpoint1", nil)
r.ServeHTTP(w, req)

for _, err := range c.Errors {

var problemErr ProblemDetailErr

Map[custom_errors.BadRequestError](func() ProblemDetailErr {
problemErr = New(http.StatusBadRequest, "bad-request", err.Error())
return problemErr
})

_ = ResolveProblemDetails(w, req, err)

assert.Equal(t, http.StatusBadRequest, problemErr.GetStatus())
assert.Equal(t, err.Error(), problemErr.GetDetails())
assert.Equal(t, "bad-request", problemErr.GetTitle())
assert.Equal(t, "https://httpstatuses.io/400", problemErr.GetType())
}
}

func TestMap_Status_Gin(t *testing.T) {

gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
r := gin.Default()

r.GET("/gin_endpoint2", func(ctx *gin.Context) {
err := errors.New("We have a specific status code error in our endpoint")
// change status code 'StatusBadGateway' to 'StatusUnauthorized' base on handler config
_ = c.AbortWithError(http.StatusBadGateway, err)
})

req, _ := http.NewRequest(http.MethodGet, "/gin_endpoint2", nil)
r.ServeHTTP(w, req)

for _, err := range c.Errors {

var problemErr ProblemDetailErr

// map status code to problem details error
MapStatus(http.StatusBadGateway, func() ProblemDetailErr {
problemErr = New(http.StatusUnauthorized, "unauthorized", err.Error())
return problemErr
})

_ = ResolveProblemDetails(w, req, err)

assert.Equal(t, http.StatusUnauthorized, problemErr.GetStatus())
assert.Equal(t, err.Error(), problemErr.GetDetails())
assert.Equal(t, "unauthorized", problemErr.GetTitle())
assert.Equal(t, "https://httpstatuses.io/401", problemErr.GetType())
}
}

func echo_endpoint1(c echo.Context) error {
err := errors.New("We have a custom type error in our endpoint")
return custom_errors.BadRequestError{InternalError: err}
}

func echo_endpoint2(c echo.Context) error {
err := errors.New("We have a specific status code error in our endpoint")
// change status code 'StatusBadGateway' to 'StatusUnauthorized' base on handler config
return echo.NewHTTPError(http.StatusBadGateway, err)
}

0 comments on commit 7fc05ee

Please sign in to comment.