jsonpb_test.go 44 KB

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