Do not treat server errors as API originated errors

This commit is contained in:
Andrey Beletsky 2021-02-16 19:40:18 +07:00
parent 39e5821760
commit ef1b43ac62
2 changed files with 22 additions and 8 deletions

View file

@ -119,6 +119,9 @@ func (c Client) doCall(url string, payload string) ([]byte, error) {
if err != nil {
return body, err
}
if r.StatusCode >= 500 {
return body, fmt.Errorf("server returned non-OK status: %v", r.StatusCode)
}
defer r.Body.Close()
return ioutil.ReadAll(r.Body)
}

View file

@ -9,23 +9,24 @@ import (
"github.com/stretchr/testify/assert"
)
func launchDummyServer(lastReq **http.Request, path, response string) *httptest.Server {
func launchDummyServer(lastReq **http.Request, path, response string, status int) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if lastReq != nil {
*lastReq = &*r
}
if r.URL.Path != path {
fmt.Printf("path doesn't match: %v != %v", r.URL.Path, path)
w.WriteHeader(http.StatusNotFound)
} else {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.WriteHeader(status)
w.Write([]byte(response))
}
}))
}
func TestUserMe(t *testing.T) {
var req *http.Request
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userMeMethod), userMeResponse)
ts := launchDummyServer(nil, makeMethodPath(userObjectPath, userMeMethod), userMeResponse, http.StatusOK)
defer ts.Close()
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL})
@ -35,8 +36,7 @@ func TestUserMe(t *testing.T) {
}
func TestUserHasVerifiedEmail(t *testing.T) {
var req *http.Request
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userHasVerifiedEmailMethod), userHasVerifiedEmailResponse)
ts := launchDummyServer(nil, makeMethodPath(userObjectPath, userHasVerifiedEmailMethod), userHasVerifiedEmailResponse, http.StatusOK)
defer ts.Close()
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL})
@ -48,7 +48,7 @@ func TestUserHasVerifiedEmail(t *testing.T) {
func TestRemoteIP(t *testing.T) {
var req *http.Request
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userMeMethod), userMeResponse)
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userMeMethod), userMeResponse, http.StatusOK)
defer ts.Close()
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL, RemoteIP: "8.8.8.8"})
@ -74,6 +74,17 @@ func TestHTTPError(t *testing.T) {
assert.EqualError(t, err, `Post "http://lolcathost/user/has_verified_email": dial tcp: lookup lolcathost: no such host`)
}
func TestGatewayError(t *testing.T) {
var req *http.Request
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userHasVerifiedEmailMethod), "", http.StatusBadGateway)
defer ts.Close()
c := NewClient("zcasdasc", &ClientOpts{ServerAddress: ts.URL})
r, err := c.UserHasVerifiedEmail()
assert.Nil(t, r)
assert.EqualError(t, err, `server returned non-OK status: 502`)
}
const userMeResponse = `{
"success": true,
"error": null,