Kaynağa Gözat

NewError tests

Signed-off-by: Niko Kovacevic <nikovacevic@gmail.com>
Niko Kovacevic 8 ay önce
ebeveyn
işleme
ec6ec2925d
2 değiştirilmiş dosya ile 26 ekleme ve 4 silme
  1. 5 4
      core/pkg/protocol/http.go
  2. 21 0
      core/pkg/protocol/http_test.go

+ 5 - 4
core/pkg/protocol/http.go

@@ -271,9 +271,10 @@ func (hp HTTPProtocol) WriteResponse(w http.ResponseWriter, r *HTTPResponse) {
 	}
 }
 
-func (hp HTTPProtocol) NewError(statusCode int, err error) *HTTPError {
-	if statusCode == 0 {
-		statusCode = http.StatusInternalServerError
+func (hp HTTPProtocol) NewError(err error, statusCode ...int) *HTTPError {
+	code := http.StatusInternalServerError
+	if len(statusCode) > 0 {
+		code = statusCode[0]
 	}
 
 	var body string
@@ -284,7 +285,7 @@ func (hp HTTPProtocol) NewError(statusCode int, err error) *HTTPError {
 	}
 
 	return &HTTPError{
-		StatusCode: statusCode,
+		StatusCode: code,
 		Body:       body,
 	}
 }

+ 21 - 0
core/pkg/protocol/http_test.go

@@ -272,3 +272,24 @@ func TestHTTPProtocol_HTTPResponse(t *testing.T) {
 		t.Error("expected message, received empty string")
 	}
 }
+
+func TestHTTPProtocol_NewError(t *testing.T) {
+	proto := HTTP()
+
+	err := errors.New("error")
+
+	httpErr := proto.NewError(err)
+	if httpErr == nil || httpErr.StatusCode != 500 || httpErr.Body != "error" {
+		t.Errorf("expected 500 error, received %d %s", httpErr.StatusCode, httpErr.Body)
+	}
+
+	httpErr = proto.NewError(err, 400)
+	if httpErr == nil || httpErr.StatusCode != 400 || httpErr.Body != "error" {
+		t.Errorf("expected 400 error, received %d %s", httpErr.StatusCode, httpErr.Body)
+	}
+
+	httpErr = proto.NewError(err, 400, 404)
+	if httpErr == nil || httpErr.StatusCode != 400 || httpErr.Body != "error" {
+		t.Errorf("expected 400 error, received %d %s", httpErr.StatusCode, httpErr.Body)
+	}
+}