encode_test.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353
  1. // Copyright 2019 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 protojson_test
  5. import (
  6. "bytes"
  7. "math"
  8. "testing"
  9. "github.com/google/go-cmp/cmp"
  10. "google.golang.org/protobuf/encoding/protojson"
  11. "google.golang.org/protobuf/internal/detrand"
  12. "google.golang.org/protobuf/internal/flags"
  13. "google.golang.org/protobuf/proto"
  14. "google.golang.org/protobuf/reflect/protoregistry"
  15. "google.golang.org/protobuf/testing/protopack"
  16. pb2 "google.golang.org/protobuf/internal/testprotos/textpb2"
  17. pb3 "google.golang.org/protobuf/internal/testprotos/textpb3"
  18. "google.golang.org/protobuf/types/known/anypb"
  19. "google.golang.org/protobuf/types/known/durationpb"
  20. "google.golang.org/protobuf/types/known/emptypb"
  21. "google.golang.org/protobuf/types/known/fieldmaskpb"
  22. "google.golang.org/protobuf/types/known/structpb"
  23. "google.golang.org/protobuf/types/known/timestamppb"
  24. "google.golang.org/protobuf/types/known/wrapperspb"
  25. )
  26. // Disable detrand to enable direct comparisons on outputs.
  27. func init() { detrand.Disable() }
  28. func TestMarshal(t *testing.T) {
  29. tests := []struct {
  30. desc string
  31. mo protojson.MarshalOptions
  32. input proto.Message
  33. want string
  34. wantErr bool // TODO: Verify error message substring.
  35. skip bool
  36. }{{
  37. desc: "proto2 optional scalars not set",
  38. input: &pb2.Scalars{},
  39. want: "{}",
  40. }, {
  41. desc: "proto3 scalars not set",
  42. input: &pb3.Scalars{},
  43. want: "{}",
  44. }, {
  45. desc: "proto3 optional not set",
  46. input: &pb3.Proto3Optional{},
  47. want: "{}",
  48. }, {
  49. desc: "proto2 optional scalars set to zero values",
  50. input: &pb2.Scalars{
  51. OptBool: proto.Bool(false),
  52. OptInt32: proto.Int32(0),
  53. OptInt64: proto.Int64(0),
  54. OptUint32: proto.Uint32(0),
  55. OptUint64: proto.Uint64(0),
  56. OptSint32: proto.Int32(0),
  57. OptSint64: proto.Int64(0),
  58. OptFixed32: proto.Uint32(0),
  59. OptFixed64: proto.Uint64(0),
  60. OptSfixed32: proto.Int32(0),
  61. OptSfixed64: proto.Int64(0),
  62. OptFloat: proto.Float32(0),
  63. OptDouble: proto.Float64(0),
  64. OptBytes: []byte{},
  65. OptString: proto.String(""),
  66. },
  67. want: `{
  68. "optBool": false,
  69. "optInt32": 0,
  70. "optInt64": "0",
  71. "optUint32": 0,
  72. "optUint64": "0",
  73. "optSint32": 0,
  74. "optSint64": "0",
  75. "optFixed32": 0,
  76. "optFixed64": "0",
  77. "optSfixed32": 0,
  78. "optSfixed64": "0",
  79. "optFloat": 0,
  80. "optDouble": 0,
  81. "optBytes": "",
  82. "optString": ""
  83. }`,
  84. }, {
  85. desc: "proto3 optional set to zero values",
  86. input: &pb3.Proto3Optional{
  87. OptBool: proto.Bool(false),
  88. OptInt32: proto.Int32(0),
  89. OptInt64: proto.Int64(0),
  90. OptUint32: proto.Uint32(0),
  91. OptUint64: proto.Uint64(0),
  92. OptFloat: proto.Float32(0),
  93. OptDouble: proto.Float64(0),
  94. OptString: proto.String(""),
  95. OptBytes: []byte{},
  96. OptEnum: pb3.Enum_ZERO.Enum(),
  97. OptMessage: &pb3.Nested{},
  98. },
  99. want: `{
  100. "optBool": false,
  101. "optInt32": 0,
  102. "optInt64": "0",
  103. "optUint32": 0,
  104. "optUint64": "0",
  105. "optFloat": 0,
  106. "optDouble": 0,
  107. "optString": "",
  108. "optBytes": "",
  109. "optEnum": "ZERO",
  110. "optMessage": {}
  111. }`,
  112. }, {
  113. desc: "proto2 optional scalars set to some values",
  114. input: &pb2.Scalars{
  115. OptBool: proto.Bool(true),
  116. OptInt32: proto.Int32(0xff),
  117. OptInt64: proto.Int64(0xdeadbeef),
  118. OptUint32: proto.Uint32(47),
  119. OptUint64: proto.Uint64(0xdeadbeef),
  120. OptSint32: proto.Int32(-1001),
  121. OptSint64: proto.Int64(-0xffff),
  122. OptFixed64: proto.Uint64(64),
  123. OptSfixed32: proto.Int32(-32),
  124. OptFloat: proto.Float32(1.02),
  125. OptDouble: proto.Float64(1.234),
  126. OptBytes: []byte("谷歌"),
  127. OptString: proto.String("谷歌"),
  128. },
  129. want: `{
  130. "optBool": true,
  131. "optInt32": 255,
  132. "optInt64": "3735928559",
  133. "optUint32": 47,
  134. "optUint64": "3735928559",
  135. "optSint32": -1001,
  136. "optSint64": "-65535",
  137. "optFixed64": "64",
  138. "optSfixed32": -32,
  139. "optFloat": 1.02,
  140. "optDouble": 1.234,
  141. "optBytes": "6LC35q2M",
  142. "optString": "谷歌"
  143. }`,
  144. }, {
  145. desc: "string",
  146. input: &pb3.Scalars{
  147. SString: "谷歌",
  148. },
  149. want: `{
  150. "sString": "谷歌"
  151. }`,
  152. }, {
  153. desc: "string with invalid UTF8",
  154. input: &pb3.Scalars{
  155. SString: "abc\xff",
  156. },
  157. wantErr: true,
  158. }, {
  159. desc: "float nan",
  160. input: &pb3.Scalars{
  161. SFloat: float32(math.NaN()),
  162. },
  163. want: `{
  164. "sFloat": "NaN"
  165. }`,
  166. }, {
  167. desc: "float positive infinity",
  168. input: &pb3.Scalars{
  169. SFloat: float32(math.Inf(1)),
  170. },
  171. want: `{
  172. "sFloat": "Infinity"
  173. }`,
  174. }, {
  175. desc: "float negative infinity",
  176. input: &pb3.Scalars{
  177. SFloat: float32(math.Inf(-1)),
  178. },
  179. want: `{
  180. "sFloat": "-Infinity"
  181. }`,
  182. }, {
  183. desc: "double nan",
  184. input: &pb3.Scalars{
  185. SDouble: math.NaN(),
  186. },
  187. want: `{
  188. "sDouble": "NaN"
  189. }`,
  190. }, {
  191. desc: "double positive infinity",
  192. input: &pb3.Scalars{
  193. SDouble: math.Inf(1),
  194. },
  195. want: `{
  196. "sDouble": "Infinity"
  197. }`,
  198. }, {
  199. desc: "double negative infinity",
  200. input: &pb3.Scalars{
  201. SDouble: math.Inf(-1),
  202. },
  203. want: `{
  204. "sDouble": "-Infinity"
  205. }`,
  206. }, {
  207. desc: "proto2 enum not set",
  208. input: &pb2.Enums{},
  209. want: "{}",
  210. }, {
  211. desc: "proto2 enum set to zero value",
  212. input: &pb2.Enums{
  213. OptEnum: pb2.Enum(0).Enum(),
  214. OptNestedEnum: pb2.Enums_NestedEnum(0).Enum(),
  215. },
  216. want: `{
  217. "optEnum": 0,
  218. "optNestedEnum": 0
  219. }`,
  220. }, {
  221. desc: "proto2 enum",
  222. input: &pb2.Enums{
  223. OptEnum: pb2.Enum_ONE.Enum(),
  224. OptNestedEnum: pb2.Enums_UNO.Enum(),
  225. },
  226. want: `{
  227. "optEnum": "ONE",
  228. "optNestedEnum": "UNO"
  229. }`,
  230. }, {
  231. desc: "proto2 enum set to numeric values",
  232. input: &pb2.Enums{
  233. OptEnum: pb2.Enum(2).Enum(),
  234. OptNestedEnum: pb2.Enums_NestedEnum(2).Enum(),
  235. },
  236. want: `{
  237. "optEnum": "TWO",
  238. "optNestedEnum": "DOS"
  239. }`,
  240. }, {
  241. desc: "proto2 enum set to unnamed numeric values",
  242. input: &pb2.Enums{
  243. OptEnum: pb2.Enum(101).Enum(),
  244. OptNestedEnum: pb2.Enums_NestedEnum(-101).Enum(),
  245. },
  246. want: `{
  247. "optEnum": 101,
  248. "optNestedEnum": -101
  249. }`,
  250. }, {
  251. desc: "proto3 enum not set",
  252. input: &pb3.Enums{},
  253. want: "{}",
  254. }, {
  255. desc: "proto3 enum set to zero value",
  256. input: &pb3.Enums{
  257. SEnum: pb3.Enum_ZERO,
  258. SNestedEnum: pb3.Enums_CERO,
  259. },
  260. want: "{}",
  261. }, {
  262. desc: "proto3 enum",
  263. input: &pb3.Enums{
  264. SEnum: pb3.Enum_ONE,
  265. SNestedEnum: pb3.Enums_UNO,
  266. },
  267. want: `{
  268. "sEnum": "ONE",
  269. "sNestedEnum": "UNO"
  270. }`,
  271. }, {
  272. desc: "proto3 enum set to numeric values",
  273. input: &pb3.Enums{
  274. SEnum: 2,
  275. SNestedEnum: 2,
  276. },
  277. want: `{
  278. "sEnum": "TWO",
  279. "sNestedEnum": "DOS"
  280. }`,
  281. }, {
  282. desc: "proto3 enum set to unnamed numeric values",
  283. input: &pb3.Enums{
  284. SEnum: -47,
  285. SNestedEnum: 47,
  286. },
  287. want: `{
  288. "sEnum": -47,
  289. "sNestedEnum": 47
  290. }`,
  291. }, {
  292. desc: "proto2 nested message not set",
  293. input: &pb2.Nests{},
  294. want: "{}",
  295. }, {
  296. desc: "proto2 nested message set to empty",
  297. input: &pb2.Nests{
  298. OptNested: &pb2.Nested{},
  299. Optgroup: &pb2.Nests_OptGroup{},
  300. },
  301. want: `{
  302. "optNested": {},
  303. "optgroup": {}
  304. }`,
  305. }, {
  306. desc: "proto2 nested messages",
  307. input: &pb2.Nests{
  308. OptNested: &pb2.Nested{
  309. OptString: proto.String("nested message"),
  310. OptNested: &pb2.Nested{
  311. OptString: proto.String("another nested message"),
  312. },
  313. },
  314. },
  315. want: `{
  316. "optNested": {
  317. "optString": "nested message",
  318. "optNested": {
  319. "optString": "another nested message"
  320. }
  321. }
  322. }`,
  323. }, {
  324. desc: "proto2 groups",
  325. input: &pb2.Nests{
  326. Optgroup: &pb2.Nests_OptGroup{
  327. OptString: proto.String("inside a group"),
  328. OptNested: &pb2.Nested{
  329. OptString: proto.String("nested message inside a group"),
  330. },
  331. Optnestedgroup: &pb2.Nests_OptGroup_OptNestedGroup{
  332. OptFixed32: proto.Uint32(47),
  333. },
  334. },
  335. },
  336. want: `{
  337. "optgroup": {
  338. "optString": "inside a group",
  339. "optNested": {
  340. "optString": "nested message inside a group"
  341. },
  342. "optnestedgroup": {
  343. "optFixed32": 47
  344. }
  345. }
  346. }`,
  347. }, {
  348. desc: "proto3 nested message not set",
  349. input: &pb3.Nests{},
  350. want: "{}",
  351. }, {
  352. desc: "proto3 nested message set to empty",
  353. input: &pb3.Nests{
  354. SNested: &pb3.Nested{},
  355. },
  356. want: `{
  357. "sNested": {}
  358. }`,
  359. }, {
  360. desc: "proto3 nested message",
  361. input: &pb3.Nests{
  362. SNested: &pb3.Nested{
  363. SString: "nested message",
  364. SNested: &pb3.Nested{
  365. SString: "another nested message",
  366. },
  367. },
  368. },
  369. want: `{
  370. "sNested": {
  371. "sString": "nested message",
  372. "sNested": {
  373. "sString": "another nested message"
  374. }
  375. }
  376. }`,
  377. }, {
  378. desc: "oneof not set",
  379. input: &pb3.Oneofs{},
  380. want: "{}",
  381. }, {
  382. desc: "oneof set to empty string",
  383. input: &pb3.Oneofs{
  384. Union: &pb3.Oneofs_OneofString{},
  385. },
  386. want: `{
  387. "oneofString": ""
  388. }`,
  389. }, {
  390. desc: "oneof set to string",
  391. input: &pb3.Oneofs{
  392. Union: &pb3.Oneofs_OneofString{
  393. OneofString: "hello",
  394. },
  395. },
  396. want: `{
  397. "oneofString": "hello"
  398. }`,
  399. }, {
  400. desc: "oneof set to enum",
  401. input: &pb3.Oneofs{
  402. Union: &pb3.Oneofs_OneofEnum{
  403. OneofEnum: pb3.Enum_ZERO,
  404. },
  405. },
  406. want: `{
  407. "oneofEnum": "ZERO"
  408. }`,
  409. }, {
  410. desc: "oneof set to empty message",
  411. input: &pb3.Oneofs{
  412. Union: &pb3.Oneofs_OneofNested{
  413. OneofNested: &pb3.Nested{},
  414. },
  415. },
  416. want: `{
  417. "oneofNested": {}
  418. }`,
  419. }, {
  420. desc: "oneof set to message",
  421. input: &pb3.Oneofs{
  422. Union: &pb3.Oneofs_OneofNested{
  423. OneofNested: &pb3.Nested{
  424. SString: "nested message",
  425. },
  426. },
  427. },
  428. want: `{
  429. "oneofNested": {
  430. "sString": "nested message"
  431. }
  432. }`,
  433. }, {
  434. desc: "repeated fields not set",
  435. input: &pb2.Repeats{},
  436. want: "{}",
  437. }, {
  438. desc: "repeated fields set to empty slices",
  439. input: &pb2.Repeats{
  440. RptBool: []bool{},
  441. RptInt32: []int32{},
  442. RptInt64: []int64{},
  443. RptUint32: []uint32{},
  444. RptUint64: []uint64{},
  445. RptFloat: []float32{},
  446. RptDouble: []float64{},
  447. RptBytes: [][]byte{},
  448. },
  449. want: "{}",
  450. }, {
  451. desc: "repeated fields set to some values",
  452. input: &pb2.Repeats{
  453. RptBool: []bool{true, false, true, true},
  454. RptInt32: []int32{1, 6, 0, 0},
  455. RptInt64: []int64{-64, 47},
  456. RptUint32: []uint32{0xff, 0xffff},
  457. RptUint64: []uint64{0xdeadbeef},
  458. RptFloat: []float32{float32(math.NaN()), float32(math.Inf(1)), float32(math.Inf(-1)), 1.034},
  459. RptDouble: []float64{math.NaN(), math.Inf(1), math.Inf(-1), 1.23e-308},
  460. RptString: []string{"hello", "世界"},
  461. RptBytes: [][]byte{
  462. []byte("hello"),
  463. []byte("\xe4\xb8\x96\xe7\x95\x8c"),
  464. },
  465. },
  466. want: `{
  467. "rptBool": [
  468. true,
  469. false,
  470. true,
  471. true
  472. ],
  473. "rptInt32": [
  474. 1,
  475. 6,
  476. 0,
  477. 0
  478. ],
  479. "rptInt64": [
  480. "-64",
  481. "47"
  482. ],
  483. "rptUint32": [
  484. 255,
  485. 65535
  486. ],
  487. "rptUint64": [
  488. "3735928559"
  489. ],
  490. "rptFloat": [
  491. "NaN",
  492. "Infinity",
  493. "-Infinity",
  494. 1.034
  495. ],
  496. "rptDouble": [
  497. "NaN",
  498. "Infinity",
  499. "-Infinity",
  500. 1.23e-308
  501. ],
  502. "rptString": [
  503. "hello",
  504. "世界"
  505. ],
  506. "rptBytes": [
  507. "aGVsbG8=",
  508. "5LiW55WM"
  509. ]
  510. }`,
  511. }, {
  512. desc: "repeated enums",
  513. input: &pb2.Enums{
  514. RptEnum: []pb2.Enum{pb2.Enum_ONE, 2, pb2.Enum_TEN, 42},
  515. RptNestedEnum: []pb2.Enums_NestedEnum{2, 47, 10},
  516. },
  517. want: `{
  518. "rptEnum": [
  519. "ONE",
  520. "TWO",
  521. "TEN",
  522. 42
  523. ],
  524. "rptNestedEnum": [
  525. "DOS",
  526. 47,
  527. "DIEZ"
  528. ]
  529. }`,
  530. }, {
  531. desc: "repeated messages set to empty",
  532. input: &pb2.Nests{
  533. RptNested: []*pb2.Nested{},
  534. Rptgroup: []*pb2.Nests_RptGroup{},
  535. },
  536. want: "{}",
  537. }, {
  538. desc: "repeated messages",
  539. input: &pb2.Nests{
  540. RptNested: []*pb2.Nested{
  541. {
  542. OptString: proto.String("repeat nested one"),
  543. },
  544. {
  545. OptString: proto.String("repeat nested two"),
  546. OptNested: &pb2.Nested{
  547. OptString: proto.String("inside repeat nested two"),
  548. },
  549. },
  550. {},
  551. },
  552. },
  553. want: `{
  554. "rptNested": [
  555. {
  556. "optString": "repeat nested one"
  557. },
  558. {
  559. "optString": "repeat nested two",
  560. "optNested": {
  561. "optString": "inside repeat nested two"
  562. }
  563. },
  564. {}
  565. ]
  566. }`,
  567. }, {
  568. desc: "repeated messages contains nil value",
  569. input: &pb2.Nests{
  570. RptNested: []*pb2.Nested{nil, {}},
  571. },
  572. want: `{
  573. "rptNested": [
  574. {},
  575. {}
  576. ]
  577. }`,
  578. }, {
  579. desc: "repeated groups",
  580. input: &pb2.Nests{
  581. Rptgroup: []*pb2.Nests_RptGroup{
  582. {
  583. RptString: []string{"hello", "world"},
  584. },
  585. {},
  586. nil,
  587. },
  588. },
  589. want: `{
  590. "rptgroup": [
  591. {
  592. "rptString": [
  593. "hello",
  594. "world"
  595. ]
  596. },
  597. {},
  598. {}
  599. ]
  600. }`,
  601. }, {
  602. desc: "map fields not set",
  603. input: &pb3.Maps{},
  604. want: "{}",
  605. }, {
  606. desc: "map fields set to empty",
  607. input: &pb3.Maps{
  608. Int32ToStr: map[int32]string{},
  609. BoolToUint32: map[bool]uint32{},
  610. Uint64ToEnum: map[uint64]pb3.Enum{},
  611. StrToNested: map[string]*pb3.Nested{},
  612. StrToOneofs: map[string]*pb3.Oneofs{},
  613. },
  614. want: "{}",
  615. }, {
  616. desc: "map fields 1",
  617. input: &pb3.Maps{
  618. BoolToUint32: map[bool]uint32{
  619. true: 42,
  620. false: 101,
  621. },
  622. },
  623. want: `{
  624. "boolToUint32": {
  625. "false": 101,
  626. "true": 42
  627. }
  628. }`,
  629. }, {
  630. desc: "map fields 2",
  631. input: &pb3.Maps{
  632. Int32ToStr: map[int32]string{
  633. -101: "-101",
  634. 0xff: "0xff",
  635. 0: "zero",
  636. },
  637. },
  638. want: `{
  639. "int32ToStr": {
  640. "-101": "-101",
  641. "0": "zero",
  642. "255": "0xff"
  643. }
  644. }`,
  645. }, {
  646. desc: "map fields 3",
  647. input: &pb3.Maps{
  648. Uint64ToEnum: map[uint64]pb3.Enum{
  649. 1: pb3.Enum_ONE,
  650. 2: pb3.Enum_TWO,
  651. 10: pb3.Enum_TEN,
  652. 47: 47,
  653. },
  654. },
  655. want: `{
  656. "uint64ToEnum": {
  657. "1": "ONE",
  658. "2": "TWO",
  659. "10": "TEN",
  660. "47": 47
  661. }
  662. }`,
  663. }, {
  664. desc: "map fields 4",
  665. input: &pb3.Maps{
  666. StrToNested: map[string]*pb3.Nested{
  667. "nested": &pb3.Nested{
  668. SString: "nested in a map",
  669. },
  670. },
  671. },
  672. want: `{
  673. "strToNested": {
  674. "nested": {
  675. "sString": "nested in a map"
  676. }
  677. }
  678. }`,
  679. }, {
  680. desc: "map fields 5",
  681. input: &pb3.Maps{
  682. StrToOneofs: map[string]*pb3.Oneofs{
  683. "string": &pb3.Oneofs{
  684. Union: &pb3.Oneofs_OneofString{
  685. OneofString: "hello",
  686. },
  687. },
  688. "nested": &pb3.Oneofs{
  689. Union: &pb3.Oneofs_OneofNested{
  690. OneofNested: &pb3.Nested{
  691. SString: "nested oneof in map field value",
  692. },
  693. },
  694. },
  695. },
  696. },
  697. want: `{
  698. "strToOneofs": {
  699. "nested": {
  700. "oneofNested": {
  701. "sString": "nested oneof in map field value"
  702. }
  703. },
  704. "string": {
  705. "oneofString": "hello"
  706. }
  707. }
  708. }`,
  709. }, {
  710. desc: "map field contains nil value",
  711. input: &pb3.Maps{
  712. StrToNested: map[string]*pb3.Nested{
  713. "nil": nil,
  714. },
  715. },
  716. want: `{
  717. "strToNested": {
  718. "nil": {}
  719. }
  720. }`,
  721. }, {
  722. desc: "required fields not set",
  723. input: &pb2.Requireds{},
  724. want: `{}`,
  725. wantErr: true,
  726. }, {
  727. desc: "required fields partially set",
  728. input: &pb2.Requireds{
  729. ReqBool: proto.Bool(false),
  730. ReqSfixed64: proto.Int64(0),
  731. ReqDouble: proto.Float64(1.23),
  732. ReqString: proto.String("hello"),
  733. ReqEnum: pb2.Enum_ONE.Enum(),
  734. },
  735. want: `{
  736. "reqBool": false,
  737. "reqSfixed64": "0",
  738. "reqDouble": 1.23,
  739. "reqString": "hello",
  740. "reqEnum": "ONE"
  741. }`,
  742. wantErr: true,
  743. }, {
  744. desc: "required fields not set with AllowPartial",
  745. mo: protojson.MarshalOptions{AllowPartial: true},
  746. input: &pb2.Requireds{
  747. ReqBool: proto.Bool(false),
  748. ReqSfixed64: proto.Int64(0),
  749. ReqDouble: proto.Float64(1.23),
  750. ReqString: proto.String("hello"),
  751. ReqEnum: pb2.Enum_ONE.Enum(),
  752. },
  753. want: `{
  754. "reqBool": false,
  755. "reqSfixed64": "0",
  756. "reqDouble": 1.23,
  757. "reqString": "hello",
  758. "reqEnum": "ONE"
  759. }`,
  760. }, {
  761. desc: "required fields all set",
  762. input: &pb2.Requireds{
  763. ReqBool: proto.Bool(false),
  764. ReqSfixed64: proto.Int64(0),
  765. ReqDouble: proto.Float64(1.23),
  766. ReqString: proto.String("hello"),
  767. ReqEnum: pb2.Enum_ONE.Enum(),
  768. ReqNested: &pb2.Nested{},
  769. },
  770. want: `{
  771. "reqBool": false,
  772. "reqSfixed64": "0",
  773. "reqDouble": 1.23,
  774. "reqString": "hello",
  775. "reqEnum": "ONE",
  776. "reqNested": {}
  777. }`,
  778. }, {
  779. desc: "indirect required field",
  780. input: &pb2.IndirectRequired{
  781. OptNested: &pb2.NestedWithRequired{},
  782. },
  783. want: `{
  784. "optNested": {}
  785. }`,
  786. wantErr: true,
  787. }, {
  788. desc: "indirect required field with AllowPartial",
  789. mo: protojson.MarshalOptions{AllowPartial: true},
  790. input: &pb2.IndirectRequired{
  791. OptNested: &pb2.NestedWithRequired{},
  792. },
  793. want: `{
  794. "optNested": {}
  795. }`,
  796. }, {
  797. desc: "indirect required field in empty repeated",
  798. input: &pb2.IndirectRequired{
  799. RptNested: []*pb2.NestedWithRequired{},
  800. },
  801. want: `{}`,
  802. }, {
  803. desc: "indirect required field in repeated",
  804. input: &pb2.IndirectRequired{
  805. RptNested: []*pb2.NestedWithRequired{
  806. &pb2.NestedWithRequired{},
  807. },
  808. },
  809. want: `{
  810. "rptNested": [
  811. {}
  812. ]
  813. }`,
  814. wantErr: true,
  815. }, {
  816. desc: "indirect required field in repeated with AllowPartial",
  817. mo: protojson.MarshalOptions{AllowPartial: true},
  818. input: &pb2.IndirectRequired{
  819. RptNested: []*pb2.NestedWithRequired{
  820. &pb2.NestedWithRequired{},
  821. },
  822. },
  823. want: `{
  824. "rptNested": [
  825. {}
  826. ]
  827. }`,
  828. }, {
  829. desc: "indirect required field in empty map",
  830. input: &pb2.IndirectRequired{
  831. StrToNested: map[string]*pb2.NestedWithRequired{},
  832. },
  833. want: "{}",
  834. }, {
  835. desc: "indirect required field in map",
  836. input: &pb2.IndirectRequired{
  837. StrToNested: map[string]*pb2.NestedWithRequired{
  838. "fail": &pb2.NestedWithRequired{},
  839. },
  840. },
  841. want: `{
  842. "strToNested": {
  843. "fail": {}
  844. }
  845. }`,
  846. wantErr: true,
  847. }, {
  848. desc: "indirect required field in map with AllowPartial",
  849. mo: protojson.MarshalOptions{AllowPartial: true},
  850. input: &pb2.IndirectRequired{
  851. StrToNested: map[string]*pb2.NestedWithRequired{
  852. "fail": &pb2.NestedWithRequired{},
  853. },
  854. },
  855. want: `{
  856. "strToNested": {
  857. "fail": {}
  858. }
  859. }`,
  860. }, {
  861. desc: "indirect required field in oneof",
  862. input: &pb2.IndirectRequired{
  863. Union: &pb2.IndirectRequired_OneofNested{
  864. OneofNested: &pb2.NestedWithRequired{},
  865. },
  866. },
  867. want: `{
  868. "oneofNested": {}
  869. }`,
  870. wantErr: true,
  871. }, {
  872. desc: "indirect required field in oneof with AllowPartial",
  873. mo: protojson.MarshalOptions{AllowPartial: true},
  874. input: &pb2.IndirectRequired{
  875. Union: &pb2.IndirectRequired_OneofNested{
  876. OneofNested: &pb2.NestedWithRequired{},
  877. },
  878. },
  879. want: `{
  880. "oneofNested": {}
  881. }`,
  882. }, {
  883. desc: "unknown fields are ignored",
  884. input: func() proto.Message {
  885. m := &pb2.Scalars{
  886. OptString: proto.String("no unknowns"),
  887. }
  888. m.ProtoReflect().SetUnknown(protopack.Message{
  889. protopack.Tag{101, protopack.BytesType}, protopack.String("hello world"),
  890. }.Marshal())
  891. return m
  892. }(),
  893. want: `{
  894. "optString": "no unknowns"
  895. }`,
  896. }, {
  897. desc: "json_name",
  898. input: &pb3.JSONNames{
  899. SString: "json_name",
  900. },
  901. want: `{
  902. "foo_bar": "json_name"
  903. }`,
  904. }, {
  905. desc: "extensions of non-repeated fields",
  906. input: func() proto.Message {
  907. m := &pb2.Extensions{
  908. OptString: proto.String("non-extension field"),
  909. OptBool: proto.Bool(true),
  910. OptInt32: proto.Int32(42),
  911. }
  912. proto.SetExtension(m, pb2.E_OptExtBool, true)
  913. proto.SetExtension(m, pb2.E_OptExtString, "extension field")
  914. proto.SetExtension(m, pb2.E_OptExtEnum, pb2.Enum_TEN)
  915. proto.SetExtension(m, pb2.E_OptExtNested, &pb2.Nested{
  916. OptString: proto.String("nested in an extension"),
  917. OptNested: &pb2.Nested{
  918. OptString: proto.String("another nested in an extension"),
  919. },
  920. })
  921. return m
  922. }(),
  923. want: `{
  924. "optString": "non-extension field",
  925. "optBool": true,
  926. "optInt32": 42,
  927. "[pb2.opt_ext_bool]": true,
  928. "[pb2.opt_ext_enum]": "TEN",
  929. "[pb2.opt_ext_nested]": {
  930. "optString": "nested in an extension",
  931. "optNested": {
  932. "optString": "another nested in an extension"
  933. }
  934. },
  935. "[pb2.opt_ext_string]": "extension field"
  936. }`,
  937. }, {
  938. desc: "extensions of repeated fields",
  939. input: func() proto.Message {
  940. m := &pb2.Extensions{}
  941. proto.SetExtension(m, pb2.E_RptExtEnum, []pb2.Enum{pb2.Enum_TEN, 101, pb2.Enum_ONE})
  942. proto.SetExtension(m, pb2.E_RptExtFixed32, []uint32{42, 47})
  943. proto.SetExtension(m, pb2.E_RptExtNested, []*pb2.Nested{
  944. &pb2.Nested{OptString: proto.String("one")},
  945. &pb2.Nested{OptString: proto.String("two")},
  946. &pb2.Nested{OptString: proto.String("three")},
  947. })
  948. return m
  949. }(),
  950. want: `{
  951. "[pb2.rpt_ext_enum]": [
  952. "TEN",
  953. 101,
  954. "ONE"
  955. ],
  956. "[pb2.rpt_ext_fixed32]": [
  957. 42,
  958. 47
  959. ],
  960. "[pb2.rpt_ext_nested]": [
  961. {
  962. "optString": "one"
  963. },
  964. {
  965. "optString": "two"
  966. },
  967. {
  968. "optString": "three"
  969. }
  970. ]
  971. }`,
  972. }, {
  973. desc: "extensions of non-repeated fields in another message",
  974. input: func() proto.Message {
  975. m := &pb2.Extensions{}
  976. proto.SetExtension(m, pb2.E_ExtensionsContainer_OptExtBool, true)
  977. proto.SetExtension(m, pb2.E_ExtensionsContainer_OptExtString, "extension field")
  978. proto.SetExtension(m, pb2.E_ExtensionsContainer_OptExtEnum, pb2.Enum_TEN)
  979. proto.SetExtension(m, pb2.E_ExtensionsContainer_OptExtNested, &pb2.Nested{
  980. OptString: proto.String("nested in an extension"),
  981. OptNested: &pb2.Nested{
  982. OptString: proto.String("another nested in an extension"),
  983. },
  984. })
  985. return m
  986. }(),
  987. want: `{
  988. "[pb2.ExtensionsContainer.opt_ext_bool]": true,
  989. "[pb2.ExtensionsContainer.opt_ext_enum]": "TEN",
  990. "[pb2.ExtensionsContainer.opt_ext_nested]": {
  991. "optString": "nested in an extension",
  992. "optNested": {
  993. "optString": "another nested in an extension"
  994. }
  995. },
  996. "[pb2.ExtensionsContainer.opt_ext_string]": "extension field"
  997. }`,
  998. }, {
  999. desc: "extensions of repeated fields in another message",
  1000. input: func() proto.Message {
  1001. m := &pb2.Extensions{
  1002. OptString: proto.String("non-extension field"),
  1003. OptBool: proto.Bool(true),
  1004. OptInt32: proto.Int32(42),
  1005. }
  1006. proto.SetExtension(m, pb2.E_ExtensionsContainer_RptExtEnum, []pb2.Enum{pb2.Enum_TEN, 101, pb2.Enum_ONE})
  1007. proto.SetExtension(m, pb2.E_ExtensionsContainer_RptExtString, []string{"hello", "world"})
  1008. proto.SetExtension(m, pb2.E_ExtensionsContainer_RptExtNested, []*pb2.Nested{
  1009. &pb2.Nested{OptString: proto.String("one")},
  1010. &pb2.Nested{OptString: proto.String("two")},
  1011. &pb2.Nested{OptString: proto.String("three")},
  1012. })
  1013. return m
  1014. }(),
  1015. want: `{
  1016. "optString": "non-extension field",
  1017. "optBool": true,
  1018. "optInt32": 42,
  1019. "[pb2.ExtensionsContainer.rpt_ext_enum]": [
  1020. "TEN",
  1021. 101,
  1022. "ONE"
  1023. ],
  1024. "[pb2.ExtensionsContainer.rpt_ext_nested]": [
  1025. {
  1026. "optString": "one"
  1027. },
  1028. {
  1029. "optString": "two"
  1030. },
  1031. {
  1032. "optString": "three"
  1033. }
  1034. ],
  1035. "[pb2.ExtensionsContainer.rpt_ext_string]": [
  1036. "hello",
  1037. "world"
  1038. ]
  1039. }`,
  1040. }, {
  1041. desc: "MessageSet",
  1042. input: func() proto.Message {
  1043. m := &pb2.MessageSet{}
  1044. proto.SetExtension(m, pb2.E_MessageSetExtension_MessageSetExtension, &pb2.MessageSetExtension{
  1045. OptString: proto.String("a messageset extension"),
  1046. })
  1047. proto.SetExtension(m, pb2.E_MessageSetExtension_NotMessageSetExtension, &pb2.MessageSetExtension{
  1048. OptString: proto.String("not a messageset extension"),
  1049. })
  1050. proto.SetExtension(m, pb2.E_MessageSetExtension_ExtNested, &pb2.Nested{
  1051. OptString: proto.String("just a regular extension"),
  1052. })
  1053. return m
  1054. }(),
  1055. want: `{
  1056. "[pb2.MessageSetExtension.ext_nested]": {
  1057. "optString": "just a regular extension"
  1058. },
  1059. "[pb2.MessageSetExtension]": {
  1060. "optString": "a messageset extension"
  1061. },
  1062. "[pb2.MessageSetExtension.not_message_set_extension]": {
  1063. "optString": "not a messageset extension"
  1064. }
  1065. }`,
  1066. skip: !flags.ProtoLegacy,
  1067. }, {
  1068. desc: "not real MessageSet 1",
  1069. input: func() proto.Message {
  1070. m := &pb2.FakeMessageSet{}
  1071. proto.SetExtension(m, pb2.E_FakeMessageSetExtension_MessageSetExtension, &pb2.FakeMessageSetExtension{
  1072. OptString: proto.String("not a messageset extension"),
  1073. })
  1074. return m
  1075. }(),
  1076. want: `{
  1077. "[pb2.FakeMessageSetExtension.message_set_extension]": {
  1078. "optString": "not a messageset extension"
  1079. }
  1080. }`,
  1081. skip: !flags.ProtoLegacy,
  1082. }, {
  1083. desc: "not real MessageSet 2",
  1084. input: func() proto.Message {
  1085. m := &pb2.MessageSet{}
  1086. proto.SetExtension(m, pb2.E_MessageSetExtension, &pb2.FakeMessageSetExtension{
  1087. OptString: proto.String("another not a messageset extension"),
  1088. })
  1089. return m
  1090. }(),
  1091. want: `{
  1092. "[pb2.message_set_extension]": {
  1093. "optString": "another not a messageset extension"
  1094. }
  1095. }`,
  1096. skip: !flags.ProtoLegacy,
  1097. }, {
  1098. desc: "BoolValue empty",
  1099. input: &wrapperspb.BoolValue{},
  1100. want: `false`,
  1101. }, {
  1102. desc: "BoolValue",
  1103. input: &wrapperspb.BoolValue{Value: true},
  1104. want: `true`,
  1105. }, {
  1106. desc: "Int32Value empty",
  1107. input: &wrapperspb.Int32Value{},
  1108. want: `0`,
  1109. }, {
  1110. desc: "Int32Value",
  1111. input: &wrapperspb.Int32Value{Value: 42},
  1112. want: `42`,
  1113. }, {
  1114. desc: "Int64Value",
  1115. input: &wrapperspb.Int64Value{Value: 42},
  1116. want: `"42"`,
  1117. }, {
  1118. desc: "UInt32Value",
  1119. input: &wrapperspb.UInt32Value{Value: 42},
  1120. want: `42`,
  1121. }, {
  1122. desc: "UInt64Value",
  1123. input: &wrapperspb.UInt64Value{Value: 42},
  1124. want: `"42"`,
  1125. }, {
  1126. desc: "FloatValue",
  1127. input: &wrapperspb.FloatValue{Value: 1.02},
  1128. want: `1.02`,
  1129. }, {
  1130. desc: "FloatValue Infinity",
  1131. input: &wrapperspb.FloatValue{Value: float32(math.Inf(-1))},
  1132. want: `"-Infinity"`,
  1133. }, {
  1134. desc: "DoubleValue",
  1135. input: &wrapperspb.DoubleValue{Value: 1.02},
  1136. want: `1.02`,
  1137. }, {
  1138. desc: "DoubleValue NaN",
  1139. input: &wrapperspb.DoubleValue{Value: math.NaN()},
  1140. want: `"NaN"`,
  1141. }, {
  1142. desc: "StringValue empty",
  1143. input: &wrapperspb.StringValue{},
  1144. want: `""`,
  1145. }, {
  1146. desc: "StringValue",
  1147. input: &wrapperspb.StringValue{Value: "谷歌"},
  1148. want: `"谷歌"`,
  1149. }, {
  1150. desc: "StringValue with invalid UTF8 error",
  1151. input: &wrapperspb.StringValue{Value: "abc\xff"},
  1152. wantErr: true,
  1153. }, {
  1154. desc: "StringValue field with invalid UTF8 error",
  1155. input: &pb2.KnownTypes{
  1156. OptString: &wrapperspb.StringValue{Value: "abc\xff"},
  1157. },
  1158. wantErr: true,
  1159. }, {
  1160. desc: "BytesValue",
  1161. input: &wrapperspb.BytesValue{Value: []byte("hello")},
  1162. want: `"aGVsbG8="`,
  1163. }, {
  1164. desc: "Empty",
  1165. input: &emptypb.Empty{},
  1166. want: `{}`,
  1167. }, {
  1168. desc: "NullValue field",
  1169. input: &pb2.KnownTypes{OptNull: new(structpb.NullValue)},
  1170. want: `{
  1171. "optNull": null
  1172. }`,
  1173. }, {
  1174. desc: "Value empty",
  1175. input: &structpb.Value{},
  1176. wantErr: true,
  1177. }, {
  1178. desc: "Value empty field",
  1179. input: &pb2.KnownTypes{
  1180. OptValue: &structpb.Value{},
  1181. },
  1182. wantErr: true,
  1183. }, {
  1184. desc: "Value contains NullValue",
  1185. input: &structpb.Value{Kind: &structpb.Value_NullValue{}},
  1186. want: `null`,
  1187. }, {
  1188. desc: "Value contains BoolValue",
  1189. input: &structpb.Value{Kind: &structpb.Value_BoolValue{}},
  1190. want: `false`,
  1191. }, {
  1192. desc: "Value contains NumberValue",
  1193. input: &structpb.Value{Kind: &structpb.Value_NumberValue{1.02}},
  1194. want: `1.02`,
  1195. }, {
  1196. desc: "Value contains StringValue",
  1197. input: &structpb.Value{Kind: &structpb.Value_StringValue{"hello"}},
  1198. want: `"hello"`,
  1199. }, {
  1200. desc: "Value contains StringValue with invalid UTF8",
  1201. input: &structpb.Value{Kind: &structpb.Value_StringValue{"\xff"}},
  1202. wantErr: true,
  1203. }, {
  1204. desc: "Value contains Struct",
  1205. input: &structpb.Value{
  1206. Kind: &structpb.Value_StructValue{
  1207. &structpb.Struct{
  1208. Fields: map[string]*structpb.Value{
  1209. "null": {Kind: &structpb.Value_NullValue{}},
  1210. "number": {Kind: &structpb.Value_NumberValue{}},
  1211. "string": {Kind: &structpb.Value_StringValue{}},
  1212. "struct": {Kind: &structpb.Value_StructValue{}},
  1213. "list": {Kind: &structpb.Value_ListValue{}},
  1214. "bool": {Kind: &structpb.Value_BoolValue{}},
  1215. },
  1216. },
  1217. },
  1218. },
  1219. want: `{
  1220. "bool": false,
  1221. "list": [],
  1222. "null": null,
  1223. "number": 0,
  1224. "string": "",
  1225. "struct": {}
  1226. }`,
  1227. }, {
  1228. desc: "Value contains ListValue",
  1229. input: &structpb.Value{
  1230. Kind: &structpb.Value_ListValue{
  1231. &structpb.ListValue{
  1232. Values: []*structpb.Value{
  1233. {Kind: &structpb.Value_BoolValue{}},
  1234. {Kind: &structpb.Value_NullValue{}},
  1235. {Kind: &structpb.Value_NumberValue{}},
  1236. {Kind: &structpb.Value_StringValue{}},
  1237. {Kind: &structpb.Value_StructValue{}},
  1238. {Kind: &structpb.Value_ListValue{}},
  1239. },
  1240. },
  1241. },
  1242. },
  1243. want: `[
  1244. false,
  1245. null,
  1246. 0,
  1247. "",
  1248. {},
  1249. []
  1250. ]`,
  1251. }, {
  1252. desc: "Value with NaN",
  1253. input: structpb.NewNumberValue(math.NaN()),
  1254. wantErr: true,
  1255. }, {
  1256. desc: "Value with -Inf",
  1257. input: structpb.NewNumberValue(math.Inf(-1)),
  1258. wantErr: true,
  1259. }, {
  1260. desc: "Value with +Inf",
  1261. input: structpb.NewNumberValue(math.Inf(+1)),
  1262. wantErr: true,
  1263. }, {
  1264. desc: "Struct with nil map",
  1265. input: &structpb.Struct{},
  1266. want: `{}`,
  1267. }, {
  1268. desc: "Struct with empty map",
  1269. input: &structpb.Struct{
  1270. Fields: map[string]*structpb.Value{},
  1271. },
  1272. want: `{}`,
  1273. }, {
  1274. desc: "Struct",
  1275. input: &structpb.Struct{
  1276. Fields: map[string]*structpb.Value{
  1277. "bool": {Kind: &structpb.Value_BoolValue{true}},
  1278. "null": {Kind: &structpb.Value_NullValue{}},
  1279. "number": {Kind: &structpb.Value_NumberValue{3.1415}},
  1280. "string": {Kind: &structpb.Value_StringValue{"hello"}},
  1281. "struct": {
  1282. Kind: &structpb.Value_StructValue{
  1283. &structpb.Struct{
  1284. Fields: map[string]*structpb.Value{
  1285. "string": {Kind: &structpb.Value_StringValue{"world"}},
  1286. },
  1287. },
  1288. },
  1289. },
  1290. "list": {
  1291. Kind: &structpb.Value_ListValue{
  1292. &structpb.ListValue{
  1293. Values: []*structpb.Value{
  1294. {Kind: &structpb.Value_BoolValue{}},
  1295. {Kind: &structpb.Value_NullValue{}},
  1296. {Kind: &structpb.Value_NumberValue{}},
  1297. },
  1298. },
  1299. },
  1300. },
  1301. },
  1302. },
  1303. want: `{
  1304. "bool": true,
  1305. "list": [
  1306. false,
  1307. null,
  1308. 0
  1309. ],
  1310. "null": null,
  1311. "number": 3.1415,
  1312. "string": "hello",
  1313. "struct": {
  1314. "string": "world"
  1315. }
  1316. }`,
  1317. }, {
  1318. desc: "Struct message with invalid UTF8 string",
  1319. input: &structpb.Struct{
  1320. Fields: map[string]*structpb.Value{
  1321. "string": {Kind: &structpb.Value_StringValue{"\xff"}},
  1322. },
  1323. },
  1324. wantErr: true,
  1325. }, {
  1326. desc: "ListValue with nil values",
  1327. input: &structpb.ListValue{},
  1328. want: `[]`,
  1329. }, {
  1330. desc: "ListValue with empty values",
  1331. input: &structpb.ListValue{
  1332. Values: []*structpb.Value{},
  1333. },
  1334. want: `[]`,
  1335. }, {
  1336. desc: "ListValue",
  1337. input: &structpb.ListValue{
  1338. Values: []*structpb.Value{
  1339. {Kind: &structpb.Value_BoolValue{true}},
  1340. {Kind: &structpb.Value_NullValue{}},
  1341. {Kind: &structpb.Value_NumberValue{3.1415}},
  1342. {Kind: &structpb.Value_StringValue{"hello"}},
  1343. {
  1344. Kind: &structpb.Value_ListValue{
  1345. &structpb.ListValue{
  1346. Values: []*structpb.Value{
  1347. {Kind: &structpb.Value_BoolValue{}},
  1348. {Kind: &structpb.Value_NullValue{}},
  1349. {Kind: &structpb.Value_NumberValue{}},
  1350. },
  1351. },
  1352. },
  1353. },
  1354. {
  1355. Kind: &structpb.Value_StructValue{
  1356. &structpb.Struct{
  1357. Fields: map[string]*structpb.Value{
  1358. "string": {Kind: &structpb.Value_StringValue{"world"}},
  1359. },
  1360. },
  1361. },
  1362. },
  1363. },
  1364. },
  1365. want: `[
  1366. true,
  1367. null,
  1368. 3.1415,
  1369. "hello",
  1370. [
  1371. false,
  1372. null,
  1373. 0
  1374. ],
  1375. {
  1376. "string": "world"
  1377. }
  1378. ]`,
  1379. }, {
  1380. desc: "ListValue with invalid UTF8 string",
  1381. input: &structpb.ListValue{
  1382. Values: []*structpb.Value{
  1383. {Kind: &structpb.Value_StringValue{"\xff"}},
  1384. },
  1385. },
  1386. wantErr: true,
  1387. }, {
  1388. desc: "Duration empty",
  1389. input: &durationpb.Duration{},
  1390. want: `"0s"`,
  1391. }, {
  1392. desc: "Duration with secs",
  1393. input: &durationpb.Duration{Seconds: 3},
  1394. want: `"3s"`,
  1395. }, {
  1396. desc: "Duration with -secs",
  1397. input: &durationpb.Duration{Seconds: -3},
  1398. want: `"-3s"`,
  1399. }, {
  1400. desc: "Duration with nanos",
  1401. input: &durationpb.Duration{Nanos: 1e6},
  1402. want: `"0.001s"`,
  1403. }, {
  1404. desc: "Duration with -nanos",
  1405. input: &durationpb.Duration{Nanos: -1e6},
  1406. want: `"-0.001s"`,
  1407. }, {
  1408. desc: "Duration with large secs",
  1409. input: &durationpb.Duration{Seconds: 1e10, Nanos: 1},
  1410. want: `"10000000000.000000001s"`,
  1411. }, {
  1412. desc: "Duration with 6-digit nanos",
  1413. input: &durationpb.Duration{Nanos: 1e4},
  1414. want: `"0.000010s"`,
  1415. }, {
  1416. desc: "Duration with 3-digit nanos",
  1417. input: &durationpb.Duration{Nanos: 1e6},
  1418. want: `"0.001s"`,
  1419. }, {
  1420. desc: "Duration with -secs -nanos",
  1421. input: &durationpb.Duration{Seconds: -123, Nanos: -450},
  1422. want: `"-123.000000450s"`,
  1423. }, {
  1424. desc: "Duration max value",
  1425. input: &durationpb.Duration{Seconds: 315576000000, Nanos: 999999999},
  1426. want: `"315576000000.999999999s"`,
  1427. }, {
  1428. desc: "Duration min value",
  1429. input: &durationpb.Duration{Seconds: -315576000000, Nanos: -999999999},
  1430. want: `"-315576000000.999999999s"`,
  1431. }, {
  1432. desc: "Duration with +secs -nanos",
  1433. input: &durationpb.Duration{Seconds: 1, Nanos: -1},
  1434. wantErr: true,
  1435. }, {
  1436. desc: "Duration with -secs +nanos",
  1437. input: &durationpb.Duration{Seconds: -1, Nanos: 1},
  1438. wantErr: true,
  1439. }, {
  1440. desc: "Duration with +secs out of range",
  1441. input: &durationpb.Duration{Seconds: 315576000001},
  1442. wantErr: true,
  1443. }, {
  1444. desc: "Duration with -secs out of range",
  1445. input: &durationpb.Duration{Seconds: -315576000001},
  1446. wantErr: true,
  1447. }, {
  1448. desc: "Duration with +nanos out of range",
  1449. input: &durationpb.Duration{Seconds: 0, Nanos: 1e9},
  1450. wantErr: true,
  1451. }, {
  1452. desc: "Duration with -nanos out of range",
  1453. input: &durationpb.Duration{Seconds: 0, Nanos: -1e9},
  1454. wantErr: true,
  1455. }, {
  1456. desc: "Timestamp zero",
  1457. input: &timestamppb.Timestamp{},
  1458. want: `"1970-01-01T00:00:00Z"`,
  1459. }, {
  1460. desc: "Timestamp",
  1461. input: &timestamppb.Timestamp{Seconds: 1553036601},
  1462. want: `"2019-03-19T23:03:21Z"`,
  1463. }, {
  1464. desc: "Timestamp with nanos",
  1465. input: &timestamppb.Timestamp{Seconds: 1553036601, Nanos: 1},
  1466. want: `"2019-03-19T23:03:21.000000001Z"`,
  1467. }, {
  1468. desc: "Timestamp with 6-digit nanos",
  1469. input: &timestamppb.Timestamp{Nanos: 1e3},
  1470. want: `"1970-01-01T00:00:00.000001Z"`,
  1471. }, {
  1472. desc: "Timestamp with 3-digit nanos",
  1473. input: &timestamppb.Timestamp{Nanos: 1e7},
  1474. want: `"1970-01-01T00:00:00.010Z"`,
  1475. }, {
  1476. desc: "Timestamp max value",
  1477. input: &timestamppb.Timestamp{Seconds: 253402300799, Nanos: 999999999},
  1478. want: `"9999-12-31T23:59:59.999999999Z"`,
  1479. }, {
  1480. desc: "Timestamp min value",
  1481. input: &timestamppb.Timestamp{Seconds: -62135596800},
  1482. want: `"0001-01-01T00:00:00Z"`,
  1483. }, {
  1484. desc: "Timestamp with +secs out of range",
  1485. input: &timestamppb.Timestamp{Seconds: 253402300800},
  1486. wantErr: true,
  1487. }, {
  1488. desc: "Timestamp with -secs out of range",
  1489. input: &timestamppb.Timestamp{Seconds: -62135596801},
  1490. wantErr: true,
  1491. }, {
  1492. desc: "Timestamp with -nanos",
  1493. input: &timestamppb.Timestamp{Nanos: -1},
  1494. wantErr: true,
  1495. }, {
  1496. desc: "Timestamp with +nanos out of range",
  1497. input: &timestamppb.Timestamp{Nanos: 1e9},
  1498. wantErr: true,
  1499. }, {
  1500. desc: "FieldMask empty",
  1501. input: &fieldmaskpb.FieldMask{},
  1502. want: `""`,
  1503. }, {
  1504. desc: "FieldMask",
  1505. input: &fieldmaskpb.FieldMask{
  1506. Paths: []string{
  1507. "foo",
  1508. "foo_bar",
  1509. "foo.bar_qux",
  1510. "_foo",
  1511. },
  1512. },
  1513. want: `"foo,fooBar,foo.barQux,Foo"`,
  1514. }, {
  1515. desc: "FieldMask empty string path",
  1516. input: &fieldmaskpb.FieldMask{
  1517. Paths: []string{""},
  1518. },
  1519. wantErr: true,
  1520. }, {
  1521. desc: "FieldMask path contains spaces only",
  1522. input: &fieldmaskpb.FieldMask{
  1523. Paths: []string{" "},
  1524. },
  1525. wantErr: true,
  1526. }, {
  1527. desc: "FieldMask irreversible error 1",
  1528. input: &fieldmaskpb.FieldMask{
  1529. Paths: []string{"foo_"},
  1530. },
  1531. wantErr: true,
  1532. }, {
  1533. desc: "FieldMask irreversible error 2",
  1534. input: &fieldmaskpb.FieldMask{
  1535. Paths: []string{"foo__bar"},
  1536. },
  1537. wantErr: true,
  1538. }, {
  1539. desc: "FieldMask invalid char",
  1540. input: &fieldmaskpb.FieldMask{
  1541. Paths: []string{"foo@bar"},
  1542. },
  1543. wantErr: true,
  1544. }, {
  1545. desc: "Any empty",
  1546. input: &anypb.Any{},
  1547. want: `{}`,
  1548. }, {
  1549. desc: "Any with non-custom message",
  1550. input: func() proto.Message {
  1551. m := &pb2.Nested{
  1552. OptString: proto.String("embedded inside Any"),
  1553. OptNested: &pb2.Nested{
  1554. OptString: proto.String("inception"),
  1555. },
  1556. }
  1557. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1558. if err != nil {
  1559. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1560. }
  1561. return &anypb.Any{
  1562. TypeUrl: "foo/pb2.Nested",
  1563. Value: b,
  1564. }
  1565. }(),
  1566. want: `{
  1567. "@type": "foo/pb2.Nested",
  1568. "optString": "embedded inside Any",
  1569. "optNested": {
  1570. "optString": "inception"
  1571. }
  1572. }`,
  1573. }, {
  1574. desc: "Any with empty embedded message",
  1575. input: &anypb.Any{TypeUrl: "foo/pb2.Nested"},
  1576. want: `{
  1577. "@type": "foo/pb2.Nested"
  1578. }`,
  1579. }, {
  1580. desc: "Any without registered type",
  1581. mo: protojson.MarshalOptions{Resolver: new(protoregistry.Types)},
  1582. input: &anypb.Any{TypeUrl: "foo/pb2.Nested"},
  1583. wantErr: true,
  1584. }, {
  1585. desc: "Any with missing required",
  1586. input: func() proto.Message {
  1587. m := &pb2.PartialRequired{
  1588. OptString: proto.String("embedded inside Any"),
  1589. }
  1590. b, err := proto.MarshalOptions{
  1591. AllowPartial: true,
  1592. Deterministic: true,
  1593. }.Marshal(m)
  1594. if err != nil {
  1595. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1596. }
  1597. return &anypb.Any{
  1598. TypeUrl: string(m.ProtoReflect().Descriptor().FullName()),
  1599. Value: b,
  1600. }
  1601. }(),
  1602. want: `{
  1603. "@type": "pb2.PartialRequired",
  1604. "optString": "embedded inside Any"
  1605. }`,
  1606. }, {
  1607. desc: "Any with partial required and AllowPartial",
  1608. mo: protojson.MarshalOptions{
  1609. AllowPartial: true,
  1610. },
  1611. input: func() proto.Message {
  1612. m := &pb2.PartialRequired{
  1613. OptString: proto.String("embedded inside Any"),
  1614. }
  1615. b, err := proto.MarshalOptions{
  1616. AllowPartial: true,
  1617. Deterministic: true,
  1618. }.Marshal(m)
  1619. if err != nil {
  1620. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1621. }
  1622. return &anypb.Any{
  1623. TypeUrl: string(m.ProtoReflect().Descriptor().FullName()),
  1624. Value: b,
  1625. }
  1626. }(),
  1627. want: `{
  1628. "@type": "pb2.PartialRequired",
  1629. "optString": "embedded inside Any"
  1630. }`,
  1631. }, {
  1632. desc: "Any with EmitUnpopulated",
  1633. mo: protojson.MarshalOptions{
  1634. EmitUnpopulated: true,
  1635. },
  1636. input: func() proto.Message {
  1637. return &anypb.Any{
  1638. TypeUrl: string(new(pb3.Scalars).ProtoReflect().Descriptor().FullName()),
  1639. }
  1640. }(),
  1641. want: `{
  1642. "@type": "pb3.Scalars",
  1643. "sBool": false,
  1644. "sInt32": 0,
  1645. "sInt64": "0",
  1646. "sUint32": 0,
  1647. "sUint64": "0",
  1648. "sSint32": 0,
  1649. "sSint64": "0",
  1650. "sFixed32": 0,
  1651. "sFixed64": "0",
  1652. "sSfixed32": 0,
  1653. "sSfixed64": "0",
  1654. "sFloat": 0,
  1655. "sDouble": 0,
  1656. "sBytes": "",
  1657. "sString": ""
  1658. }`,
  1659. }, {
  1660. desc: "Any with invalid UTF8",
  1661. input: func() proto.Message {
  1662. m := &pb2.Nested{
  1663. OptString: proto.String("abc\xff"),
  1664. }
  1665. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1666. if err != nil {
  1667. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1668. }
  1669. return &anypb.Any{
  1670. TypeUrl: "foo/pb2.Nested",
  1671. Value: b,
  1672. }
  1673. }(),
  1674. wantErr: true,
  1675. }, {
  1676. desc: "Any with invalid value",
  1677. input: &anypb.Any{
  1678. TypeUrl: "foo/pb2.Nested",
  1679. Value: []byte("\x80"),
  1680. },
  1681. wantErr: true,
  1682. }, {
  1683. desc: "Any with BoolValue",
  1684. input: func() proto.Message {
  1685. m := &wrapperspb.BoolValue{Value: true}
  1686. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1687. if err != nil {
  1688. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1689. }
  1690. return &anypb.Any{
  1691. TypeUrl: "type.googleapis.com/google.protobuf.BoolValue",
  1692. Value: b,
  1693. }
  1694. }(),
  1695. want: `{
  1696. "@type": "type.googleapis.com/google.protobuf.BoolValue",
  1697. "value": true
  1698. }`,
  1699. }, {
  1700. desc: "Any with Empty",
  1701. input: func() proto.Message {
  1702. m := &emptypb.Empty{}
  1703. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1704. if err != nil {
  1705. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1706. }
  1707. return &anypb.Any{
  1708. TypeUrl: "type.googleapis.com/google.protobuf.Empty",
  1709. Value: b,
  1710. }
  1711. }(),
  1712. want: `{
  1713. "@type": "type.googleapis.com/google.protobuf.Empty",
  1714. "value": {}
  1715. }`,
  1716. }, {
  1717. desc: "Any with StringValue containing invalid UTF8",
  1718. input: func() proto.Message {
  1719. m := &wrapperspb.StringValue{Value: "abcd"}
  1720. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1721. if err != nil {
  1722. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1723. }
  1724. return &anypb.Any{
  1725. TypeUrl: "google.protobuf.StringValue",
  1726. Value: bytes.Replace(b, []byte("abcd"), []byte("abc\xff"), -1),
  1727. }
  1728. }(),
  1729. wantErr: true,
  1730. }, {
  1731. desc: "Any with Int64Value",
  1732. input: func() proto.Message {
  1733. m := &wrapperspb.Int64Value{Value: 42}
  1734. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1735. if err != nil {
  1736. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1737. }
  1738. return &anypb.Any{
  1739. TypeUrl: "google.protobuf.Int64Value",
  1740. Value: b,
  1741. }
  1742. }(),
  1743. want: `{
  1744. "@type": "google.protobuf.Int64Value",
  1745. "value": "42"
  1746. }`,
  1747. }, {
  1748. desc: "Any with Duration",
  1749. input: func() proto.Message {
  1750. m := &durationpb.Duration{}
  1751. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1752. if err != nil {
  1753. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1754. }
  1755. return &anypb.Any{
  1756. TypeUrl: "type.googleapis.com/google.protobuf.Duration",
  1757. Value: b,
  1758. }
  1759. }(),
  1760. want: `{
  1761. "@type": "type.googleapis.com/google.protobuf.Duration",
  1762. "value": "0s"
  1763. }`,
  1764. }, {
  1765. desc: "Any with empty Value",
  1766. input: func() proto.Message {
  1767. m := &structpb.Value{}
  1768. b, err := proto.Marshal(m)
  1769. if err != nil {
  1770. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1771. }
  1772. return &anypb.Any{
  1773. TypeUrl: "type.googleapis.com/google.protobuf.Value",
  1774. Value: b,
  1775. }
  1776. }(),
  1777. wantErr: true,
  1778. }, {
  1779. desc: "Any with Value of StringValue",
  1780. input: func() proto.Message {
  1781. m := &structpb.Value{Kind: &structpb.Value_StringValue{"abcd"}}
  1782. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1783. if err != nil {
  1784. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1785. }
  1786. return &anypb.Any{
  1787. TypeUrl: "type.googleapis.com/google.protobuf.Value",
  1788. Value: bytes.Replace(b, []byte("abcd"), []byte("abc\xff"), -1),
  1789. }
  1790. }(),
  1791. wantErr: true,
  1792. }, {
  1793. desc: "Any with Value of NullValue",
  1794. input: func() proto.Message {
  1795. m := &structpb.Value{Kind: &structpb.Value_NullValue{}}
  1796. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1797. if err != nil {
  1798. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1799. }
  1800. return &anypb.Any{
  1801. TypeUrl: "type.googleapis.com/google.protobuf.Value",
  1802. Value: b,
  1803. }
  1804. }(),
  1805. want: `{
  1806. "@type": "type.googleapis.com/google.protobuf.Value",
  1807. "value": null
  1808. }`,
  1809. }, {
  1810. desc: "Any with Struct",
  1811. input: func() proto.Message {
  1812. m := &structpb.Struct{
  1813. Fields: map[string]*structpb.Value{
  1814. "bool": {Kind: &structpb.Value_BoolValue{true}},
  1815. "null": {Kind: &structpb.Value_NullValue{}},
  1816. "string": {Kind: &structpb.Value_StringValue{"hello"}},
  1817. "struct": {
  1818. Kind: &structpb.Value_StructValue{
  1819. &structpb.Struct{
  1820. Fields: map[string]*structpb.Value{
  1821. "string": {Kind: &structpb.Value_StringValue{"world"}},
  1822. },
  1823. },
  1824. },
  1825. },
  1826. },
  1827. }
  1828. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1829. if err != nil {
  1830. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1831. }
  1832. return &anypb.Any{
  1833. TypeUrl: "google.protobuf.Struct",
  1834. Value: b,
  1835. }
  1836. }(),
  1837. want: `{
  1838. "@type": "google.protobuf.Struct",
  1839. "value": {
  1840. "bool": true,
  1841. "null": null,
  1842. "string": "hello",
  1843. "struct": {
  1844. "string": "world"
  1845. }
  1846. }
  1847. }`,
  1848. }, {
  1849. desc: "Any with missing type_url",
  1850. input: func() proto.Message {
  1851. m := &wrapperspb.BoolValue{Value: true}
  1852. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  1853. if err != nil {
  1854. t.Fatalf("error in binary marshaling message for Any.value: %v", err)
  1855. }
  1856. return &anypb.Any{
  1857. Value: b,
  1858. }
  1859. }(),
  1860. wantErr: true,
  1861. }, {
  1862. desc: "well known types as field values",
  1863. input: &pb2.KnownTypes{
  1864. OptBool: &wrapperspb.BoolValue{Value: false},
  1865. OptInt32: &wrapperspb.Int32Value{Value: 42},
  1866. OptInt64: &wrapperspb.Int64Value{Value: 42},
  1867. OptUint32: &wrapperspb.UInt32Value{Value: 42},
  1868. OptUint64: &wrapperspb.UInt64Value{Value: 42},
  1869. OptFloat: &wrapperspb.FloatValue{Value: 1.23},
  1870. OptDouble: &wrapperspb.DoubleValue{Value: 3.1415},
  1871. OptString: &wrapperspb.StringValue{Value: "hello"},
  1872. OptBytes: &wrapperspb.BytesValue{Value: []byte("hello")},
  1873. OptDuration: &durationpb.Duration{Seconds: 123},
  1874. OptTimestamp: &timestamppb.Timestamp{Seconds: 1553036601},
  1875. OptStruct: &structpb.Struct{
  1876. Fields: map[string]*structpb.Value{
  1877. "string": {Kind: &structpb.Value_StringValue{"hello"}},
  1878. },
  1879. },
  1880. OptList: &structpb.ListValue{
  1881. Values: []*structpb.Value{
  1882. {Kind: &structpb.Value_NullValue{}},
  1883. {Kind: &structpb.Value_StringValue{}},
  1884. {Kind: &structpb.Value_StructValue{}},
  1885. {Kind: &structpb.Value_ListValue{}},
  1886. },
  1887. },
  1888. OptValue: &structpb.Value{
  1889. Kind: &structpb.Value_StringValue{"world"},
  1890. },
  1891. OptEmpty: &emptypb.Empty{},
  1892. OptAny: &anypb.Any{
  1893. TypeUrl: "google.protobuf.Empty",
  1894. },
  1895. OptFieldmask: &fieldmaskpb.FieldMask{
  1896. Paths: []string{"foo_bar", "bar_foo"},
  1897. },
  1898. },
  1899. want: `{
  1900. "optBool": false,
  1901. "optInt32": 42,
  1902. "optInt64": "42",
  1903. "optUint32": 42,
  1904. "optUint64": "42",
  1905. "optFloat": 1.23,
  1906. "optDouble": 3.1415,
  1907. "optString": "hello",
  1908. "optBytes": "aGVsbG8=",
  1909. "optDuration": "123s",
  1910. "optTimestamp": "2019-03-19T23:03:21Z",
  1911. "optStruct": {
  1912. "string": "hello"
  1913. },
  1914. "optList": [
  1915. null,
  1916. "",
  1917. {},
  1918. []
  1919. ],
  1920. "optValue": "world",
  1921. "optEmpty": {},
  1922. "optAny": {
  1923. "@type": "google.protobuf.Empty",
  1924. "value": {}
  1925. },
  1926. "optFieldmask": "fooBar,barFoo"
  1927. }`,
  1928. }, {
  1929. desc: "EmitUnpopulated: proto2 optional scalars",
  1930. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  1931. input: &pb2.Scalars{},
  1932. want: `{
  1933. "optBool": null,
  1934. "optInt32": null,
  1935. "optInt64": null,
  1936. "optUint32": null,
  1937. "optUint64": null,
  1938. "optSint32": null,
  1939. "optSint64": null,
  1940. "optFixed32": null,
  1941. "optFixed64": null,
  1942. "optSfixed32": null,
  1943. "optSfixed64": null,
  1944. "optFloat": null,
  1945. "optDouble": null,
  1946. "optBytes": null,
  1947. "optString": null
  1948. }`,
  1949. }, {
  1950. desc: "EmitUnpopulated: proto3 scalars",
  1951. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  1952. input: &pb3.Scalars{},
  1953. want: `{
  1954. "sBool": false,
  1955. "sInt32": 0,
  1956. "sInt64": "0",
  1957. "sUint32": 0,
  1958. "sUint64": "0",
  1959. "sSint32": 0,
  1960. "sSint64": "0",
  1961. "sFixed32": 0,
  1962. "sFixed64": "0",
  1963. "sSfixed32": 0,
  1964. "sSfixed64": "0",
  1965. "sFloat": 0,
  1966. "sDouble": 0,
  1967. "sBytes": "",
  1968. "sString": ""
  1969. }`,
  1970. }, {
  1971. desc: "EmitUnpopulated: proto2 enum",
  1972. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  1973. input: &pb2.Enums{},
  1974. want: `{
  1975. "optEnum": null,
  1976. "rptEnum": [],
  1977. "optNestedEnum": null,
  1978. "rptNestedEnum": []
  1979. }`,
  1980. }, {
  1981. desc: "EmitUnpopulated: proto3 enum",
  1982. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  1983. input: &pb3.Enums{},
  1984. want: `{
  1985. "sEnum": "ZERO",
  1986. "sNestedEnum": "CERO"
  1987. }`,
  1988. }, {
  1989. desc: "EmitUnpopulated: proto2 message and group fields",
  1990. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  1991. input: &pb2.Nests{},
  1992. want: `{
  1993. "optNested": null,
  1994. "optgroup": null,
  1995. "rptNested": [],
  1996. "rptgroup": []
  1997. }`,
  1998. }, {
  1999. desc: "EmitUnpopulated: proto3 message field",
  2000. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2001. input: &pb3.Nests{},
  2002. want: `{
  2003. "sNested": null
  2004. }`,
  2005. }, {
  2006. desc: "EmitUnpopulated: proto2 empty message and group fields",
  2007. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2008. input: &pb2.Nests{
  2009. OptNested: &pb2.Nested{},
  2010. Optgroup: &pb2.Nests_OptGroup{},
  2011. },
  2012. want: `{
  2013. "optNested": {
  2014. "optString": null,
  2015. "optNested": null
  2016. },
  2017. "optgroup": {
  2018. "optString": null,
  2019. "optNested": null,
  2020. "optnestedgroup": null
  2021. },
  2022. "rptNested": [],
  2023. "rptgroup": []
  2024. }`,
  2025. }, {
  2026. desc: "EmitUnpopulated: proto3 empty message field",
  2027. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2028. input: &pb3.Nests{
  2029. SNested: &pb3.Nested{},
  2030. },
  2031. want: `{
  2032. "sNested": {
  2033. "sString": "",
  2034. "sNested": null
  2035. }
  2036. }`,
  2037. }, {
  2038. desc: "EmitUnpopulated: proto2 required fields",
  2039. mo: protojson.MarshalOptions{
  2040. AllowPartial: true,
  2041. EmitUnpopulated: true,
  2042. },
  2043. input: &pb2.Requireds{},
  2044. want: `{
  2045. "reqBool": null,
  2046. "reqSfixed64": null,
  2047. "reqDouble": null,
  2048. "reqString": null,
  2049. "reqEnum": null,
  2050. "reqNested": null
  2051. }`,
  2052. }, {
  2053. desc: "EmitUnpopulated: repeated fields",
  2054. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2055. input: &pb2.Repeats{},
  2056. want: `{
  2057. "rptBool": [],
  2058. "rptInt32": [],
  2059. "rptInt64": [],
  2060. "rptUint32": [],
  2061. "rptUint64": [],
  2062. "rptFloat": [],
  2063. "rptDouble": [],
  2064. "rptString": [],
  2065. "rptBytes": []
  2066. }`,
  2067. }, {
  2068. desc: "EmitUnpopulated: repeated containing empty message",
  2069. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2070. input: &pb2.Nests{
  2071. RptNested: []*pb2.Nested{nil, {}},
  2072. },
  2073. want: `{
  2074. "optNested": null,
  2075. "optgroup": null,
  2076. "rptNested": [
  2077. {
  2078. "optString": null,
  2079. "optNested": null
  2080. },
  2081. {
  2082. "optString": null,
  2083. "optNested": null
  2084. }
  2085. ],
  2086. "rptgroup": []
  2087. }`,
  2088. }, {
  2089. desc: "EmitUnpopulated: map fields",
  2090. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2091. input: &pb3.Maps{},
  2092. want: `{
  2093. "int32ToStr": {},
  2094. "boolToUint32": {},
  2095. "uint64ToEnum": {},
  2096. "strToNested": {},
  2097. "strToOneofs": {}
  2098. }`,
  2099. }, {
  2100. desc: "EmitUnpopulated: map containing empty message",
  2101. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2102. input: &pb3.Maps{
  2103. StrToNested: map[string]*pb3.Nested{
  2104. "nested": &pb3.Nested{},
  2105. },
  2106. StrToOneofs: map[string]*pb3.Oneofs{
  2107. "nested": &pb3.Oneofs{},
  2108. },
  2109. },
  2110. want: `{
  2111. "int32ToStr": {},
  2112. "boolToUint32": {},
  2113. "uint64ToEnum": {},
  2114. "strToNested": {
  2115. "nested": {
  2116. "sString": "",
  2117. "sNested": null
  2118. }
  2119. },
  2120. "strToOneofs": {
  2121. "nested": {}
  2122. }
  2123. }`,
  2124. }, {
  2125. desc: "EmitUnpopulated: oneof fields",
  2126. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2127. input: &pb3.Oneofs{},
  2128. want: `{}`,
  2129. }, {
  2130. desc: "EmitUnpopulated: extensions",
  2131. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2132. input: func() proto.Message {
  2133. m := &pb2.Extensions{}
  2134. proto.SetExtension(m, pb2.E_OptExtNested, &pb2.Nested{})
  2135. proto.SetExtension(m, pb2.E_RptExtNested, []*pb2.Nested{
  2136. nil,
  2137. {},
  2138. })
  2139. return m
  2140. }(),
  2141. want: `{
  2142. "optString": null,
  2143. "optBool": null,
  2144. "optInt32": null,
  2145. "[pb2.opt_ext_nested]": {
  2146. "optString": null,
  2147. "optNested": null
  2148. },
  2149. "[pb2.rpt_ext_nested]": [
  2150. {
  2151. "optString": null,
  2152. "optNested": null
  2153. },
  2154. {
  2155. "optString": null,
  2156. "optNested": null
  2157. }
  2158. ]
  2159. }`,
  2160. }, {
  2161. desc: "EmitUnpopulated: with populated fields",
  2162. mo: protojson.MarshalOptions{EmitUnpopulated: true},
  2163. input: &pb2.Scalars{
  2164. OptInt32: proto.Int32(0xff),
  2165. OptUint32: proto.Uint32(47),
  2166. OptSint32: proto.Int32(-1001),
  2167. OptFixed32: proto.Uint32(32),
  2168. OptSfixed32: proto.Int32(-32),
  2169. OptFloat: proto.Float32(1.02),
  2170. OptBytes: []byte("谷歌"),
  2171. },
  2172. want: `{
  2173. "optBool": null,
  2174. "optInt32": 255,
  2175. "optInt64": null,
  2176. "optUint32": 47,
  2177. "optUint64": null,
  2178. "optSint32": -1001,
  2179. "optSint64": null,
  2180. "optFixed32": 32,
  2181. "optFixed64": null,
  2182. "optSfixed32": -32,
  2183. "optSfixed64": null,
  2184. "optFloat": 1.02,
  2185. "optDouble": null,
  2186. "optBytes": "6LC35q2M",
  2187. "optString": null
  2188. }`,
  2189. }, {
  2190. desc: "UseEnumNumbers in singular field",
  2191. mo: protojson.MarshalOptions{UseEnumNumbers: true},
  2192. input: &pb2.Enums{
  2193. OptEnum: pb2.Enum_ONE.Enum(),
  2194. OptNestedEnum: pb2.Enums_UNO.Enum(),
  2195. },
  2196. want: `{
  2197. "optEnum": 1,
  2198. "optNestedEnum": 1
  2199. }`,
  2200. }, {
  2201. desc: "UseEnumNumbers in repeated field",
  2202. mo: protojson.MarshalOptions{UseEnumNumbers: true},
  2203. input: &pb2.Enums{
  2204. RptEnum: []pb2.Enum{pb2.Enum_ONE, 2, pb2.Enum_TEN, 42},
  2205. RptNestedEnum: []pb2.Enums_NestedEnum{pb2.Enums_UNO, pb2.Enums_DOS, 47},
  2206. },
  2207. want: `{
  2208. "rptEnum": [
  2209. 1,
  2210. 2,
  2211. 10,
  2212. 42
  2213. ],
  2214. "rptNestedEnum": [
  2215. 1,
  2216. 2,
  2217. 47
  2218. ]
  2219. }`,
  2220. }, {
  2221. desc: "UseEnumNumbers in map field",
  2222. mo: protojson.MarshalOptions{UseEnumNumbers: true},
  2223. input: &pb3.Maps{
  2224. Uint64ToEnum: map[uint64]pb3.Enum{
  2225. 1: pb3.Enum_ONE,
  2226. 2: pb3.Enum_TWO,
  2227. 10: pb3.Enum_TEN,
  2228. 47: 47,
  2229. },
  2230. },
  2231. want: `{
  2232. "uint64ToEnum": {
  2233. "1": 1,
  2234. "2": 2,
  2235. "10": 10,
  2236. "47": 47
  2237. }
  2238. }`,
  2239. }, {
  2240. desc: "UseProtoNames",
  2241. mo: protojson.MarshalOptions{UseProtoNames: true},
  2242. input: &pb2.Nests{
  2243. OptNested: &pb2.Nested{},
  2244. Optgroup: &pb2.Nests_OptGroup{
  2245. OptString: proto.String("inside a group"),
  2246. OptNested: &pb2.Nested{
  2247. OptString: proto.String("nested message inside a group"),
  2248. },
  2249. Optnestedgroup: &pb2.Nests_OptGroup_OptNestedGroup{
  2250. OptFixed32: proto.Uint32(47),
  2251. },
  2252. },
  2253. Rptgroup: []*pb2.Nests_RptGroup{
  2254. {
  2255. RptString: []string{"hello", "world"},
  2256. },
  2257. },
  2258. },
  2259. want: `{
  2260. "opt_nested": {},
  2261. "OptGroup": {
  2262. "opt_string": "inside a group",
  2263. "opt_nested": {
  2264. "opt_string": "nested message inside a group"
  2265. },
  2266. "OptNestedGroup": {
  2267. "opt_fixed32": 47
  2268. }
  2269. },
  2270. "RptGroup": [
  2271. {
  2272. "rpt_string": [
  2273. "hello",
  2274. "world"
  2275. ]
  2276. }
  2277. ]
  2278. }`,
  2279. }}
  2280. for _, tt := range tests {
  2281. tt := tt
  2282. if tt.skip {
  2283. continue
  2284. }
  2285. t.Run(tt.desc, func(t *testing.T) {
  2286. // Use 2-space indentation on all MarshalOptions.
  2287. tt.mo.Indent = " "
  2288. b, err := tt.mo.Marshal(tt.input)
  2289. if err != nil && !tt.wantErr {
  2290. t.Errorf("Marshal() returned error: %v\n", err)
  2291. }
  2292. if err == nil && tt.wantErr {
  2293. t.Errorf("Marshal() got nil error, want error\n")
  2294. }
  2295. got := string(b)
  2296. if got != tt.want {
  2297. t.Errorf("Marshal()\n<got>\n%v\n<want>\n%v\n", got, tt.want)
  2298. if diff := cmp.Diff(tt.want, got); diff != "" {
  2299. t.Errorf("Marshal() diff -want +got\n%v\n", diff)
  2300. }
  2301. }
  2302. })
  2303. }
  2304. }
  2305. func TestEncodeAppend(t *testing.T) {
  2306. want := []byte("prefix")
  2307. got := append([]byte(nil), want...)
  2308. got, err := protojson.MarshalOptions{}.MarshalAppend(got, &pb3.Scalars{
  2309. SString: "value",
  2310. })
  2311. if err != nil {
  2312. t.Fatal(err)
  2313. }
  2314. if !bytes.HasPrefix(got, want) {
  2315. t.Fatalf("MarshalAppend modified prefix: got %v, want prefix %v", got, want)
  2316. }
  2317. }
  2318. func TestMarshalAppendAllocations(t *testing.T) {
  2319. m := &pb3.Scalars{SInt32: 1}
  2320. const count = 1000
  2321. size := 12
  2322. b := make([]byte, size)
  2323. // AllocsPerRun returns an integral value.
  2324. marshalAllocs := testing.AllocsPerRun(count, func() {
  2325. _, err := protojson.MarshalOptions{}.MarshalAppend(b[:0], m)
  2326. if err != nil {
  2327. t.Fatal(err)
  2328. }
  2329. })
  2330. b = nil
  2331. marshalAppendAllocs := testing.AllocsPerRun(count, func() {
  2332. var err error
  2333. b, err = protojson.MarshalOptions{}.MarshalAppend(b, m)
  2334. if err != nil {
  2335. t.Fatal(err)
  2336. }
  2337. })
  2338. if marshalAllocs != marshalAppendAllocs {
  2339. t.Errorf("%v allocs/op when writing to a preallocated buffer", marshalAllocs)
  2340. t.Errorf("%v allocs/op when repeatedly appending to a slice", marshalAppendAllocs)
  2341. t.Errorf("expect amortized allocs/op to be identical")
  2342. }
  2343. }