gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/grpc/codes/codes_test.go (about) 1 /* 2 * 3 * Copyright 2017 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 package codes 20 21 import ( 22 "encoding/json" 23 "reflect" 24 "testing" 25 26 "gitee.com/ks-custle/core-gm/grpc/internal/grpctest" 27 cpb "google.golang.org/genproto/googleapis/rpc/code" 28 ) 29 30 type s struct { 31 grpctest.Tester 32 } 33 34 func Test(t *testing.T) { 35 grpctest.RunSubTests(t, s{}) 36 } 37 38 func (s) TestUnmarshalJSON(t *testing.T) { 39 for s, v := range cpb.Code_value { 40 want := Code(v) 41 var got Code 42 if err := got.UnmarshalJSON([]byte(`"` + s + `"`)); err != nil || got != want { 43 t.Errorf("got.UnmarshalJSON(%q) = %v; want <nil>. got=%v; want %v", s, err, got, want) 44 } 45 } 46 } 47 48 func (s) TestJSONUnmarshal(t *testing.T) { 49 var got []Code 50 want := []Code{OK, NotFound, Internal, Canceled} 51 in := `["OK", "NOT_FOUND", "INTERNAL", "CANCELLED"]` 52 err := json.Unmarshal([]byte(in), &got) 53 if err != nil || !reflect.DeepEqual(got, want) { 54 t.Fatalf("json.Unmarshal(%q, &got) = %v; want <nil>. got=%v; want %v", in, err, got, want) 55 } 56 } 57 58 func (s) TestUnmarshalJSON_NilReceiver(t *testing.T) { 59 var got *Code 60 in := OK.String() 61 if err := got.UnmarshalJSON([]byte(in)); err == nil { 62 t.Errorf("got.UnmarshalJSON(%q) = nil; want <non-nil>. got=%v", in, got) 63 } 64 } 65 66 func (s) TestUnmarshalJSON_UnknownInput(t *testing.T) { 67 var got Code 68 for _, in := range [][]byte{[]byte(""), []byte("xxx"), []byte("Code(17)"), nil} { 69 if err := got.UnmarshalJSON([]byte(in)); err == nil { 70 t.Errorf("got.UnmarshalJSON(%q) = nil; want <non-nil>. got=%v", in, got) 71 } 72 } 73 } 74 75 func (s) TestUnmarshalJSON_MarshalUnmarshal(t *testing.T) { 76 for i := 0; i < _maxCode; i++ { 77 var cUnMarshaled Code 78 c := Code(i) 79 80 cJSON, err := json.Marshal(c) 81 if err != nil { 82 t.Errorf("marshalling %q failed: %v", c, err) 83 } 84 85 if err := json.Unmarshal(cJSON, &cUnMarshaled); err != nil { 86 t.Errorf("unmarshalling code failed: %s", err) 87 } 88 89 if c != cUnMarshaled { 90 t.Errorf("code is %q after marshalling/unmarshalling, expected %q", cUnMarshaled, c) 91 } 92 } 93 }