diff --git a/autorest/client.go b/autorest/client.go index cfc7ed757..92da6adb2 100644 --- a/autorest/client.go +++ b/autorest/client.go @@ -73,6 +73,22 @@ type Response struct { *http.Response `json:"-"` } +// IsHTTPStatus returns true if the returned HTTP status code matches the provided status code. +// If there was no response (i.e. the underlying http.Response is nil) the return value is false. +func (r Response) IsHTTPStatus(statusCode int) bool { + if r.Response == nil { + return false + } + return r.Response.StatusCode == statusCode +} + +// HasHTTPStatus returns true if the returned HTTP status code matches one of the provided status codes. +// If there was no response (i.e. the underlying http.Response is nil) or not status codes are provided +// the return value is false. +func (r Response) HasHTTPStatus(statusCodes ...int) bool { + return ResponseHasStatusCode(r.Response, statusCodes...) +} + // LoggingInspector implements request and response inspectors that log the full request and // response to a supplied log. type LoggingInspector struct { diff --git a/autorest/client_test.go b/autorest/client_test.go index 9ae7ed608..ca896714d 100644 --- a/autorest/client_test.go +++ b/autorest/client_test.go @@ -435,6 +435,37 @@ func TestCookies(t *testing.T) { } } +func TestResponseIsHTTPStatus(t *testing.T) { + r := Response{} + if r.IsHTTPStatus(http.StatusBadRequest) { + t.Fatal("autorest: expected false for nil response") + } + r.Response = &http.Response{StatusCode: http.StatusOK} + if r.IsHTTPStatus(http.StatusBadRequest) { + t.Fatal("autorest: expected false") + } + if !r.IsHTTPStatus(http.StatusOK) { + t.Fatal("autorest: expected true") + } +} + +func TestResponseHasHTTPStatus(t *testing.T) { + r := Response{} + if r.HasHTTPStatus(http.StatusBadRequest, http.StatusInternalServerError) { + t.Fatal("autorest: expected false for nil response") + } + r.Response = &http.Response{StatusCode: http.StatusAccepted} + if r.HasHTTPStatus(http.StatusBadRequest, http.StatusInternalServerError) { + t.Fatal("autorest: expected false") + } + if !r.HasHTTPStatus(http.StatusOK, http.StatusCreated, http.StatusAccepted) { + t.Fatal("autorest: expected true") + } + if r.HasHTTPStatus() { + t.Fatal("autorest: expected false for no status codes") + } +} + func randomString(n int) string { const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))