Skip to content

Commit

Permalink
add jsonapi errpayload test
Browse files Browse the repository at this point in the history
  • Loading branch information
jharley committed Jul 17, 2024
1 parent 6761e5e commit 22c2e50
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
1 change: 1 addition & 0 deletions client/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ func ErrorFromResponse(r *http.Response) error {
// TODO: field when we have it via pointer
}
}
detailedError.Details = details
}
return detailedError
default:
Expand Down
83 changes: 83 additions & 0 deletions client/errors_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package client_test

import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"

"github.com/hashicorp/jsonapi"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -191,3 +194,83 @@ func TestErrors_ErrorTypeDetail_String(t *testing.T) {
})
}
}

func TestErrors_JSONAPI(t *testing.T) {
t.Parallel()

testCases := []struct {
name string
code int
body jsonapi.ErrorsPayload
expectedOutput client.DetailedError
}{
{
name: "single error",
code: http.StatusConflict,
body: jsonapi.ErrorsPayload{
Errors: []*jsonapi.ErrorObject{
{
Status: "409",
Title: "Conflict",
Detail: "The resource already exists.",
Code: "/errors/conflict",
},
},
},
expectedOutput: client.DetailedError{
Status: 409,
Type: "/errors/conflict",
Message: "The resource already exists.",
Title: "Conflict",
},
},
{
name: "multi error",
code: http.StatusUnprocessableEntity,
body: jsonapi.ErrorsPayload{
Errors: []*jsonapi.ErrorObject{
{
Status: "422",
Code: "/errors/validation-failed",
Title: "The provided input is invalid.",
},
{
Status: "422",
Code: "/errors/validation-failed",
Title: "The provided input is invalid.",
},
},
},
expectedOutput: client.DetailedError{
Status: 422,
Title: "The provided input is invalid.",
Details: []client.ErrorTypeDetail{
{
Code: "/errors/validation-failed",
},
{
Code: "/errors/validation-failed",
},
},
},
},
}

for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
resp := &httptest.ResponseRecorder{
Code: testCase.code,
HeaderMap: http.Header{
"Content-Type": []string{jsonapi.MediaType},
},
}

buf := bytes.NewBuffer(nil)
jsonapi.MarshalErrors(buf, testCase.body.Errors)
resp.Body = bytes.NewBuffer(buf.Bytes())

actualOutput := client.ErrorFromResponse(resp.Result())
assert.Equal(t, testCase.expectedOutput, actualOutput)
})
}
}

0 comments on commit 22c2e50

Please sign in to comment.