codes_test.go 2.3 KB

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