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 19package codes 20 21import ( 22 "encoding/json" 23 "reflect" 24 "testing" 25 26 cpb "google.golang.org/genproto/googleapis/rpc/code" 27) 28 29func TestUnmarshalJSON(t *testing.T) { 30 for s, v := range cpb.Code_value { 31 want := Code(v) 32 var got Code 33 if err := got.UnmarshalJSON([]byte(`"` + s + `"`)); err != nil || got != want { 34 t.Errorf("got.UnmarshalJSON(%q) = %v; want <nil>. got=%v; want %v", s, err, got, want) 35 } 36 } 37} 38 39func TestJSONUnmarshal(t *testing.T) { 40 var got []Code 41 want := []Code{OK, NotFound, Internal, Canceled} 42 in := `["OK", "NOT_FOUND", "INTERNAL", "CANCELLED"]` 43 err := json.Unmarshal([]byte(in), &got) 44 if err != nil || !reflect.DeepEqual(got, want) { 45 t.Fatalf("json.Unmarshal(%q, &got) = %v; want <nil>. got=%v; want %v", in, err, got, want) 46 } 47} 48 49func TestUnmarshalJSON_NilReceiver(t *testing.T) { 50 var got *Code 51 in := OK.String() 52 if err := got.UnmarshalJSON([]byte(in)); err == nil { 53 t.Errorf("got.UnmarshalJSON(%q) = nil; want <non-nil>. got=%v", in, got) 54 } 55} 56 57func TestUnmarshalJSON_UnknownInput(t *testing.T) { 58 var got Code 59 for _, in := range [][]byte{[]byte(""), []byte("xxx"), []byte("Code(17)"), nil} { 60 if err := got.UnmarshalJSON([]byte(in)); err == nil { 61 t.Errorf("got.UnmarshalJSON(%q) = nil; want <non-nil>. got=%v", in, got) 62 } 63 } 64} 65 66func TestUnmarshalJSON_MarshalUnmarshal(t *testing.T) { 67 for i := 0; i < _maxCode; i++ { 68 var cUnMarshaled Code 69 c := Code(i) 70 71 cJSON, err := json.Marshal(c) 72 if err != nil { 73 t.Errorf("marshalling %q failed: %v", c, err) 74 } 75 76 if err := json.Unmarshal(cJSON, &cUnMarshaled); err != nil { 77 t.Errorf("unmarshalling code failed: %s", err) 78 } 79 80 if c != cUnMarshaled { 81 t.Errorf("code is %q after marshalling/unmarshalling, expected %q", cUnMarshaled, c) 82 } 83 } 84} 85