jsonpb_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2015 The Go Authors. All rights reserved.
  4. // https://github.com/golang/protobuf
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. package jsonpb
  32. import (
  33. "bytes"
  34. "encoding/json"
  35. "io"
  36. "reflect"
  37. "strings"
  38. "testing"
  39. "github.com/golang/protobuf/proto"
  40. pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto"
  41. proto3pb "github.com/golang/protobuf/proto/proto3_proto"
  42. anypb "github.com/golang/protobuf/ptypes/any"
  43. durpb "github.com/golang/protobuf/ptypes/duration"
  44. stpb "github.com/golang/protobuf/ptypes/struct"
  45. tspb "github.com/golang/protobuf/ptypes/timestamp"
  46. wpb "github.com/golang/protobuf/ptypes/wrappers"
  47. )
  48. var (
  49. marshaler = Marshaler{}
  50. marshalerAllOptions = Marshaler{
  51. Indent: " ",
  52. }
  53. simpleObject = &pb.Simple{
  54. OInt32: proto.Int32(-32),
  55. OInt64: proto.Int64(-6400000000),
  56. OUint32: proto.Uint32(32),
  57. OUint64: proto.Uint64(6400000000),
  58. OSint32: proto.Int32(-13),
  59. OSint64: proto.Int64(-2600000000),
  60. OFloat: proto.Float32(3.14),
  61. ODouble: proto.Float64(6.02214179e23),
  62. OBool: proto.Bool(true),
  63. OString: proto.String("hello \"there\""),
  64. OBytes: []byte("beep boop"),
  65. }
  66. simpleObjectJSON = `{` +
  67. `"oBool":true,` +
  68. `"oInt32":-32,` +
  69. `"oInt64":"-6400000000",` +
  70. `"oUint32":32,` +
  71. `"oUint64":"6400000000",` +
  72. `"oSint32":-13,` +
  73. `"oSint64":"-2600000000",` +
  74. `"oFloat":3.14,` +
  75. `"oDouble":6.02214179e+23,` +
  76. `"oString":"hello \"there\"",` +
  77. `"oBytes":"YmVlcCBib29w"` +
  78. `}`
  79. simpleObjectPrettyJSON = `{
  80. "oBool": true,
  81. "oInt32": -32,
  82. "oInt64": "-6400000000",
  83. "oUint32": 32,
  84. "oUint64": "6400000000",
  85. "oSint32": -13,
  86. "oSint64": "-2600000000",
  87. "oFloat": 3.14,
  88. "oDouble": 6.02214179e+23,
  89. "oString": "hello \"there\"",
  90. "oBytes": "YmVlcCBib29w"
  91. }`
  92. repeatsObject = &pb.Repeats{
  93. RBool: []bool{true, false, true},
  94. RInt32: []int32{-3, -4, -5},
  95. RInt64: []int64{-123456789, -987654321},
  96. RUint32: []uint32{1, 2, 3},
  97. RUint64: []uint64{6789012345, 3456789012},
  98. RSint32: []int32{-1, -2, -3},
  99. RSint64: []int64{-6789012345, -3456789012},
  100. RFloat: []float32{3.14, 6.28},
  101. RDouble: []float64{299792458 * 1e20, 6.62606957e-34},
  102. RString: []string{"happy", "days"},
  103. RBytes: [][]byte{[]byte("skittles"), []byte("m&m's")},
  104. }
  105. repeatsObjectJSON = `{` +
  106. `"rBool":[true,false,true],` +
  107. `"rInt32":[-3,-4,-5],` +
  108. `"rInt64":["-123456789","-987654321"],` +
  109. `"rUint32":[1,2,3],` +
  110. `"rUint64":["6789012345","3456789012"],` +
  111. `"rSint32":[-1,-2,-3],` +
  112. `"rSint64":["-6789012345","-3456789012"],` +
  113. `"rFloat":[3.14,6.28],` +
  114. `"rDouble":[2.99792458e+28,6.62606957e-34],` +
  115. `"rString":["happy","days"],` +
  116. `"rBytes":["c2tpdHRsZXM=","bSZtJ3M="]` +
  117. `}`
  118. repeatsObjectPrettyJSON = `{
  119. "rBool": [
  120. true,
  121. false,
  122. true
  123. ],
  124. "rInt32": [
  125. -3,
  126. -4,
  127. -5
  128. ],
  129. "rInt64": [
  130. "-123456789",
  131. "-987654321"
  132. ],
  133. "rUint32": [
  134. 1,
  135. 2,
  136. 3
  137. ],
  138. "rUint64": [
  139. "6789012345",
  140. "3456789012"
  141. ],
  142. "rSint32": [
  143. -1,
  144. -2,
  145. -3
  146. ],
  147. "rSint64": [
  148. "-6789012345",
  149. "-3456789012"
  150. ],
  151. "rFloat": [
  152. 3.14,
  153. 6.28
  154. ],
  155. "rDouble": [
  156. 2.99792458e+28,
  157. 6.62606957e-34
  158. ],
  159. "rString": [
  160. "happy",
  161. "days"
  162. ],
  163. "rBytes": [
  164. "c2tpdHRsZXM=",
  165. "bSZtJ3M="
  166. ]
  167. }`
  168. innerSimple = &pb.Simple{OInt32: proto.Int32(-32)}
  169. innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)}
  170. innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}}
  171. innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}}
  172. complexObject = &pb.Widget{
  173. Color: pb.Widget_GREEN.Enum(),
  174. RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE},
  175. Simple: innerSimple,
  176. RSimple: []*pb.Simple{innerSimple, innerSimple2},
  177. Repeats: innerRepeats,
  178. RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2},
  179. }
  180. complexObjectJSON = `{"color":"GREEN",` +
  181. `"rColor":["RED","GREEN","BLUE"],` +
  182. `"simple":{"oInt32":-32},` +
  183. `"rSimple":[{"oInt32":-32},{"oInt64":"25"}],` +
  184. `"repeats":{"rString":["roses","red"]},` +
  185. `"rRepeats":[{"rString":["roses","red"]},{"rString":["violets","blue"]}]` +
  186. `}`
  187. complexObjectPrettyJSON = `{
  188. "color": "GREEN",
  189. "rColor": [
  190. "RED",
  191. "GREEN",
  192. "BLUE"
  193. ],
  194. "simple": {
  195. "oInt32": -32
  196. },
  197. "rSimple": [
  198. {
  199. "oInt32": -32
  200. },
  201. {
  202. "oInt64": "25"
  203. }
  204. ],
  205. "repeats": {
  206. "rString": [
  207. "roses",
  208. "red"
  209. ]
  210. },
  211. "rRepeats": [
  212. {
  213. "rString": [
  214. "roses",
  215. "red"
  216. ]
  217. },
  218. {
  219. "rString": [
  220. "violets",
  221. "blue"
  222. ]
  223. }
  224. ]
  225. }`
  226. colorPrettyJSON = `{
  227. "color": 2
  228. }`
  229. colorListPrettyJSON = `{
  230. "color": 1000,
  231. "rColor": [
  232. "RED"
  233. ]
  234. }`
  235. nummyPrettyJSON = `{
  236. "nummy": {
  237. "1": 2,
  238. "3": 4
  239. }
  240. }`
  241. objjyPrettyJSON = `{
  242. "objjy": {
  243. "1": {
  244. "dub": 1
  245. }
  246. }
  247. }`
  248. realNumber = &pb.Real{Value: proto.Float64(3.14159265359)}
  249. realNumberName = "Pi"
  250. complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)}
  251. realNumberJSON = `{` +
  252. `"value":3.14159265359,` +
  253. `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` +
  254. `"[jsonpb.name]":"Pi"` +
  255. `}`
  256. anySimple = &pb.KnownTypes{
  257. An: &anypb.Any{
  258. TypeUrl: "something.example.com/jsonpb.Simple",
  259. Value: []byte{
  260. // &pb.Simple{OBool:true}
  261. 1 << 3, 1,
  262. },
  263. },
  264. }
  265. anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb.Simple","oBool":true}}`
  266. anySimplePrettyJSON = `{
  267. "an": {
  268. "@type": "something.example.com/jsonpb.Simple",
  269. "oBool": true
  270. }
  271. }`
  272. anyWellKnown = &pb.KnownTypes{
  273. An: &anypb.Any{
  274. TypeUrl: "type.googleapis.com/google.protobuf.Duration",
  275. Value: []byte{
  276. // &durpb.Duration{Seconds: 1, Nanos: 212000000 }
  277. 1 << 3, 1, // seconds
  278. 2 << 3, 0x80, 0xba, 0x8b, 0x65, // nanos
  279. },
  280. },
  281. }
  282. anyWellKnownJSON = `{"an":{"@type":"type.googleapis.com/google.protobuf.Duration","value":"1.212s"}}`
  283. anyWellKnownPrettyJSON = `{
  284. "an": {
  285. "@type": "type.googleapis.com/google.protobuf.Duration",
  286. "value": "1.212s"
  287. }
  288. }`
  289. )
  290. func init() {
  291. if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil {
  292. panic(err)
  293. }
  294. if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil {
  295. panic(err)
  296. }
  297. }
  298. var marshalingTests = []struct {
  299. desc string
  300. marshaler Marshaler
  301. pb proto.Message
  302. json string
  303. }{
  304. {"simple flat object", marshaler, simpleObject, simpleObjectJSON},
  305. {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON},
  306. {"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON},
  307. {"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON},
  308. {"nested message/enum flat object", marshaler, complexObject, complexObjectJSON},
  309. {"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON},
  310. {"enum-string flat object", Marshaler{},
  311. &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`},
  312. {"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "},
  313. &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON},
  314. {"unknown enum value object", marshalerAllOptions,
  315. &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON},
  316. {"repeated proto3 enum", Marshaler{},
  317. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  318. proto3pb.Message_PUNS,
  319. proto3pb.Message_SLAPSTICK,
  320. }},
  321. `{"rFunny":["PUNS","SLAPSTICK"]}`},
  322. {"repeated proto3 enum as int", Marshaler{EnumsAsInts: true},
  323. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  324. proto3pb.Message_PUNS,
  325. proto3pb.Message_SLAPSTICK,
  326. }},
  327. `{"rFunny":[1,2]}`},
  328. {"empty value", marshaler, &pb.Simple3{}, `{}`},
  329. {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`},
  330. {"map<int64, int32>", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`},
  331. {"map<int64, int32>", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON},
  332. {"map<string, string>", marshaler,
  333. &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}},
  334. `{"strry":{"\"one\"":"two","three":"four"}}`},
  335. {"map<int32, Object>", marshaler,
  336. &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: &pb.Simple3{Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`},
  337. {"map<int32, Object>", marshalerAllOptions,
  338. &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: &pb.Simple3{Dub: 1}}}, objjyPrettyJSON},
  339. {"map<int64, string>", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}},
  340. `{"buggy":{"1234":"yup"}}`},
  341. {"map<bool, bool>", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`},
  342. // TODO: This is broken.
  343. //{"map<string, enum>", marshaler, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}`},
  344. {"map<string, enum as int>", Marshaler{EnumsAsInts: true}, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`},
  345. {"map<int32, bool>", marshaler, &pb.Mappy{S32Booly: map[int32]bool{1: true, 3: false, 10: true, 12: false}}, `{"s32booly":{"1":true,"3":false,"10":true,"12":false}}`},
  346. {"map<int64, bool>", marshaler, &pb.Mappy{S64Booly: map[int64]bool{1: true, 3: false, 10: true, 12: false}}, `{"s64booly":{"1":true,"3":false,"10":true,"12":false}}`},
  347. {"map<uint32, bool>", marshaler, &pb.Mappy{U32Booly: map[uint32]bool{1: true, 3: false, 10: true, 12: false}}, `{"u32booly":{"1":true,"3":false,"10":true,"12":false}}`},
  348. {"map<uint64, bool>", marshaler, &pb.Mappy{U64Booly: map[uint64]bool{1: true, 3: false, 10: true, 12: false}}, `{"u64booly":{"1":true,"3":false,"10":true,"12":false}}`},
  349. {"proto2 map<int64, string>", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}},
  350. `{"mInt64Str":{"213":"cat"}}`},
  351. {"proto2 map<bool, Object>", marshaler,
  352. &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: &pb.Simple{OInt32: proto.Int32(1)}}},
  353. `{"mBoolSimple":{"true":{"oInt32":1}}}`},
  354. {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`},
  355. {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`},
  356. {"force orig_name", Marshaler{OrigName: true}, &pb.Simple{OInt32: proto.Int32(4)},
  357. `{"o_int32":4}`},
  358. {"proto2 extension", marshaler, realNumber, realNumberJSON},
  359. {"Any with message", marshaler, anySimple, anySimpleJSON},
  360. {"Any with message and indent", marshalerAllOptions, anySimple, anySimplePrettyJSON},
  361. {"Any with WKT", marshaler, anyWellKnown, anyWellKnownJSON},
  362. {"Any with WKT and indent", marshalerAllOptions, anyWellKnown, anyWellKnownPrettyJSON},
  363. {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}, `{"dur":"3.000s"}`},
  364. {"Struct", marshaler, &pb.KnownTypes{St: &stpb.Struct{
  365. Fields: map[string]*stpb.Value{
  366. "one": &stpb.Value{Kind: &stpb.Value_StringValue{"loneliest number"}},
  367. "two": &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}},
  368. },
  369. }}, `{"st":{"one":"loneliest number","two":null}}`},
  370. {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`},
  371. {"DoubleValue", marshaler, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`},
  372. {"FloatValue", marshaler, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}, `{"flt":1.2}`},
  373. {"Int64Value", marshaler, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}, `{"i64":"-3"}`},
  374. {"UInt64Value", marshaler, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}, `{"u64":"3"}`},
  375. {"Int32Value", marshaler, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}, `{"i32":-4}`},
  376. {"UInt32Value", marshaler, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}, `{"u32":4}`},
  377. {"BoolValue", marshaler, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}, `{"bool":true}`},
  378. {"StringValue", marshaler, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}, `{"str":"plush"}`},
  379. {"BytesValue", marshaler, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`},
  380. }
  381. func TestMarshaling(t *testing.T) {
  382. for _, tt := range marshalingTests {
  383. json, err := tt.marshaler.MarshalToString(tt.pb)
  384. if err != nil {
  385. t.Errorf("%s: marshaling error: %v", tt.desc, err)
  386. } else if tt.json != json {
  387. t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json)
  388. }
  389. }
  390. }
  391. var unmarshalingTests = []struct {
  392. desc string
  393. unmarshaler Unmarshaler
  394. json string
  395. pb proto.Message
  396. }{
  397. {"simple flat object", Unmarshaler{}, simpleObjectJSON, simpleObject},
  398. {"simple pretty object", Unmarshaler{}, simpleObjectPrettyJSON, simpleObject},
  399. {"repeated fields flat object", Unmarshaler{}, repeatsObjectJSON, repeatsObject},
  400. {"repeated fields pretty object", Unmarshaler{}, repeatsObjectPrettyJSON, repeatsObject},
  401. {"nested message/enum flat object", Unmarshaler{}, complexObjectJSON, complexObject},
  402. {"nested message/enum pretty object", Unmarshaler{}, complexObjectPrettyJSON, complexObject},
  403. {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}},
  404. {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}},
  405. {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb.Simple)},
  406. {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
  407. {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
  408. {"unknown enum value object",
  409. Unmarshaler{},
  410. "{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}",
  411. &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}},
  412. {"repeated proto3 enum", Unmarshaler{}, `{"rFunny":["PUNS","SLAPSTICK"]}`,
  413. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  414. proto3pb.Message_PUNS,
  415. proto3pb.Message_SLAPSTICK,
  416. }}},
  417. {"repeated proto3 enum as int", Unmarshaler{}, `{"rFunny":[1,2]}`,
  418. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  419. proto3pb.Message_PUNS,
  420. proto3pb.Message_SLAPSTICK,
  421. }}},
  422. {"repeated proto3 enum as mix of strings and ints", Unmarshaler{}, `{"rFunny":["PUNS",2]}`,
  423. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  424. proto3pb.Message_PUNS,
  425. proto3pb.Message_SLAPSTICK,
  426. }}},
  427. {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}},
  428. {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}},
  429. {"map<int64, int32>", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}},
  430. {"map<string, string>", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}},
  431. {"map<int32, Object>", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: &pb.Simple3{Dub: 1}}}},
  432. // TODO: This is broken.
  433. //{"map<string, enum>", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}},
  434. {"map<string, enum as int>", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}},
  435. {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{31000}}},
  436. {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}},
  437. {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}},
  438. {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}},
  439. {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}},
  440. {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb.Simple{OBool: proto.Bool(true)}},
  441. {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb.Simple{OBool: proto.Bool(true)}},
  442. {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}},
  443. {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}},
  444. {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -2, Nanos: 999999995}}},
  445. {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -62135596800, Nanos: 0}}},
  446. {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}},
  447. {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}},
  448. {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}},
  449. {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}},
  450. {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}},
  451. {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}},
  452. {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}},
  453. {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}},
  454. {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}},
  455. // `null` is also a permissible value. Let's just test one.
  456. {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb.KnownTypes{Dbl: &wpb.DoubleValue{}}},
  457. }
  458. func TestUnmarshaling(t *testing.T) {
  459. for _, tt := range unmarshalingTests {
  460. // Make a new instance of the type of our expected object.
  461. p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message)
  462. err := tt.unmarshaler.Unmarshal(strings.NewReader(tt.json), p)
  463. if err != nil {
  464. t.Errorf("%s: %v", tt.desc, err)
  465. continue
  466. }
  467. // For easier diffs, compare text strings of the protos.
  468. exp := proto.MarshalTextString(tt.pb)
  469. act := proto.MarshalTextString(p)
  470. if string(exp) != string(act) {
  471. t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp)
  472. }
  473. }
  474. }
  475. func TestUnmarshalNext(t *testing.T) {
  476. // We only need to check against a few, not all of them.
  477. tests := unmarshalingTests[:5]
  478. // Create a buffer with many concatenated JSON objects.
  479. var b bytes.Buffer
  480. for _, tt := range tests {
  481. b.WriteString(tt.json)
  482. }
  483. dec := json.NewDecoder(&b)
  484. for _, tt := range tests {
  485. // Make a new instance of the type of our expected object.
  486. p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message)
  487. err := tt.unmarshaler.UnmarshalNext(dec, p)
  488. if err != nil {
  489. t.Errorf("%s: %v", tt.desc, err)
  490. continue
  491. }
  492. // For easier diffs, compare text strings of the protos.
  493. exp := proto.MarshalTextString(tt.pb)
  494. act := proto.MarshalTextString(p)
  495. if string(exp) != string(act) {
  496. t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp)
  497. }
  498. }
  499. p := &pb.Simple{}
  500. err := new(Unmarshaler).UnmarshalNext(dec, p)
  501. if err != io.EOF {
  502. t.Errorf("eof: got %v, expected io.EOF", err)
  503. }
  504. }
  505. var unmarshalingShouldError = []struct {
  506. desc string
  507. in string
  508. pb proto.Message
  509. }{
  510. {"a value", "666", new(pb.Simple)},
  511. {"gibberish", "{adskja123;l23=-=", new(pb.Simple)},
  512. {"unknown field", `{"unknown": "foo"}`, new(pb.Simple)},
  513. {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)},
  514. }
  515. func TestUnmarshalingBadInput(t *testing.T) {
  516. for _, tt := range unmarshalingShouldError {
  517. err := UnmarshalString(tt.in, tt.pb)
  518. if err == nil {
  519. t.Errorf("an error was expected when parsing %q instead of an object", tt.desc)
  520. }
  521. }
  522. }