From 070d9c793af46df05f24b4de548509627606f5b7 Mon Sep 17 00:00:00 2001 From: Purnesh Dixit Date: Thu, 9 May 2024 21:41:37 +0530 Subject: [PATCH] codes: replace %q to %d in error string when invalid code is an integer (#7188) --- codes/codes.go | 2 +- codes/codes_test.go | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/codes/codes.go b/codes/codes.go index 08476ad1fe17..0b42c302b24b 100644 --- a/codes/codes.go +++ b/codes/codes.go @@ -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) diff --git a/codes/codes_test.go b/codes/codes_test.go index cb43408aa6b6..e27ff61d40ff 100644 --- a/codes/codes_test.go +++ b/codes/codes_test.go @@ -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" ) @@ -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 . got=%v; want %v", in, err, got, want) } } @@ -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) + } +}