Skip to content

Commit 070d9c7

Browse files
authored
codes: replace %q to %d in error string when invalid code is an integer (#7188)
1 parent 5d24ee2 commit 070d9c7

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

codes/codes.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ func (c *Code) UnmarshalJSON(b []byte) error {
235235

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

241241
*c = Code(ci)

codes/codes_test.go

+12-2
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,10 @@ package codes
2020

2121
import (
2222
"encoding/json"
23-
"reflect"
23+
"strings"
2424
"testing"
2525

26+
"github.com/google/go-cmp/cmp"
2627
cpb "google.golang.org/genproto/googleapis/rpc/code"
2728
"google.golang.org/grpc/internal/grpctest"
2829
)
@@ -50,7 +51,7 @@ func (s) TestJSONUnmarshal(t *testing.T) {
5051
want := []Code{OK, NotFound, Internal, Canceled}
5152
in := `["OK", "NOT_FOUND", "INTERNAL", "CANCELLED"]`
5253
err := json.Unmarshal([]byte(in), &got)
53-
if err != nil || !reflect.DeepEqual(got, want) {
54+
if err != nil || !cmp.Equal(got, want) {
5455
t.Fatalf("json.Unmarshal(%q, &got) = %v; want <nil>. got=%v; want %v", in, err, got, want)
5556
}
5657
}
@@ -91,3 +92,12 @@ func (s) TestUnmarshalJSON_MarshalUnmarshal(t *testing.T) {
9192
}
9293
}
9394
}
95+
96+
func (s) TestUnmarshalJSON_InvalidIntegerCode(t *testing.T) {
97+
const wantErr = "invalid code: 200" // for integer invalid code, expect integer value in error message
98+
99+
var got Code
100+
if err := got.UnmarshalJSON([]byte("200")); !strings.Contains(err.Error(), wantErr) {
101+
t.Errorf("got.UnmarshalJSON(200) = %v; wantErr: %v", err, wantErr)
102+
}
103+
}

0 commit comments

Comments
 (0)