Skip to content

Commit

Permalink
Add test for marshalling of error details
Browse files Browse the repository at this point in the history
  • Loading branch information
johanbrandhorst committed Apr 24, 2018
1 parent 2045c5d commit da583f8
Showing 1 changed file with 32 additions and 5 deletions.
37 changes: 32 additions & 5 deletions runtime/errors_test.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
package runtime_test

import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"

"context"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

func TestDefaultHTTPError(t *testing.T) {
ctx := context.Background()

statusWithDetails, _ := status.New(codes.FailedPrecondition, "failed precondition").WithDetails(
&errdetails.PreconditionFailure{},
)

for _, spec := range []struct {
err error
status int
msg string
err error
status int
msg string
details string
}{
{
err: fmt.Errorf("example error"),
Expand All @@ -32,10 +38,16 @@ func TestDefaultHTTPError(t *testing.T) {
status: http.StatusNotFound,
msg: "no such resource",
},
{
err: statusWithDetails.Err(),
status: http.StatusPreconditionFailed,
msg: "failed precondition",
details: "type.googleapis.com/google.rpc.PreconditionFailure",
},
} {
w := httptest.NewRecorder()
req, _ := http.NewRequest("", "", nil) // Pass in an empty request to match the signature
runtime.DefaultHTTPError(ctx, &runtime.ServeMux{}, &runtime.JSONBuiltin{}, w, req, spec.err)
runtime.DefaultHTTPError(ctx, &runtime.ServeMux{}, &runtime.JSONPb{}, w, req, spec.err)

if got, want := w.Header().Get("Content-Type"), "application/json"; got != want {
t.Errorf(`w.Header().Get("Content-Type") = %q; want %q; on spec.err=%v`, got, want, spec.err)
Expand All @@ -53,5 +65,20 @@ func TestDefaultHTTPError(t *testing.T) {
if got, want := body["error"].(string), spec.msg; !strings.Contains(got, want) {
t.Errorf(`body["error"] = %q; want %q; on spec.err=%v`, got, want, spec.err)
}

if spec.details != "" {
details, ok := body["details"].([]interface{})
if !ok {
t.Errorf(`body["details"] = %T; want %T`, body["details"], []interface{}{})
continue
}
if len(details) != 1 {
t.Errorf(`len(body["details"]) = %v; want 1`, len(details))
continue
}
if details[0].(map[string]interface{})["@type"] != spec.details {
t.Errorf(`details.@type = %s; want %s`, details[0].(map[string]interface{})["@type"], spec.details)
}
}
}
}

0 comments on commit da583f8

Please sign in to comment.