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