Skip to content

Commit

Permalink
test: add unit tests for isError function
Browse files Browse the repository at this point in the history
  • Loading branch information
gonzolino committed Nov 11, 2021
1 parent be7261f commit 7e16cb1
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
4 changes: 4 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gotado

import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
Expand Down Expand Up @@ -29,6 +30,9 @@ func (e *apiError) Error() string {
}

func isError(resp *http.Response) error {
if resp == nil {
return errors.New("response is nil")
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return nil
}
Expand Down
58 changes: 58 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package gotado

import (
"fmt"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
)

func TestIsError(t *testing.T) {
tests := map[string]struct {
resp *http.Response
wantErr error
}{
"NoError": {
resp: makeResponse(200, ""),
wantErr: nil,
},
"NilError": {
resp: nil,
wantErr: fmt.Errorf("response is nil"),
},

"NoJsonError": {
resp: makeResponse(404, "not found"),
wantErr: fmt.Errorf("unable to decode API error: invalid character 'o' in literal null (expecting 'u')"),
},
"InvalidJsonError": {
resp: makeResponse(301, `{"foo": "bar"}`),
wantErr: fmt.Errorf("API returned empty error"),
},
"EmptyError": {
resp: makeResponse(500, `{"errors":[]}`),
wantErr: fmt.Errorf("API returned empty error"),
},
"SingleError": {
resp: makeResponse(500, `{"errors":[{"code":"1","title":"One"}]}`),
wantErr: fmt.Errorf("1: One"),
},
"MultiError": {
resp: makeResponse(500, `{"errors":[{"code":"1","title":"One"},{"code":"2","title":"Two"}]}`),
wantErr: fmt.Errorf("1: One, 2: Two"),
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
err := isError(tc.resp)

if tc.wantErr != nil {
assert.EqualError(t, err, tc.wantErr.Error())
} else {
assert.NoError(t, err)
}
})
}
}

0 comments on commit 7e16cb1

Please sign in to comment.