jsonpb_test.go 42 KB

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