Skip to content

Commit

Permalink
codes: replace %q to %d in error string when invalid code is an integ…
Browse files Browse the repository at this point in the history
…er (#7188)
  • Loading branch information
purnesh42H committed May 9, 2024
1 parent 5d24ee2 commit 070d9c7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
2 changes: 1 addition & 1 deletion codes/codes.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ func (c *Code) UnmarshalJSON(b []byte) error {

if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil {
if ci >= _maxCode {
return fmt.Errorf("invalid code: %q", ci)
return fmt.Errorf("invalid code: %d", ci)
}

*c = Code(ci)
Expand Down
14 changes: 12 additions & 2 deletions codes/codes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ package codes

import (
"encoding/json"
"reflect"
"strings"
"testing"

"github.com/google/go-cmp/cmp"
cpb "google.golang.org/genproto/googleapis/rpc/code"
"google.golang.org/grpc/internal/grpctest"
)
Expand Down Expand Up @@ -50,7 +51,7 @@ func (s) TestJSONUnmarshal(t *testing.T) {
want := []Code{OK, NotFound, Internal, Canceled}
in := `["OK", "NOT_FOUND", "INTERNAL", "CANCELLED"]`
err := json.Unmarshal([]byte(in), &got)
if err != nil || !reflect.DeepEqual(got, want) {
if err != nil || !cmp.Equal(got, want) {
t.Fatalf("json.Unmarshal(%q, &got) = %v; want <nil>. got=%v; want %v", in, err, got, want)
}
}
Expand Down Expand Up @@ -91,3 +92,12 @@ func (s) TestUnmarshalJSON_MarshalUnmarshal(t *testing.T) {
}
}
}

func (s) TestUnmarshalJSON_InvalidIntegerCode(t *testing.T) {
const wantErr = "invalid code: 200" // for integer invalid code, expect integer value in error message

var got Code
if err := got.UnmarshalJSON([]byte("200")); !strings.Contains(err.Error(), wantErr) {
t.Errorf("got.UnmarshalJSON(200) = %v; wantErr: %v", err, wantErr)
}
}

0 comments on commit 070d9c7

Please sign in to comment.