jsonpb_test.go 46 KB

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