jsonpb_test.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  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. "math"
  37. "reflect"
  38. "strings"
  39. "testing"
  40. "github.com/golang/protobuf/proto"
  41. pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto"
  42. proto3pb "github.com/golang/protobuf/proto/proto3_proto"
  43. "github.com/golang/protobuf/ptypes"
  44. anypb "github.com/golang/protobuf/ptypes/any"
  45. durpb "github.com/golang/protobuf/ptypes/duration"
  46. stpb "github.com/golang/protobuf/ptypes/struct"
  47. tspb "github.com/golang/protobuf/ptypes/timestamp"
  48. wpb "github.com/golang/protobuf/ptypes/wrappers"
  49. )
  50. var (
  51. marshaler = Marshaler{}
  52. marshalerAllOptions = Marshaler{
  53. Indent: " ",
  54. }
  55. simpleObject = &pb.Simple{
  56. OInt32: proto.Int32(-32),
  57. OInt64: proto.Int64(-6400000000),
  58. OUint32: proto.Uint32(32),
  59. OUint64: proto.Uint64(6400000000),
  60. OSint32: proto.Int32(-13),
  61. OSint64: proto.Int64(-2600000000),
  62. OFloat: proto.Float32(3.14),
  63. ODouble: proto.Float64(6.02214179e23),
  64. OBool: proto.Bool(true),
  65. OString: proto.String("hello \"there\""),
  66. OBytes: []byte("beep boop"),
  67. }
  68. simpleObjectJSON = `{` +
  69. `"oBool":true,` +
  70. `"oInt32":-32,` +
  71. `"oInt64":"-6400000000",` +
  72. `"oUint32":32,` +
  73. `"oUint64":"6400000000",` +
  74. `"oSint32":-13,` +
  75. `"oSint64":"-2600000000",` +
  76. `"oFloat":3.14,` +
  77. `"oDouble":6.02214179e+23,` +
  78. `"oString":"hello \"there\"",` +
  79. `"oBytes":"YmVlcCBib29w"` +
  80. `}`
  81. simpleObjectPrettyJSON = `{
  82. "oBool": true,
  83. "oInt32": -32,
  84. "oInt64": "-6400000000",
  85. "oUint32": 32,
  86. "oUint64": "6400000000",
  87. "oSint32": -13,
  88. "oSint64": "-2600000000",
  89. "oFloat": 3.14,
  90. "oDouble": 6.02214179e+23,
  91. "oString": "hello \"there\"",
  92. "oBytes": "YmVlcCBib29w"
  93. }`
  94. repeatsObject = &pb.Repeats{
  95. RBool: []bool{true, false, true},
  96. RInt32: []int32{-3, -4, -5},
  97. RInt64: []int64{-123456789, -987654321},
  98. RUint32: []uint32{1, 2, 3},
  99. RUint64: []uint64{6789012345, 3456789012},
  100. RSint32: []int32{-1, -2, -3},
  101. RSint64: []int64{-6789012345, -3456789012},
  102. RFloat: []float32{3.14, 6.28},
  103. RDouble: []float64{299792458 * 1e20, 6.62606957e-34},
  104. RString: []string{"happy", "days"},
  105. RBytes: [][]byte{[]byte("skittles"), []byte("m&m's")},
  106. }
  107. repeatsObjectJSON = `{` +
  108. `"rBool":[true,false,true],` +
  109. `"rInt32":[-3,-4,-5],` +
  110. `"rInt64":["-123456789","-987654321"],` +
  111. `"rUint32":[1,2,3],` +
  112. `"rUint64":["6789012345","3456789012"],` +
  113. `"rSint32":[-1,-2,-3],` +
  114. `"rSint64":["-6789012345","-3456789012"],` +
  115. `"rFloat":[3.14,6.28],` +
  116. `"rDouble":[2.99792458e+28,6.62606957e-34],` +
  117. `"rString":["happy","days"],` +
  118. `"rBytes":["c2tpdHRsZXM=","bSZtJ3M="]` +
  119. `}`
  120. repeatsObjectPrettyJSON = `{
  121. "rBool": [
  122. true,
  123. false,
  124. true
  125. ],
  126. "rInt32": [
  127. -3,
  128. -4,
  129. -5
  130. ],
  131. "rInt64": [
  132. "-123456789",
  133. "-987654321"
  134. ],
  135. "rUint32": [
  136. 1,
  137. 2,
  138. 3
  139. ],
  140. "rUint64": [
  141. "6789012345",
  142. "3456789012"
  143. ],
  144. "rSint32": [
  145. -1,
  146. -2,
  147. -3
  148. ],
  149. "rSint64": [
  150. "-6789012345",
  151. "-3456789012"
  152. ],
  153. "rFloat": [
  154. 3.14,
  155. 6.28
  156. ],
  157. "rDouble": [
  158. 2.99792458e+28,
  159. 6.62606957e-34
  160. ],
  161. "rString": [
  162. "happy",
  163. "days"
  164. ],
  165. "rBytes": [
  166. "c2tpdHRsZXM=",
  167. "bSZtJ3M="
  168. ]
  169. }`
  170. innerSimple = &pb.Simple{OInt32: proto.Int32(-32)}
  171. innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)}
  172. innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}}
  173. innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}}
  174. complexObject = &pb.Widget{
  175. Color: pb.Widget_GREEN.Enum(),
  176. RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE},
  177. Simple: innerSimple,
  178. RSimple: []*pb.Simple{innerSimple, innerSimple2},
  179. Repeats: innerRepeats,
  180. RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2},
  181. }
  182. complexObjectJSON = `{"color":"GREEN",` +
  183. `"rColor":["RED","GREEN","BLUE"],` +
  184. `"simple":{"oInt32":-32},` +
  185. `"rSimple":[{"oInt32":-32},{"oInt64":"25"}],` +
  186. `"repeats":{"rString":["roses","red"]},` +
  187. `"rRepeats":[{"rString":["roses","red"]},{"rString":["violets","blue"]}]` +
  188. `}`
  189. complexObjectPrettyJSON = `{
  190. "color": "GREEN",
  191. "rColor": [
  192. "RED",
  193. "GREEN",
  194. "BLUE"
  195. ],
  196. "simple": {
  197. "oInt32": -32
  198. },
  199. "rSimple": [
  200. {
  201. "oInt32": -32
  202. },
  203. {
  204. "oInt64": "25"
  205. }
  206. ],
  207. "repeats": {
  208. "rString": [
  209. "roses",
  210. "red"
  211. ]
  212. },
  213. "rRepeats": [
  214. {
  215. "rString": [
  216. "roses",
  217. "red"
  218. ]
  219. },
  220. {
  221. "rString": [
  222. "violets",
  223. "blue"
  224. ]
  225. }
  226. ]
  227. }`
  228. colorPrettyJSON = `{
  229. "color": 2
  230. }`
  231. colorListPrettyJSON = `{
  232. "color": 1000,
  233. "rColor": [
  234. "RED"
  235. ]
  236. }`
  237. nummyPrettyJSON = `{
  238. "nummy": {
  239. "1": 2,
  240. "3": 4
  241. }
  242. }`
  243. objjyPrettyJSON = `{
  244. "objjy": {
  245. "1": {
  246. "dub": 1
  247. }
  248. }
  249. }`
  250. realNumber = &pb.Real{Value: proto.Float64(3.14159265359)}
  251. realNumberName = "Pi"
  252. complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)}
  253. realNumberJSON = `{` +
  254. `"value":3.14159265359,` +
  255. `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` +
  256. `"[jsonpb.name]":"Pi"` +
  257. `}`
  258. anySimple = &pb.KnownTypes{
  259. An: &anypb.Any{
  260. TypeUrl: "something.example.com/jsonpb.Simple",
  261. Value: []byte{
  262. // &pb.Simple{OBool:true}
  263. 1 << 3, 1,
  264. },
  265. },
  266. }
  267. anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb.Simple","oBool":true}}`
  268. anySimplePrettyJSON = `{
  269. "an": {
  270. "@type": "something.example.com/jsonpb.Simple",
  271. "oBool": true
  272. }
  273. }`
  274. anyWellKnown = &pb.KnownTypes{
  275. An: &anypb.Any{
  276. TypeUrl: "type.googleapis.com/google.protobuf.Duration",
  277. Value: []byte{
  278. // &durpb.Duration{Seconds: 1, Nanos: 212000000 }
  279. 1 << 3, 1, // seconds
  280. 2 << 3, 0x80, 0xba, 0x8b, 0x65, // nanos
  281. },
  282. },
  283. }
  284. anyWellKnownJSON = `{"an":{"@type":"type.googleapis.com/google.protobuf.Duration","value":"1.212s"}}`
  285. anyWellKnownPrettyJSON = `{
  286. "an": {
  287. "@type": "type.googleapis.com/google.protobuf.Duration",
  288. "value": "1.212s"
  289. }
  290. }`
  291. nonFinites = &pb.NonFinites{
  292. FNan: proto.Float32(float32(math.NaN())),
  293. FPinf: proto.Float32(float32(math.Inf(1))),
  294. FNinf: proto.Float32(float32(math.Inf(-1))),
  295. DNan: proto.Float64(float64(math.NaN())),
  296. DPinf: proto.Float64(float64(math.Inf(1))),
  297. DNinf: proto.Float64(float64(math.Inf(-1))),
  298. }
  299. nonFinitesJSON = `{` +
  300. `"fNan":"NaN",` +
  301. `"fPinf":"Infinity",` +
  302. `"fNinf":"-Infinity",` +
  303. `"dNan":"NaN",` +
  304. `"dPinf":"Infinity",` +
  305. `"dNinf":"-Infinity"` +
  306. `}`
  307. )
  308. func init() {
  309. if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil {
  310. panic(err)
  311. }
  312. if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil {
  313. panic(err)
  314. }
  315. }
  316. var marshalingTests = []struct {
  317. desc string
  318. marshaler Marshaler
  319. pb proto.Message
  320. json string
  321. }{
  322. {"simple flat object", marshaler, simpleObject, simpleObjectJSON},
  323. {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON},
  324. {"non-finite floats fields object", marshaler, nonFinites, nonFinitesJSON},
  325. {"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON},
  326. {"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON},
  327. {"nested message/enum flat object", marshaler, complexObject, complexObjectJSON},
  328. {"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON},
  329. {"enum-string flat object", Marshaler{},
  330. &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`},
  331. {"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "},
  332. &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON},
  333. {"unknown enum value object", marshalerAllOptions,
  334. &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON},
  335. {"repeated proto3 enum", Marshaler{},
  336. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  337. proto3pb.Message_PUNS,
  338. proto3pb.Message_SLAPSTICK,
  339. }},
  340. `{"rFunny":["PUNS","SLAPSTICK"]}`},
  341. {"repeated proto3 enum as int", Marshaler{EnumsAsInts: true},
  342. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  343. proto3pb.Message_PUNS,
  344. proto3pb.Message_SLAPSTICK,
  345. }},
  346. `{"rFunny":[1,2]}`},
  347. {"empty value", marshaler, &pb.Simple3{}, `{}`},
  348. {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`},
  349. {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb.SimpleSlice3{}, `{"slices":[]}`},
  350. {"empty map emitted", Marshaler{EmitDefaults: true}, &pb.SimpleMap3{}, `{"stringy":{}}`},
  351. {"nested struct null", Marshaler{EmitDefaults: true}, &pb.SimpleNull3{}, `{"simple":null}`},
  352. {"map<int64, int32>", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`},
  353. {"map<int64, int32>", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON},
  354. {"map<string, string>", marshaler,
  355. &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}},
  356. `{"strry":{"\"one\"":"two","three":"four"}}`},
  357. {"map<int32, Object>", marshaler,
  358. &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`},
  359. {"map<int32, Object>", marshalerAllOptions,
  360. &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, objjyPrettyJSON},
  361. {"map<int64, string>", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}},
  362. `{"buggy":{"1234":"yup"}}`},
  363. {"map<bool, bool>", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`},
  364. // TODO: This is broken.
  365. //{"map<string, enum>", marshaler, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}`},
  366. {"map<string, enum as int>", Marshaler{EnumsAsInts: true}, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`},
  367. {"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}}`},
  368. {"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}}`},
  369. {"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}}`},
  370. {"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}}`},
  371. {"proto2 map<int64, string>", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}},
  372. `{"mInt64Str":{"213":"cat"}}`},
  373. {"proto2 map<bool, Object>", marshaler,
  374. &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: {OInt32: proto.Int32(1)}}},
  375. `{"mBoolSimple":{"true":{"oInt32":1}}}`},
  376. {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`},
  377. {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`},
  378. {"force orig_name", Marshaler{OrigName: true}, &pb.Simple{OInt32: proto.Int32(4)},
  379. `{"o_int32":4}`},
  380. {"proto2 extension", marshaler, realNumber, realNumberJSON},
  381. {"Any with message", marshaler, anySimple, anySimpleJSON},
  382. {"Any with message and indent", marshalerAllOptions, anySimple, anySimplePrettyJSON},
  383. {"Any with WKT", marshaler, anyWellKnown, anyWellKnownJSON},
  384. {"Any with WKT and indent", marshalerAllOptions, anyWellKnown, anyWellKnownPrettyJSON},
  385. {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}, `{"dur":"3s"}`},
  386. {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3, Nanos: 1e6}}, `{"dur":"3.001s"}`},
  387. {"Duration beyond float64 precision", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 100000000, Nanos: 1}}, `{"dur":"100000000.000000001s"}`},
  388. {"negative Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: -123, Nanos: -456}}, `{"dur":"-123.000000456s"}`},
  389. {"Struct", marshaler, &pb.KnownTypes{St: &stpb.Struct{
  390. Fields: map[string]*stpb.Value{
  391. "one": {Kind: &stpb.Value_StringValue{"loneliest number"}},
  392. "two": {Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}},
  393. },
  394. }}, `{"st":{"one":"loneliest number","two":null}}`},
  395. {"empty ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{}}, `{"lv":[]}`},
  396. {"basic ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{
  397. {Kind: &stpb.Value_StringValue{"x"}},
  398. {Kind: &stpb.Value_NullValue{}},
  399. {Kind: &stpb.Value_NumberValue{3}},
  400. {Kind: &stpb.Value_BoolValue{true}},
  401. }}}, `{"lv":["x",null,3,true]}`},
  402. {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`},
  403. {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}, `{"ts":"2014-05-13T16:53:20Z"}`},
  404. {"number Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}, `{"val":1}`},
  405. {"null Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}, `{"val":null}`},
  406. {"string number value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}, `{"val":"9223372036854775807"}`},
  407. {"list of lists Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{
  408. Kind: &stpb.Value_ListValue{&stpb.ListValue{
  409. Values: []*stpb.Value{
  410. {Kind: &stpb.Value_StringValue{"x"}},
  411. {Kind: &stpb.Value_ListValue{&stpb.ListValue{
  412. Values: []*stpb.Value{
  413. {Kind: &stpb.Value_ListValue{&stpb.ListValue{
  414. Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}},
  415. }}},
  416. {Kind: &stpb.Value_StringValue{"z"}},
  417. },
  418. }}},
  419. },
  420. }},
  421. }}, `{"val":["x",[["y"],"z"]]}`},
  422. {"DoubleValue", marshaler, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`},
  423. {"FloatValue", marshaler, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}, `{"flt":1.2}`},
  424. {"Int64Value", marshaler, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}, `{"i64":"-3"}`},
  425. {"UInt64Value", marshaler, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}, `{"u64":"3"}`},
  426. {"Int32Value", marshaler, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}, `{"i32":-4}`},
  427. {"UInt32Value", marshaler, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}, `{"u32":4}`},
  428. {"BoolValue", marshaler, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}, `{"bool":true}`},
  429. {"StringValue", marshaler, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}, `{"str":"plush"}`},
  430. {"BytesValue", marshaler, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`},
  431. {"required", marshaler, &pb.MsgWithRequired{Str: proto.String("hello")}, `{"str":"hello"}`},
  432. {"required bytes", marshaler, &pb.MsgWithRequiredBytes{Byts: []byte{}}, `{"byts":""}`},
  433. }
  434. func TestMarshaling(t *testing.T) {
  435. for _, tt := range marshalingTests {
  436. json, err := tt.marshaler.MarshalToString(tt.pb)
  437. if err != nil {
  438. t.Errorf("%s: marshaling error: %v", tt.desc, err)
  439. } else if tt.json != json {
  440. t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json)
  441. }
  442. }
  443. }
  444. func TestMarshalingNil(t *testing.T) {
  445. var msg *pb.Simple
  446. m := &Marshaler{}
  447. if _, err := m.MarshalToString(msg); err == nil {
  448. t.Errorf("mashaling nil returned no error")
  449. }
  450. }
  451. func TestMarshalIllegalTime(t *testing.T) {
  452. tests := []struct {
  453. pb proto.Message
  454. fail bool
  455. }{
  456. {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: 1, Nanos: 0}}, false},
  457. {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: -1, Nanos: 0}}, false},
  458. {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: 1, Nanos: -1}}, true},
  459. {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: -1, Nanos: 1}}, true},
  460. {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: 1, Nanos: 1000000000}}, true},
  461. {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: -1, Nanos: -1000000000}}, true},
  462. {&pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 1, Nanos: 1}}, false},
  463. {&pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 1, Nanos: -1}}, true},
  464. {&pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 1, Nanos: 1000000000}}, true},
  465. }
  466. for _, tt := range tests {
  467. _, err := marshaler.MarshalToString(tt.pb)
  468. if err == nil && tt.fail {
  469. t.Errorf("marshaler.MarshalToString(%v) = _, <nil>; want _, <non-nil>", tt.pb)
  470. }
  471. if err != nil && !tt.fail {
  472. t.Errorf("marshaler.MarshalToString(%v) = _, %v; want _, <nil>", tt.pb, err)
  473. }
  474. }
  475. }
  476. func TestMarshalJSONPBMarshaler(t *testing.T) {
  477. rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }`
  478. msg := dynamicMessage{rawJson: rawJson}
  479. str, err := new(Marshaler).MarshalToString(&msg)
  480. if err != nil {
  481. t.Errorf("an unexpected error occurred when marshalling JSONPBMarshaler: %v", err)
  482. }
  483. if str != rawJson {
  484. t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, rawJson)
  485. }
  486. }
  487. func TestMarshalAnyJSONPBMarshaler(t *testing.T) {
  488. msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`}
  489. a, err := ptypes.MarshalAny(&msg)
  490. if err != nil {
  491. t.Errorf("an unexpected error occurred when marshalling to Any: %v", err)
  492. }
  493. str, err := new(Marshaler).MarshalToString(a)
  494. if err != nil {
  495. t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err)
  496. }
  497. // after custom marshaling, it's round-tripped through JSON decoding/encoding already,
  498. // so the keys are sorted, whitespace is compacted, and "@type" key has been added
  499. expected := `{"@type":"type.googleapis.com/` + dynamicMessageName + `","baz":[0,1,2,3],"foo":"bar"}`
  500. if str != expected {
  501. t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected)
  502. }
  503. }
  504. // Test marshaling message containing unset required fields should produce error.
  505. func TestMarshalUnsetRequiredFields(t *testing.T) {
  506. msgExt := &pb.Real{}
  507. proto.SetExtension(msgExt, pb.E_Extm, &pb.MsgWithRequired{})
  508. tests := []struct {
  509. desc string
  510. marshaler *Marshaler
  511. pb proto.Message
  512. }{
  513. {
  514. desc: "direct required field",
  515. marshaler: &Marshaler{},
  516. pb: &pb.MsgWithRequired{},
  517. },
  518. {
  519. desc: "direct required field + emit defaults",
  520. marshaler: &Marshaler{EmitDefaults: true},
  521. pb: &pb.MsgWithRequired{},
  522. },
  523. {
  524. desc: "indirect required field",
  525. marshaler: &Marshaler{},
  526. pb: &pb.MsgWithIndirectRequired{Subm: &pb.MsgWithRequired{}},
  527. },
  528. {
  529. desc: "indirect required field + emit defaults",
  530. marshaler: &Marshaler{EmitDefaults: true},
  531. pb: &pb.MsgWithIndirectRequired{Subm: &pb.MsgWithRequired{}},
  532. },
  533. {
  534. desc: "direct required wkt field",
  535. marshaler: &Marshaler{},
  536. pb: &pb.MsgWithRequiredWKT{},
  537. },
  538. {
  539. desc: "direct required wkt field + emit defaults",
  540. marshaler: &Marshaler{EmitDefaults: true},
  541. pb: &pb.MsgWithRequiredWKT{},
  542. },
  543. {
  544. desc: "direct required bytes field",
  545. marshaler: &Marshaler{},
  546. pb: &pb.MsgWithRequiredBytes{},
  547. },
  548. {
  549. desc: "required in map value",
  550. marshaler: &Marshaler{},
  551. pb: &pb.MsgWithIndirectRequired{
  552. MapField: map[string]*pb.MsgWithRequired{
  553. "key": {},
  554. },
  555. },
  556. },
  557. {
  558. desc: "required in repeated item",
  559. marshaler: &Marshaler{},
  560. pb: &pb.MsgWithIndirectRequired{
  561. SliceField: []*pb.MsgWithRequired{
  562. {Str: proto.String("hello")},
  563. {},
  564. },
  565. },
  566. },
  567. {
  568. desc: "required inside oneof",
  569. marshaler: &Marshaler{},
  570. pb: &pb.MsgWithOneof{
  571. Union: &pb.MsgWithOneof_MsgWithRequired{&pb.MsgWithRequired{}},
  572. },
  573. },
  574. {
  575. desc: "required inside extension",
  576. marshaler: &Marshaler{},
  577. pb: msgExt,
  578. },
  579. }
  580. for _, tc := range tests {
  581. if _, err := tc.marshaler.MarshalToString(tc.pb); err == nil {
  582. t.Errorf("%s: expecting error in marshaling with unset required fields %+v", tc.desc, tc.pb)
  583. }
  584. }
  585. }
  586. var unmarshalingTests = []struct {
  587. desc string
  588. unmarshaler Unmarshaler
  589. json string
  590. pb proto.Message
  591. }{
  592. {"simple flat object", Unmarshaler{}, simpleObjectJSON, simpleObject},
  593. {"simple pretty object", Unmarshaler{}, simpleObjectPrettyJSON, simpleObject},
  594. {"repeated fields flat object", Unmarshaler{}, repeatsObjectJSON, repeatsObject},
  595. {"repeated fields pretty object", Unmarshaler{}, repeatsObjectPrettyJSON, repeatsObject},
  596. {"nested message/enum flat object", Unmarshaler{}, complexObjectJSON, complexObject},
  597. {"nested message/enum pretty object", Unmarshaler{}, complexObjectPrettyJSON, complexObject},
  598. {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}},
  599. {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}},
  600. {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb.Simple)},
  601. {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
  602. {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
  603. {"unknown enum value object",
  604. Unmarshaler{},
  605. "{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}",
  606. &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}},
  607. {"repeated proto3 enum", Unmarshaler{}, `{"rFunny":["PUNS","SLAPSTICK"]}`,
  608. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  609. proto3pb.Message_PUNS,
  610. proto3pb.Message_SLAPSTICK,
  611. }}},
  612. {"repeated proto3 enum as int", Unmarshaler{}, `{"rFunny":[1,2]}`,
  613. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  614. proto3pb.Message_PUNS,
  615. proto3pb.Message_SLAPSTICK,
  616. }}},
  617. {"repeated proto3 enum as mix of strings and ints", Unmarshaler{}, `{"rFunny":["PUNS",2]}`,
  618. &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
  619. proto3pb.Message_PUNS,
  620. proto3pb.Message_SLAPSTICK,
  621. }}},
  622. {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}},
  623. {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}},
  624. {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb.Simple{ODouble: proto.Float64(math.NaN())}},
  625. {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}},
  626. {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb.Simple{ODouble: proto.Float64(math.Inf(-1))}},
  627. {"map<int64, int32>", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}},
  628. {"map<string, string>", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}},
  629. {"map<int32, Object>", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}},
  630. {"proto2 extension", Unmarshaler{}, realNumberJSON, realNumber},
  631. {"Any with message", Unmarshaler{}, anySimpleJSON, anySimple},
  632. {"Any with message and indent", Unmarshaler{}, anySimplePrettyJSON, anySimple},
  633. {"Any with WKT", Unmarshaler{}, anyWellKnownJSON, anyWellKnown},
  634. {"Any with WKT and indent", Unmarshaler{}, anyWellKnownPrettyJSON, anyWellKnown},
  635. // TODO: This is broken.
  636. //{"map<string, enum>", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}},
  637. {"map<string, enum as int>", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}},
  638. {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{31000}}},
  639. {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}},
  640. {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}},
  641. {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}},
  642. {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}},
  643. {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb.Simple{OBool: proto.Bool(true)}},
  644. {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb.Simple{OBool: proto.Bool(true)}},
  645. {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}},
  646. {"Duration", Unmarshaler{}, `{"dur":"4s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 4}}},
  647. {"null Duration", Unmarshaler{}, `{"dur":null}`, &pb.KnownTypes{Dur: nil}},
  648. {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}},
  649. {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}},
  650. {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -2, Nanos: 999999995}}},
  651. {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -62135596800, Nanos: 0}}},
  652. {"null Timestamp", Unmarshaler{}, `{"ts":null}`, &pb.KnownTypes{Ts: nil}},
  653. {"null Struct", Unmarshaler{}, `{"st": null}`, &pb.KnownTypes{St: nil}},
  654. {"empty Struct", Unmarshaler{}, `{"st": {}}`, &pb.KnownTypes{St: &stpb.Struct{}}},
  655. {"basic Struct", Unmarshaler{}, `{"st": {"a": "x", "b": null, "c": 3, "d": true}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{
  656. "a": {Kind: &stpb.Value_StringValue{"x"}},
  657. "b": {Kind: &stpb.Value_NullValue{}},
  658. "c": {Kind: &stpb.Value_NumberValue{3}},
  659. "d": {Kind: &stpb.Value_BoolValue{true}},
  660. }}}},
  661. {"nested Struct", Unmarshaler{}, `{"st": {"a": {"b": 1, "c": [{"d": true}, "f"]}}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{
  662. "a": {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{
  663. "b": {Kind: &stpb.Value_NumberValue{1}},
  664. "c": {Kind: &stpb.Value_ListValue{&stpb.ListValue{Values: []*stpb.Value{
  665. {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{"d": {Kind: &stpb.Value_BoolValue{true}}}}}},
  666. {Kind: &stpb.Value_StringValue{"f"}},
  667. }}}},
  668. }}}},
  669. }}}},
  670. {"null ListValue", Unmarshaler{}, `{"lv": null}`, &pb.KnownTypes{Lv: nil}},
  671. {"empty ListValue", Unmarshaler{}, `{"lv": []}`, &pb.KnownTypes{Lv: &stpb.ListValue{}}},
  672. {"basic ListValue", Unmarshaler{}, `{"lv": ["x", null, 3, true]}`, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{
  673. {Kind: &stpb.Value_StringValue{"x"}},
  674. {Kind: &stpb.Value_NullValue{}},
  675. {Kind: &stpb.Value_NumberValue{3}},
  676. {Kind: &stpb.Value_BoolValue{true}},
  677. }}}},
  678. {"number Value", Unmarshaler{}, `{"val":1}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}},
  679. {"null Value", Unmarshaler{}, `{"val":null}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}},
  680. {"bool Value", Unmarshaler{}, `{"val":true}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_BoolValue{true}}}},
  681. {"string Value", Unmarshaler{}, `{"val":"x"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"x"}}}},
  682. {"string number value", Unmarshaler{}, `{"val":"9223372036854775807"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}},
  683. {"list of lists Value", Unmarshaler{}, `{"val":["x", [["y"], "z"]]}`, &pb.KnownTypes{Val: &stpb.Value{
  684. Kind: &stpb.Value_ListValue{&stpb.ListValue{
  685. Values: []*stpb.Value{
  686. {Kind: &stpb.Value_StringValue{"x"}},
  687. {Kind: &stpb.Value_ListValue{&stpb.ListValue{
  688. Values: []*stpb.Value{
  689. {Kind: &stpb.Value_ListValue{&stpb.ListValue{
  690. Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}},
  691. }}},
  692. {Kind: &stpb.Value_StringValue{"z"}},
  693. },
  694. }}},
  695. },
  696. }}}}},
  697. {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}},
  698. {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}},
  699. {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}},
  700. {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}},
  701. {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}},
  702. {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}},
  703. {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}},
  704. {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}},
  705. {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}},
  706. // Ensure that `null` as a value ends up with a nil pointer instead of a [type]Value struct.
  707. {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb.KnownTypes{Dbl: nil}},
  708. {"null FloatValue", Unmarshaler{}, `{"flt":null}`, &pb.KnownTypes{Flt: nil}},
  709. {"null Int64Value", Unmarshaler{}, `{"i64":null}`, &pb.KnownTypes{I64: nil}},
  710. {"null UInt64Value", Unmarshaler{}, `{"u64":null}`, &pb.KnownTypes{U64: nil}},
  711. {"null Int32Value", Unmarshaler{}, `{"i32":null}`, &pb.KnownTypes{I32: nil}},
  712. {"null UInt32Value", Unmarshaler{}, `{"u32":null}`, &pb.KnownTypes{U32: nil}},
  713. {"null BoolValue", Unmarshaler{}, `{"bool":null}`, &pb.KnownTypes{Bool: nil}},
  714. {"null StringValue", Unmarshaler{}, `{"str":null}`, &pb.KnownTypes{Str: nil}},
  715. {"null BytesValue", Unmarshaler{}, `{"bytes":null}`, &pb.KnownTypes{Bytes: nil}},
  716. {"required", Unmarshaler{}, `{"str":"hello"}`, &pb.MsgWithRequired{Str: proto.String("hello")}},
  717. {"required bytes", Unmarshaler{}, `{"byts": []}`, &pb.MsgWithRequiredBytes{Byts: []byte{}}},
  718. }
  719. func TestUnmarshaling(t *testing.T) {
  720. for _, tt := range unmarshalingTests {
  721. // Make a new instance of the type of our expected object.
  722. p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message)
  723. err := tt.unmarshaler.Unmarshal(strings.NewReader(tt.json), p)
  724. if err != nil {
  725. t.Errorf("%s: %v", tt.desc, err)
  726. continue
  727. }
  728. // For easier diffs, compare text strings of the protos.
  729. exp := proto.MarshalTextString(tt.pb)
  730. act := proto.MarshalTextString(p)
  731. if string(exp) != string(act) {
  732. t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp)
  733. }
  734. }
  735. }
  736. func TestUnmarshalNullArray(t *testing.T) {
  737. var repeats pb.Repeats
  738. if err := UnmarshalString(`{"rBool":null}`, &repeats); err != nil {
  739. t.Fatal(err)
  740. }
  741. if !reflect.DeepEqual(repeats, pb.Repeats{}) {
  742. t.Errorf("got non-nil fields in [%#v]", repeats)
  743. }
  744. }
  745. func TestUnmarshalNullObject(t *testing.T) {
  746. var maps pb.Maps
  747. if err := UnmarshalString(`{"mInt64Str":null}`, &maps); err != nil {
  748. t.Fatal(err)
  749. }
  750. if !reflect.DeepEqual(maps, pb.Maps{}) {
  751. t.Errorf("got non-nil fields in [%#v]", maps)
  752. }
  753. }
  754. func TestUnmarshalNext(t *testing.T) {
  755. // We only need to check against a few, not all of them.
  756. tests := unmarshalingTests[:5]
  757. // Create a buffer with many concatenated JSON objects.
  758. var b bytes.Buffer
  759. for _, tt := range tests {
  760. b.WriteString(tt.json)
  761. }
  762. dec := json.NewDecoder(&b)
  763. for _, tt := range tests {
  764. // Make a new instance of the type of our expected object.
  765. p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message)
  766. err := tt.unmarshaler.UnmarshalNext(dec, p)
  767. if err != nil {
  768. t.Errorf("%s: %v", tt.desc, err)
  769. continue
  770. }
  771. // For easier diffs, compare text strings of the protos.
  772. exp := proto.MarshalTextString(tt.pb)
  773. act := proto.MarshalTextString(p)
  774. if string(exp) != string(act) {
  775. t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp)
  776. }
  777. }
  778. p := &pb.Simple{}
  779. err := new(Unmarshaler).UnmarshalNext(dec, p)
  780. if err != io.EOF {
  781. t.Errorf("eof: got %v, expected io.EOF", err)
  782. }
  783. }
  784. var unmarshalingShouldError = []struct {
  785. desc string
  786. in string
  787. pb proto.Message
  788. }{
  789. {"a value", "666", new(pb.Simple)},
  790. {"gibberish", "{adskja123;l23=-=", new(pb.Simple)},
  791. {"unknown field", `{"unknown": "foo"}`, new(pb.Simple)},
  792. {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)},
  793. }
  794. func TestUnmarshalingBadInput(t *testing.T) {
  795. for _, tt := range unmarshalingShouldError {
  796. err := UnmarshalString(tt.in, tt.pb)
  797. if err == nil {
  798. t.Errorf("an error was expected when parsing %q instead of an object", tt.desc)
  799. }
  800. }
  801. }
  802. type funcResolver func(turl string) (proto.Message, error)
  803. func (fn funcResolver) Resolve(turl string) (proto.Message, error) {
  804. return fn(turl)
  805. }
  806. func TestAnyWithCustomResolver(t *testing.T) {
  807. var resolvedTypeUrls []string
  808. resolver := funcResolver(func(turl string) (proto.Message, error) {
  809. resolvedTypeUrls = append(resolvedTypeUrls, turl)
  810. return new(pb.Simple), nil
  811. })
  812. msg := &pb.Simple{
  813. OBytes: []byte{1, 2, 3, 4},
  814. OBool: proto.Bool(true),
  815. OString: proto.String("foobar"),
  816. OInt64: proto.Int64(1020304),
  817. }
  818. msgBytes, err := proto.Marshal(msg)
  819. if err != nil {
  820. t.Errorf("an unexpected error occurred when marshaling message: %v", err)
  821. }
  822. // make an Any with a type URL that won't resolve w/out custom resolver
  823. any := &anypb.Any{
  824. TypeUrl: "https://foobar.com/some.random.MessageKind",
  825. Value: msgBytes,
  826. }
  827. m := Marshaler{AnyResolver: resolver}
  828. js, err := m.MarshalToString(any)
  829. if err != nil {
  830. t.Errorf("an unexpected error occurred when marshaling any to JSON: %v", err)
  831. }
  832. if len(resolvedTypeUrls) != 1 {
  833. t.Errorf("custom resolver was not invoked during marshaling")
  834. } else if resolvedTypeUrls[0] != "https://foobar.com/some.random.MessageKind" {
  835. t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[0], "https://foobar.com/some.random.MessageKind")
  836. }
  837. wanted := `{"@type":"https://foobar.com/some.random.MessageKind","oBool":true,"oInt64":"1020304","oString":"foobar","oBytes":"AQIDBA=="}`
  838. if js != wanted {
  839. t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", js, wanted)
  840. }
  841. u := Unmarshaler{AnyResolver: resolver}
  842. roundTrip := &anypb.Any{}
  843. err = u.Unmarshal(bytes.NewReader([]byte(js)), roundTrip)
  844. if err != nil {
  845. t.Errorf("an unexpected error occurred when unmarshaling any from JSON: %v", err)
  846. }
  847. if len(resolvedTypeUrls) != 2 {
  848. t.Errorf("custom resolver was not invoked during marshaling")
  849. } else if resolvedTypeUrls[1] != "https://foobar.com/some.random.MessageKind" {
  850. t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[1], "https://foobar.com/some.random.MessageKind")
  851. }
  852. if !proto.Equal(any, roundTrip) {
  853. t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", roundTrip, any)
  854. }
  855. }
  856. func TestUnmarshalJSONPBUnmarshaler(t *testing.T) {
  857. rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }`
  858. var msg dynamicMessage
  859. if err := Unmarshal(strings.NewReader(rawJson), &msg); err != nil {
  860. t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err)
  861. }
  862. if msg.rawJson != rawJson {
  863. t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", msg.rawJson, rawJson)
  864. }
  865. }
  866. func TestUnmarshalNullWithJSONPBUnmarshaler(t *testing.T) {
  867. rawJson := `{"stringField":null}`
  868. var ptrFieldMsg ptrFieldMessage
  869. if err := Unmarshal(strings.NewReader(rawJson), &ptrFieldMsg); err != nil {
  870. t.Errorf("unmarshal error: %v", err)
  871. }
  872. want := ptrFieldMessage{StringField: &stringField{IsSet: true, StringValue: "null"}}
  873. if !proto.Equal(&ptrFieldMsg, &want) {
  874. t.Errorf("unmarshal result StringField: got %v, want %v", ptrFieldMsg, want)
  875. }
  876. }
  877. func TestUnmarshalAnyJSONPBUnmarshaler(t *testing.T) {
  878. rawJson := `{ "@type": "blah.com/` + dynamicMessageName + `", "foo": "bar", "baz": [0, 1, 2, 3] }`
  879. var got anypb.Any
  880. if err := Unmarshal(strings.NewReader(rawJson), &got); err != nil {
  881. t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err)
  882. }
  883. dm := &dynamicMessage{rawJson: `{"baz":[0,1,2,3],"foo":"bar"}`}
  884. var want anypb.Any
  885. if b, err := proto.Marshal(dm); err != nil {
  886. t.Errorf("an unexpected error occurred when marshaling message: %v", err)
  887. } else {
  888. want.TypeUrl = "blah.com/" + dynamicMessageName
  889. want.Value = b
  890. }
  891. if !proto.Equal(&got, &want) {
  892. t.Errorf("message contents not set correctly after unmarshalling JSON: got %v, wanted %v", got, want)
  893. }
  894. }
  895. const (
  896. dynamicMessageName = "google.protobuf.jsonpb.testing.dynamicMessage"
  897. )
  898. func init() {
  899. // we register the custom type below so that we can use it in Any types
  900. proto.RegisterType((*dynamicMessage)(nil), dynamicMessageName)
  901. }
  902. type ptrFieldMessage struct {
  903. StringField *stringField `protobuf:"bytes,1,opt,name=stringField"`
  904. }
  905. func (m *ptrFieldMessage) Reset() {
  906. }
  907. func (m *ptrFieldMessage) String() string {
  908. return m.StringField.StringValue
  909. }
  910. func (m *ptrFieldMessage) ProtoMessage() {
  911. }
  912. type stringField struct {
  913. IsSet bool `protobuf:"varint,1,opt,name=isSet"`
  914. StringValue string `protobuf:"bytes,2,opt,name=stringValue"`
  915. }
  916. func (s *stringField) Reset() {
  917. }
  918. func (s *stringField) String() string {
  919. return s.StringValue
  920. }
  921. func (s *stringField) ProtoMessage() {
  922. }
  923. func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
  924. s.IsSet = true
  925. s.StringValue = string(js)
  926. return nil
  927. }
  928. // dynamicMessage implements protobuf.Message but is not a normal generated message type.
  929. // It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support.
  930. type dynamicMessage struct {
  931. rawJson string `protobuf:"bytes,1,opt,name=rawJson"`
  932. }
  933. func (m *dynamicMessage) Reset() {
  934. m.rawJson = "{}"
  935. }
  936. func (m *dynamicMessage) String() string {
  937. return m.rawJson
  938. }
  939. func (m *dynamicMessage) ProtoMessage() {
  940. }
  941. func (m *dynamicMessage) MarshalJSONPB(jm *Marshaler) ([]byte, error) {
  942. return []byte(m.rawJson), nil
  943. }
  944. func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
  945. m.rawJson = string(js)
  946. return nil
  947. }
  948. // Test unmarshaling message containing unset required fields should produce error.
  949. func TestUnmarshalUnsetRequiredFields(t *testing.T) {
  950. tests := []struct {
  951. desc string
  952. pb proto.Message
  953. json string
  954. }{
  955. {
  956. desc: "direct required field missing",
  957. pb: &pb.MsgWithRequired{},
  958. json: `{}`,
  959. },
  960. {
  961. desc: "direct required field set to null",
  962. pb: &pb.MsgWithRequired{},
  963. json: `{"str": null}`,
  964. },
  965. {
  966. desc: "indirect required field missing",
  967. pb: &pb.MsgWithIndirectRequired{},
  968. json: `{"subm": {}}`,
  969. },
  970. {
  971. desc: "indirect required field set to null",
  972. pb: &pb.MsgWithIndirectRequired{},
  973. json: `{"subm": {"str": null}}`,
  974. },
  975. {
  976. desc: "direct required bytes field missing",
  977. pb: &pb.MsgWithRequiredBytes{},
  978. json: `{}`,
  979. },
  980. {
  981. desc: "direct required bytes field set to null",
  982. pb: &pb.MsgWithRequiredBytes{},
  983. json: `{"byts": null}`,
  984. },
  985. {
  986. desc: "direct required wkt field missing",
  987. pb: &pb.MsgWithRequiredWKT{},
  988. json: `{}`,
  989. },
  990. {
  991. desc: "direct required wkt field set to null",
  992. pb: &pb.MsgWithRequiredWKT{},
  993. json: `{"str": null}`,
  994. },
  995. {
  996. desc: "any containing message with required field set to null",
  997. pb: &pb.KnownTypes{},
  998. json: `{"an": {"@type": "example.com/jsonpb.MsgWithRequired", "str": null}}`,
  999. },
  1000. {
  1001. desc: "any containing message with missing required field",
  1002. pb: &pb.KnownTypes{},
  1003. json: `{"an": {"@type": "example.com/jsonpb.MsgWithRequired"}}`,
  1004. },
  1005. {
  1006. desc: "missing required in map value",
  1007. pb: &pb.MsgWithIndirectRequired{},
  1008. json: `{"map_field": {"a": {}, "b": {"str": "hi"}}}`,
  1009. },
  1010. {
  1011. desc: "required in map value set to null",
  1012. pb: &pb.MsgWithIndirectRequired{},
  1013. json: `{"map_field": {"a": {"str": "hello"}, "b": {"str": null}}}`,
  1014. },
  1015. {
  1016. desc: "missing required in slice item",
  1017. pb: &pb.MsgWithIndirectRequired{},
  1018. json: `{"slice_field": [{}, {"str": "hi"}]}`,
  1019. },
  1020. {
  1021. desc: "required in slice item set to null",
  1022. pb: &pb.MsgWithIndirectRequired{},
  1023. json: `{"slice_field": [{"str": "hello"}, {"str": null}]}`,
  1024. },
  1025. {
  1026. desc: "required inside oneof missing",
  1027. pb: &pb.MsgWithOneof{},
  1028. json: `{"msgWithRequired": {}}`,
  1029. },
  1030. {
  1031. desc: "required inside oneof set to null",
  1032. pb: &pb.MsgWithOneof{},
  1033. json: `{"msgWithRequired": {"str": null}}`,
  1034. },
  1035. {
  1036. desc: "required field in extension missing",
  1037. pb: &pb.Real{},
  1038. json: `{"[jsonpb.extm]":{}}`,
  1039. },
  1040. {
  1041. desc: "required field in extension set to null",
  1042. pb: &pb.Real{},
  1043. json: `{"[jsonpb.extm]":{"str": null}}`,
  1044. },
  1045. }
  1046. for _, tc := range tests {
  1047. if err := UnmarshalString(tc.json, tc.pb); err == nil {
  1048. t.Errorf("%s: expecting error in unmarshaling with unset required fields %s", tc.desc, tc.json)
  1049. }
  1050. }
  1051. }