binary_json_conformance_suite.cc 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #include "binary_json_conformance_suite.h"
  31. #include "conformance_test.h"
  32. #include "third_party/jsoncpp/json.h"
  33. #include <google/protobuf/test_messages_proto3.pb.h>
  34. #include <google/protobuf/test_messages_proto2.pb.h>
  35. #include <google/protobuf/stubs/common.h>
  36. #include <google/protobuf/stubs/strutil.h>
  37. #include <google/protobuf/text_format.h>
  38. #include <google/protobuf/util/json_util.h>
  39. #include <google/protobuf/util/type_resolver_util.h>
  40. #include <google/protobuf/wire_format_lite.h>
  41. using conformance::ConformanceRequest;
  42. using conformance::ConformanceResponse;
  43. using conformance::WireFormat;
  44. using google::protobuf::Descriptor;
  45. using google::protobuf::FieldDescriptor;
  46. using google::protobuf::Message;
  47. using google::protobuf::internal::WireFormatLite;
  48. using google::protobuf::TextFormat;
  49. using google::protobuf::util::NewTypeResolverForDescriptorPool;
  50. using protobuf_test_messages::proto3::TestAllTypesProto3;
  51. using protobuf_test_messages::proto2::TestAllTypesProto2;
  52. using std::string;
  53. namespace {
  54. static const char kTypeUrlPrefix[] = "type.googleapis.com";
  55. static string GetTypeUrl(const Descriptor* message) {
  56. return string(kTypeUrlPrefix) + "/" + message->full_name();
  57. }
  58. /* Routines for building arbitrary protos *************************************/
  59. // We would use CodedOutputStream except that we want more freedom to build
  60. // arbitrary protos (even invalid ones).
  61. const string empty;
  62. string cat(const string& a, const string& b,
  63. const string& c = empty,
  64. const string& d = empty,
  65. const string& e = empty,
  66. const string& f = empty,
  67. const string& g = empty,
  68. const string& h = empty,
  69. const string& i = empty,
  70. const string& j = empty,
  71. const string& k = empty,
  72. const string& l = empty) {
  73. string ret;
  74. ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() +
  75. g.size() + h.size() + i.size() + j.size() + k.size() + l.size());
  76. ret.append(a);
  77. ret.append(b);
  78. ret.append(c);
  79. ret.append(d);
  80. ret.append(e);
  81. ret.append(f);
  82. ret.append(g);
  83. ret.append(h);
  84. ret.append(i);
  85. ret.append(j);
  86. ret.append(k);
  87. ret.append(l);
  88. return ret;
  89. }
  90. // The maximum number of bytes that it takes to encode a 64-bit varint.
  91. #define VARINT_MAX_LEN 10
  92. size_t vencode64(uint64_t val, int over_encoded_bytes, char *buf) {
  93. if (val == 0) { buf[0] = 0; return 1; }
  94. size_t i = 0;
  95. while (val) {
  96. uint8_t byte = val & 0x7fU;
  97. val >>= 7;
  98. if (val || over_encoded_bytes) byte |= 0x80U;
  99. buf[i++] = byte;
  100. }
  101. while (over_encoded_bytes--) {
  102. assert(i < 10);
  103. uint8_t byte = over_encoded_bytes ? 0x80 : 0;
  104. buf[i++] = byte;
  105. }
  106. return i;
  107. }
  108. string varint(uint64_t x) {
  109. char buf[VARINT_MAX_LEN];
  110. size_t len = vencode64(x, 0, buf);
  111. return string(buf, len);
  112. }
  113. // Encodes a varint that is |extra| bytes longer than it needs to be, but still
  114. // valid.
  115. string longvarint(uint64_t x, int extra) {
  116. char buf[VARINT_MAX_LEN];
  117. size_t len = vencode64(x, extra, buf);
  118. return string(buf, len);
  119. }
  120. // TODO: proper byte-swapping for big-endian machines.
  121. string fixed32(void *data) { return string(static_cast<char*>(data), 4); }
  122. string fixed64(void *data) { return string(static_cast<char*>(data), 8); }
  123. string delim(const string& buf) { return cat(varint(buf.size()), buf); }
  124. string u32(uint32_t u32) { return fixed32(&u32); }
  125. string u64(uint64_t u64) { return fixed64(&u64); }
  126. string flt(float f) { return fixed32(&f); }
  127. string dbl(double d) { return fixed64(&d); }
  128. string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); }
  129. string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); }
  130. string tag(uint32_t fieldnum, char wire_type) {
  131. return varint((fieldnum << 3) | wire_type);
  132. }
  133. string GetDefaultValue(FieldDescriptor::Type type) {
  134. switch (type) {
  135. case FieldDescriptor::TYPE_INT32:
  136. case FieldDescriptor::TYPE_INT64:
  137. case FieldDescriptor::TYPE_UINT32:
  138. case FieldDescriptor::TYPE_UINT64:
  139. case FieldDescriptor::TYPE_ENUM:
  140. case FieldDescriptor::TYPE_BOOL:
  141. return varint(0);
  142. case FieldDescriptor::TYPE_SINT32:
  143. return zz32(0);
  144. case FieldDescriptor::TYPE_SINT64:
  145. return zz64(0);
  146. case FieldDescriptor::TYPE_FIXED32:
  147. case FieldDescriptor::TYPE_SFIXED32:
  148. return u32(0);
  149. case FieldDescriptor::TYPE_FIXED64:
  150. case FieldDescriptor::TYPE_SFIXED64:
  151. return u64(0);
  152. case FieldDescriptor::TYPE_FLOAT:
  153. return flt(0);
  154. case FieldDescriptor::TYPE_DOUBLE:
  155. return dbl(0);
  156. case FieldDescriptor::TYPE_STRING:
  157. case FieldDescriptor::TYPE_BYTES:
  158. case FieldDescriptor::TYPE_MESSAGE:
  159. return delim("");
  160. }
  161. return "";
  162. }
  163. string GetNonDefaultValue(FieldDescriptor::Type type) {
  164. switch (type) {
  165. case FieldDescriptor::TYPE_INT32:
  166. case FieldDescriptor::TYPE_INT64:
  167. case FieldDescriptor::TYPE_UINT32:
  168. case FieldDescriptor::TYPE_UINT64:
  169. case FieldDescriptor::TYPE_ENUM:
  170. case FieldDescriptor::TYPE_BOOL:
  171. return varint(1);
  172. case FieldDescriptor::TYPE_SINT32:
  173. return zz32(1);
  174. case FieldDescriptor::TYPE_SINT64:
  175. return zz64(1);
  176. case FieldDescriptor::TYPE_FIXED32:
  177. case FieldDescriptor::TYPE_SFIXED32:
  178. return u32(1);
  179. case FieldDescriptor::TYPE_FIXED64:
  180. case FieldDescriptor::TYPE_SFIXED64:
  181. return u64(1);
  182. case FieldDescriptor::TYPE_FLOAT:
  183. return flt(1);
  184. case FieldDescriptor::TYPE_DOUBLE:
  185. return dbl(1);
  186. case FieldDescriptor::TYPE_STRING:
  187. case FieldDescriptor::TYPE_BYTES:
  188. return delim("a");
  189. case FieldDescriptor::TYPE_MESSAGE:
  190. return delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234)));
  191. }
  192. return "";
  193. }
  194. #define UNKNOWN_FIELD 666
  195. enum class Packed {
  196. UNSPECIFIED = 0,
  197. TRUE = 1,
  198. FALSE = 2,
  199. };
  200. const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type,
  201. bool repeated, bool is_proto3,
  202. Packed packed = Packed::UNSPECIFIED) {
  203. const Descriptor* d = is_proto3 ?
  204. TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor();
  205. for (int i = 0; i < d->field_count(); i++) {
  206. const FieldDescriptor* f = d->field(i);
  207. if (f->type() == type && f->is_repeated() == repeated) {
  208. if ((packed == Packed::TRUE && !f->is_packed()) ||
  209. (packed == Packed::FALSE && f->is_packed())) {
  210. continue;
  211. }
  212. return f;
  213. }
  214. }
  215. string packed_string = "";
  216. const string repeated_string = repeated ? "Repeated " : "Singular ";
  217. const string proto_string = is_proto3 ? "Proto3" : "Proto2";
  218. if (packed == Packed::TRUE) {
  219. packed_string = "Packed ";
  220. }
  221. if (packed == Packed::FALSE) {
  222. packed_string = "Unpacked ";
  223. }
  224. GOOGLE_LOG(FATAL) << "Couldn't find field with type: "
  225. << repeated_string.c_str() << packed_string.c_str()
  226. << FieldDescriptor::TypeName(type) << " for "
  227. << proto_string.c_str();
  228. return nullptr;
  229. }
  230. const FieldDescriptor* GetFieldForMapType(
  231. FieldDescriptor::Type key_type,
  232. FieldDescriptor::Type value_type,
  233. bool is_proto3) {
  234. const Descriptor* d = is_proto3 ?
  235. TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor();
  236. for (int i = 0; i < d->field_count(); i++) {
  237. const FieldDescriptor* f = d->field(i);
  238. if (f->is_map()) {
  239. const Descriptor* map_entry = f->message_type();
  240. const FieldDescriptor* key = map_entry->field(0);
  241. const FieldDescriptor* value = map_entry->field(1);
  242. if (key->type() == key_type && value->type() == value_type) {
  243. return f;
  244. }
  245. }
  246. }
  247. const string proto_string = is_proto3 ? "Proto3" : "Proto2";
  248. GOOGLE_LOG(FATAL) << "Couldn't find map field with type: "
  249. << FieldDescriptor::TypeName(key_type)
  250. << " and "
  251. << FieldDescriptor::TypeName(key_type)
  252. << " for "
  253. << proto_string.c_str();
  254. return nullptr;
  255. }
  256. const FieldDescriptor* GetFieldForOneofType(
  257. FieldDescriptor::Type type, bool is_proto3, bool exclusive = false) {
  258. const Descriptor* d = is_proto3 ?
  259. TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor();
  260. for (int i = 0; i < d->field_count(); i++) {
  261. const FieldDescriptor* f = d->field(i);
  262. if (f->containing_oneof() && ((f->type() == type) ^ exclusive)) {
  263. return f;
  264. }
  265. }
  266. const string proto_string = is_proto3 ? "Proto3" : "Proto2";
  267. GOOGLE_LOG(FATAL) << "Couldn't find oneof field with type: "
  268. << FieldDescriptor::TypeName(type)
  269. << " for "
  270. << proto_string.c_str();
  271. return nullptr;
  272. }
  273. string UpperCase(string str) {
  274. for (int i = 0; i < str.size(); i++) {
  275. str[i] = toupper(str[i]);
  276. }
  277. return str;
  278. }
  279. std::unique_ptr<Message> NewTestMessage(bool is_proto3) {
  280. std::unique_ptr<Message> prototype;
  281. if (is_proto3) {
  282. prototype.reset(new TestAllTypesProto3());
  283. } else {
  284. prototype.reset(new TestAllTypesProto2());
  285. }
  286. return prototype;
  287. }
  288. bool IsProto3Default(FieldDescriptor::Type type, const string& binary_data) {
  289. switch (type) {
  290. case FieldDescriptor::TYPE_DOUBLE:
  291. return binary_data == dbl(0);
  292. case FieldDescriptor::TYPE_FLOAT:
  293. return binary_data == flt(0);
  294. case FieldDescriptor::TYPE_BOOL:
  295. case FieldDescriptor::TYPE_INT64:
  296. case FieldDescriptor::TYPE_UINT64:
  297. case FieldDescriptor::TYPE_INT32:
  298. case FieldDescriptor::TYPE_UINT32:
  299. case FieldDescriptor::TYPE_SINT32:
  300. case FieldDescriptor::TYPE_SINT64:
  301. case FieldDescriptor::TYPE_ENUM:
  302. return binary_data == varint(0);
  303. case FieldDescriptor::TYPE_FIXED64:
  304. case FieldDescriptor::TYPE_SFIXED64:
  305. return binary_data == u64(0);
  306. case FieldDescriptor::TYPE_FIXED32:
  307. case FieldDescriptor::TYPE_SFIXED32:
  308. return binary_data == u32(0);
  309. case FieldDescriptor::TYPE_STRING:
  310. case FieldDescriptor::TYPE_BYTES:
  311. return binary_data == delim("");
  312. default:
  313. return false;
  314. }
  315. }
  316. } // anonymous namespace
  317. namespace google {
  318. namespace protobuf {
  319. bool BinaryAndJsonConformanceSuite::ParseJsonResponse(
  320. const ConformanceResponse& response,
  321. Message* test_message) {
  322. string binary_protobuf;
  323. util::Status status =
  324. JsonToBinaryString(type_resolver_.get(), type_url_,
  325. response.json_payload(), &binary_protobuf);
  326. if (!status.ok()) {
  327. return false;
  328. }
  329. if (!test_message->ParseFromString(binary_protobuf)) {
  330. GOOGLE_LOG(FATAL)
  331. << "INTERNAL ERROR: internal JSON->protobuf transcode "
  332. << "yielded unparseable proto.";
  333. return false;
  334. }
  335. return true;
  336. }
  337. bool BinaryAndJsonConformanceSuite::ParseResponse(
  338. const ConformanceResponse& response,
  339. const ConformanceRequestSetting& setting,
  340. Message* test_message) {
  341. const ConformanceRequest& request = setting.GetRequest();
  342. WireFormat requested_output = request.requested_output_format();
  343. const string& test_name = setting.GetTestName();
  344. ConformanceLevel level = setting.GetLevel();
  345. switch (response.result_case()) {
  346. case ConformanceResponse::kProtobufPayload: {
  347. if (requested_output != conformance::PROTOBUF) {
  348. ReportFailure(
  349. test_name, level, request, response,
  350. StrCat("Test was asked for ", WireFormatToString(requested_output),
  351. " output but provided PROTOBUF instead.").c_str());
  352. return false;
  353. }
  354. if (!test_message->ParseFromString(response.protobuf_payload())) {
  355. ReportFailure(test_name, level, request, response,
  356. "Protobuf output we received from test was unparseable.");
  357. return false;
  358. }
  359. break;
  360. }
  361. case ConformanceResponse::kJsonPayload: {
  362. if (requested_output != conformance::JSON) {
  363. ReportFailure(
  364. test_name, level, request, response,
  365. StrCat("Test was asked for ", WireFormatToString(requested_output),
  366. " output but provided JSON instead.").c_str());
  367. return false;
  368. }
  369. if (!ParseJsonResponse(response, test_message)) {
  370. ReportFailure(test_name, level, request, response,
  371. "JSON output we received from test was unparseable.");
  372. return false;
  373. }
  374. break;
  375. }
  376. default:
  377. GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: "
  378. << response.result_case();
  379. }
  380. return true;
  381. }
  382. void BinaryAndJsonConformanceSuite::ExpectParseFailureForProtoWithProtoVersion (
  383. const string& proto, const string& test_name, ConformanceLevel level,
  384. bool is_proto3) {
  385. std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
  386. // We don't expect output, but if the program erroneously accepts the protobuf
  387. // we let it send its response as this. We must not leave it unspecified.
  388. ConformanceRequestSetting setting(
  389. level, conformance::PROTOBUF, conformance::PROTOBUF,
  390. conformance::BINARY_TEST,
  391. *prototype, test_name, proto);
  392. const ConformanceRequest& request = setting.GetRequest();
  393. ConformanceResponse response;
  394. string effective_test_name =
  395. StrCat(setting.ConformanceLevelToString(level),
  396. (is_proto3 ? ".Proto3" : ".Proto2"),
  397. ".ProtobufInput.", test_name);
  398. RunTest(effective_test_name, request, &response);
  399. if (response.result_case() == ConformanceResponse::kParseError) {
  400. ReportSuccess(effective_test_name);
  401. } else if (response.result_case() == ConformanceResponse::kSkipped) {
  402. ReportSkip(effective_test_name, request, response);
  403. } else {
  404. ReportFailure(effective_test_name, level, request, response,
  405. "Should have failed to parse, but didn't.");
  406. }
  407. }
  408. // Expect that this precise protobuf will cause a parse error.
  409. void BinaryAndJsonConformanceSuite::ExpectParseFailureForProto(
  410. const string& proto, const string& test_name, ConformanceLevel level) {
  411. ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, true);
  412. ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, false);
  413. }
  414. // Expect that this protobuf will cause a parse error, even if it is followed
  415. // by valid protobuf data. We can try running this twice: once with this
  416. // data verbatim and once with this data followed by some valid data.
  417. //
  418. // TODO(haberman): implement the second of these.
  419. void BinaryAndJsonConformanceSuite::ExpectHardParseFailureForProto(
  420. const string& proto, const string& test_name, ConformanceLevel level) {
  421. return ExpectParseFailureForProto(proto, test_name, level);
  422. }
  423. void BinaryAndJsonConformanceSuite::RunValidJsonTest(
  424. const string& test_name, ConformanceLevel level, const string& input_json,
  425. const string& equivalent_text_format) {
  426. TestAllTypesProto3 prototype;
  427. ConformanceRequestSetting setting1(
  428. level, conformance::JSON, conformance::PROTOBUF,
  429. conformance::JSON_TEST,
  430. prototype, test_name, input_json);
  431. RunValidInputTest(setting1, equivalent_text_format);
  432. ConformanceRequestSetting setting2(
  433. level, conformance::JSON, conformance::JSON,
  434. conformance::JSON_TEST,
  435. prototype, test_name, input_json);
  436. RunValidInputTest(setting2, equivalent_text_format);
  437. }
  438. void BinaryAndJsonConformanceSuite::RunValidJsonTestWithProtobufInput(
  439. const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input,
  440. const string& equivalent_text_format) {
  441. ConformanceRequestSetting setting(
  442. level, conformance::PROTOBUF, conformance::JSON,
  443. conformance::JSON_TEST,
  444. input, test_name, input.SerializeAsString());
  445. RunValidInputTest(setting, equivalent_text_format);
  446. }
  447. void BinaryAndJsonConformanceSuite::RunValidJsonIgnoreUnknownTest(
  448. const string& test_name, ConformanceLevel level, const string& input_json,
  449. const string& equivalent_text_format) {
  450. TestAllTypesProto3 prototype;
  451. ConformanceRequestSetting setting(
  452. level, conformance::JSON, conformance::PROTOBUF,
  453. conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST,
  454. prototype, test_name, input_json);
  455. RunValidInputTest(setting, equivalent_text_format);
  456. }
  457. void BinaryAndJsonConformanceSuite::RunValidProtobufTest(
  458. const string& test_name, ConformanceLevel level,
  459. const string& input_protobuf, const string& equivalent_text_format,
  460. bool is_proto3) {
  461. std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
  462. ConformanceRequestSetting setting1(
  463. level, conformance::PROTOBUF, conformance::PROTOBUF,
  464. conformance::BINARY_TEST,
  465. *prototype, test_name, input_protobuf);
  466. RunValidInputTest(setting1, equivalent_text_format);
  467. if (is_proto3) {
  468. ConformanceRequestSetting setting2(
  469. level, conformance::PROTOBUF, conformance::JSON,
  470. conformance::BINARY_TEST,
  471. *prototype, test_name, input_protobuf);
  472. RunValidInputTest(setting2, equivalent_text_format);
  473. }
  474. }
  475. void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest(
  476. const string& test_name, ConformanceLevel level,
  477. const string& input_protobuf, bool is_proto3) {
  478. RunValidBinaryProtobufTest(test_name, level, input_protobuf, input_protobuf,
  479. is_proto3);
  480. }
  481. void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest(
  482. const string& test_name, ConformanceLevel level,
  483. const string& input_protobuf, const string& expected_protobuf,
  484. bool is_proto3) {
  485. std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
  486. ConformanceRequestSetting setting(
  487. level, conformance::PROTOBUF, conformance::PROTOBUF,
  488. conformance::BINARY_TEST,
  489. *prototype, test_name, input_protobuf);
  490. RunValidBinaryInputTest(setting, expected_protobuf, true);
  491. }
  492. void BinaryAndJsonConformanceSuite::RunValidProtobufTestWithMessage(
  493. const string& test_name, ConformanceLevel level, const Message *input,
  494. const string& equivalent_text_format, bool is_proto3) {
  495. RunValidProtobufTest(test_name, level, input->SerializeAsString(),
  496. equivalent_text_format, is_proto3);
  497. }
  498. // According to proto3 JSON specification, JSON serializers follow more strict
  499. // rules than parsers (e.g., a serializer must serialize int32 values as JSON
  500. // numbers while the parser is allowed to accept them as JSON strings). This
  501. // method allows strict checking on a proto3 JSON serializer by inspecting
  502. // the JSON output directly.
  503. void BinaryAndJsonConformanceSuite::RunValidJsonTestWithValidator(
  504. const string& test_name, ConformanceLevel level, const string& input_json,
  505. const Validator& validator) {
  506. TestAllTypesProto3 prototype;
  507. ConformanceRequestSetting setting(
  508. level, conformance::JSON, conformance::JSON,
  509. conformance::JSON_TEST,
  510. prototype, test_name, input_json);
  511. const ConformanceRequest& request = setting.GetRequest();
  512. ConformanceResponse response;
  513. string effective_test_name =
  514. StrCat(setting.ConformanceLevelToString(level),
  515. ".Proto3.JsonInput.",
  516. test_name, ".Validator");
  517. RunTest(effective_test_name, request, &response);
  518. if (response.result_case() == ConformanceResponse::kSkipped) {
  519. ReportSkip(effective_test_name, request, response);
  520. return;
  521. }
  522. if (response.result_case() != ConformanceResponse::kJsonPayload) {
  523. ReportFailure(effective_test_name, level, request, response,
  524. "Expected JSON payload but got type %d.",
  525. response.result_case());
  526. return;
  527. }
  528. Json::Reader reader;
  529. Json::Value value;
  530. if (!reader.parse(response.json_payload(), value)) {
  531. ReportFailure(effective_test_name, level, request, response,
  532. "JSON payload cannot be parsed as valid JSON: %s",
  533. reader.getFormattedErrorMessages().c_str());
  534. return;
  535. }
  536. if (!validator(value)) {
  537. ReportFailure(effective_test_name, level, request, response,
  538. "JSON payload validation failed.");
  539. return;
  540. }
  541. ReportSuccess(effective_test_name);
  542. }
  543. void BinaryAndJsonConformanceSuite::ExpectParseFailureForJson(
  544. const string& test_name, ConformanceLevel level, const string& input_json) {
  545. TestAllTypesProto3 prototype;
  546. // We don't expect output, but if the program erroneously accepts the protobuf
  547. // we let it send its response as this. We must not leave it unspecified.
  548. ConformanceRequestSetting setting(
  549. level, conformance::JSON, conformance::JSON,
  550. conformance::JSON_TEST,
  551. prototype, test_name, input_json);
  552. const ConformanceRequest& request = setting.GetRequest();
  553. ConformanceResponse response;
  554. string effective_test_name =
  555. StrCat(setting.ConformanceLevelToString(level),
  556. ".Proto3.JsonInput.", test_name);
  557. RunTest(effective_test_name, request, &response);
  558. if (response.result_case() == ConformanceResponse::kParseError) {
  559. ReportSuccess(effective_test_name);
  560. } else if (response.result_case() == ConformanceResponse::kSkipped) {
  561. ReportSkip(effective_test_name, request, response);
  562. } else {
  563. ReportFailure(effective_test_name, level, request, response,
  564. "Should have failed to parse, but didn't.");
  565. }
  566. }
  567. void BinaryAndJsonConformanceSuite::ExpectSerializeFailureForJson(
  568. const string& test_name, ConformanceLevel level, const string& text_format) {
  569. TestAllTypesProto3 payload_message;
  570. GOOGLE_CHECK(
  571. TextFormat::ParseFromString(text_format, &payload_message))
  572. << "Failed to parse: " << text_format;
  573. TestAllTypesProto3 prototype;
  574. ConformanceRequestSetting setting(
  575. level, conformance::PROTOBUF, conformance::JSON,
  576. conformance::JSON_TEST,
  577. prototype, test_name, payload_message.SerializeAsString());
  578. const ConformanceRequest& request = setting.GetRequest();
  579. ConformanceResponse response;
  580. string effective_test_name =
  581. StrCat(setting.ConformanceLevelToString(level),
  582. ".", test_name, ".JsonOutput");
  583. RunTest(effective_test_name, request, &response);
  584. if (response.result_case() == ConformanceResponse::kSerializeError) {
  585. ReportSuccess(effective_test_name);
  586. } else if (response.result_case() == ConformanceResponse::kSkipped) {
  587. ReportSkip(effective_test_name, request, response);
  588. } else {
  589. ReportFailure(effective_test_name, level, request, response,
  590. "Should have failed to serialize, but didn't.");
  591. }
  592. }
  593. void BinaryAndJsonConformanceSuite::TestPrematureEOFForType(
  594. FieldDescriptor::Type type) {
  595. // Incomplete values for each wire type.
  596. static const string incompletes[6] = {
  597. string("\x80"), // VARINT
  598. string("abcdefg"), // 64BIT
  599. string("\x80"), // DELIMITED (partial length)
  600. string(), // START_GROUP (no value required)
  601. string(), // END_GROUP (no value required)
  602. string("abc") // 32BIT
  603. };
  604. const FieldDescriptor* field = GetFieldForType(type, false, true);
  605. const FieldDescriptor* rep_field = GetFieldForType(type, true, true);
  606. WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
  607. static_cast<WireFormatLite::FieldType>(type));
  608. const string& incomplete = incompletes[wire_type];
  609. const string type_name =
  610. UpperCase(string(".") + FieldDescriptor::TypeName(type));
  611. ExpectParseFailureForProto(
  612. tag(field->number(), wire_type),
  613. "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
  614. ExpectParseFailureForProto(
  615. tag(rep_field->number(), wire_type),
  616. "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
  617. ExpectParseFailureForProto(
  618. tag(UNKNOWN_FIELD, wire_type),
  619. "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
  620. ExpectParseFailureForProto(
  621. cat( tag(field->number(), wire_type), incomplete ),
  622. "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
  623. ExpectParseFailureForProto(
  624. cat( tag(rep_field->number(), wire_type), incomplete ),
  625. "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
  626. ExpectParseFailureForProto(
  627. cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
  628. "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
  629. if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
  630. ExpectParseFailureForProto(
  631. cat( tag(field->number(), wire_type), varint(1) ),
  632. "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
  633. REQUIRED);
  634. ExpectParseFailureForProto(
  635. cat( tag(rep_field->number(), wire_type), varint(1) ),
  636. "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
  637. REQUIRED);
  638. // EOF in the middle of delimited data for unknown value.
  639. ExpectParseFailureForProto(
  640. cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
  641. "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED);
  642. if (type == FieldDescriptor::TYPE_MESSAGE) {
  643. // Submessage ends in the middle of a value.
  644. string incomplete_submsg =
  645. cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
  646. incompletes[WireFormatLite::WIRETYPE_VARINT] );
  647. ExpectHardParseFailureForProto(
  648. cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  649. varint(incomplete_submsg.size()),
  650. incomplete_submsg ),
  651. "PrematureEofInSubmessageValue" + type_name, REQUIRED);
  652. }
  653. } else if (type != FieldDescriptor::TYPE_GROUP) {
  654. // Non-delimited, non-group: eligible for packing.
  655. // Packed region ends in the middle of a value.
  656. ExpectHardParseFailureForProto(
  657. cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  658. varint(incomplete.size()), incomplete),
  659. "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
  660. // EOF in the middle of packed region.
  661. ExpectParseFailureForProto(
  662. cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  663. varint(1)),
  664. "PrematureEofInPackedField" + type_name, REQUIRED);
  665. }
  666. }
  667. void BinaryAndJsonConformanceSuite::TestValidDataForType(
  668. FieldDescriptor::Type type,
  669. std::vector<std::pair<std::string, std::string>> values) {
  670. for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
  671. const string type_name =
  672. UpperCase(string(".") + FieldDescriptor::TypeName(type));
  673. WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
  674. static_cast<WireFormatLite::FieldType>(type));
  675. const FieldDescriptor* field = GetFieldForType(type, false, is_proto3);
  676. const FieldDescriptor* rep_field = GetFieldForType(type, true, is_proto3);
  677. // Test singular data for singular fields.
  678. for (size_t i = 0; i < values.size(); i++) {
  679. string proto = cat(tag(field->number(), wire_type), values[i].first);
  680. // In proto3, default primitive fields should not be encoded.
  681. string expected_proto =
  682. is_proto3 && IsProto3Default(field->type(), values[i].second) ?
  683. "" :
  684. cat(tag(field->number(), wire_type), values[i].second);
  685. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  686. test_message->MergeFromString(expected_proto);
  687. string text = test_message->DebugString();
  688. RunValidProtobufTest(StrCat("ValidDataScalar", type_name, "[", i, "]"),
  689. REQUIRED, proto, text, is_proto3);
  690. RunValidBinaryProtobufTest(
  691. StrCat("ValidDataScalarBinary", type_name, "[", i, "]"),
  692. RECOMMENDED,
  693. proto,
  694. expected_proto, is_proto3);
  695. }
  696. // Test repeated data for singular fields.
  697. // For scalar message fields, repeated values are merged, which is tested
  698. // separately.
  699. if (type != FieldDescriptor::TYPE_MESSAGE) {
  700. string proto;
  701. for (size_t i = 0; i < values.size(); i++) {
  702. proto += cat(tag(field->number(), wire_type), values[i].first);
  703. }
  704. string expected_proto =
  705. cat(tag(field->number(), wire_type), values.back().second);
  706. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  707. test_message->MergeFromString(expected_proto);
  708. string text = test_message->DebugString();
  709. RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED,
  710. proto, text, is_proto3);
  711. }
  712. // Test repeated fields.
  713. if (FieldDescriptor::IsTypePackable(type)) {
  714. const FieldDescriptor* packed_field =
  715. GetFieldForType(type, true, is_proto3, Packed::TRUE);
  716. const FieldDescriptor* unpacked_field =
  717. GetFieldForType(type, true, is_proto3, Packed::FALSE);
  718. string default_proto_packed;
  719. string default_proto_unpacked;
  720. string default_proto_packed_expected;
  721. string default_proto_unpacked_expected;
  722. string packed_proto_packed;
  723. string packed_proto_unpacked;
  724. string packed_proto_expected;
  725. string unpacked_proto_packed;
  726. string unpacked_proto_unpacked;
  727. string unpacked_proto_expected;
  728. for (size_t i = 0; i < values.size(); i++) {
  729. default_proto_unpacked +=
  730. cat(tag(rep_field->number(), wire_type), values[i].first);
  731. default_proto_unpacked_expected +=
  732. cat(tag(rep_field->number(), wire_type), values[i].second);
  733. default_proto_packed += values[i].first;
  734. default_proto_packed_expected += values[i].second;
  735. packed_proto_unpacked +=
  736. cat(tag(packed_field->number(), wire_type), values[i].first);
  737. packed_proto_packed += values[i].first;
  738. packed_proto_expected += values[i].second;
  739. unpacked_proto_unpacked +=
  740. cat(tag(unpacked_field->number(), wire_type), values[i].first);
  741. unpacked_proto_packed += values[i].first;
  742. unpacked_proto_expected +=
  743. cat(tag(unpacked_field->number(), wire_type), values[i].second);
  744. }
  745. default_proto_packed = cat(
  746. tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  747. delim(default_proto_packed));
  748. default_proto_packed_expected = cat(
  749. tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  750. delim(default_proto_packed_expected));
  751. packed_proto_packed = cat(tag(packed_field->number(),
  752. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  753. delim(packed_proto_packed));
  754. packed_proto_expected =
  755. cat(tag(packed_field->number(),
  756. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  757. delim(packed_proto_expected));
  758. unpacked_proto_packed =
  759. cat(tag(unpacked_field->number(),
  760. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  761. delim(unpacked_proto_packed));
  762. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  763. test_message->MergeFromString(default_proto_packed_expected);
  764. string text = test_message->DebugString();
  765. // Ensures both packed and unpacked data can be parsed.
  766. RunValidProtobufTest(
  767. StrCat("ValidDataRepeated", type_name, ".UnpackedInput"), REQUIRED,
  768. default_proto_unpacked, text, is_proto3);
  769. RunValidProtobufTest(
  770. StrCat("ValidDataRepeated", type_name, ".PackedInput"), REQUIRED,
  771. default_proto_packed, text, is_proto3);
  772. // proto2 should encode as unpacked by default and proto3 should encode as
  773. // packed by default.
  774. string expected_proto = rep_field->is_packed()
  775. ? default_proto_packed_expected
  776. : default_proto_unpacked_expected;
  777. RunValidBinaryProtobufTest(StrCat("ValidDataRepeated", type_name,
  778. ".UnpackedInput.DefaultOutput"),
  779. RECOMMENDED, default_proto_unpacked,
  780. expected_proto, is_proto3);
  781. RunValidBinaryProtobufTest(
  782. StrCat("ValidDataRepeated", type_name, ".PackedInput.DefaultOutput"),
  783. RECOMMENDED, default_proto_packed, expected_proto, is_proto3);
  784. RunValidBinaryProtobufTest(
  785. StrCat("ValidDataRepeated", type_name, ".UnpackedInput.PackedOutput"),
  786. RECOMMENDED, packed_proto_unpacked, packed_proto_expected, is_proto3);
  787. RunValidBinaryProtobufTest(
  788. StrCat("ValidDataRepeated", type_name, ".PackedInput.PackedOutput"),
  789. RECOMMENDED, packed_proto_packed, packed_proto_expected, is_proto3);
  790. RunValidBinaryProtobufTest(StrCat("ValidDataRepeated", type_name,
  791. ".UnpackedInput.UnpackedOutput"),
  792. RECOMMENDED, unpacked_proto_unpacked,
  793. unpacked_proto_expected, is_proto3);
  794. RunValidBinaryProtobufTest(
  795. StrCat("ValidDataRepeated", type_name, ".PackedInput.UnpackedOutput"),
  796. RECOMMENDED, unpacked_proto_packed, unpacked_proto_expected,
  797. is_proto3);
  798. } else {
  799. string proto;
  800. string expected_proto;
  801. for (size_t i = 0; i < values.size(); i++) {
  802. proto += cat(tag(rep_field->number(), wire_type), values[i].first);
  803. expected_proto +=
  804. cat(tag(rep_field->number(), wire_type), values[i].second);
  805. }
  806. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  807. test_message->MergeFromString(expected_proto);
  808. string text = test_message->DebugString();
  809. RunValidProtobufTest(StrCat("ValidDataRepeated", type_name), REQUIRED,
  810. proto, text, is_proto3);
  811. }
  812. }
  813. }
  814. void BinaryAndJsonConformanceSuite::TestValidDataForRepeatedScalarMessage() {
  815. std::vector<std::string> values = {
  816. delim(cat(
  817. tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  818. delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234),
  819. tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1234),
  820. tag(31, WireFormatLite::WIRETYPE_VARINT), varint(1234))))),
  821. delim(cat(
  822. tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  823. delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(4321),
  824. tag(3, WireFormatLite::WIRETYPE_VARINT), varint(4321),
  825. tag(31, WireFormatLite::WIRETYPE_VARINT), varint(4321))))),
  826. };
  827. const std::string expected =
  828. R"({
  829. corecursive: {
  830. optional_int32: 4321,
  831. optional_int64: 1234,
  832. optional_uint32: 4321,
  833. repeated_int32: [1234, 4321],
  834. }
  835. })";
  836. for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
  837. string proto;
  838. const FieldDescriptor* field =
  839. GetFieldForType(FieldDescriptor::TYPE_MESSAGE, false, is_proto3);
  840. for (size_t i = 0; i < values.size(); i++) {
  841. proto +=
  842. cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  843. values[i]);
  844. }
  845. RunValidProtobufTest("RepeatedScalarMessageMerge", REQUIRED, proto,
  846. field->name() + ": " + expected, is_proto3);
  847. }
  848. }
  849. void BinaryAndJsonConformanceSuite::TestValidDataForMapType(
  850. FieldDescriptor::Type key_type,
  851. FieldDescriptor::Type value_type) {
  852. const string key_type_name =
  853. UpperCase(string(".") + FieldDescriptor::TypeName(key_type));
  854. const string value_type_name =
  855. UpperCase(string(".") + FieldDescriptor::TypeName(value_type));
  856. WireFormatLite::WireType key_wire_type =
  857. WireFormatLite::WireTypeForFieldType(
  858. static_cast<WireFormatLite::FieldType>(key_type));
  859. WireFormatLite::WireType value_wire_type =
  860. WireFormatLite::WireTypeForFieldType(
  861. static_cast<WireFormatLite::FieldType>(value_type));
  862. string key1_data =
  863. cat(tag(1, key_wire_type), GetDefaultValue(key_type));
  864. string value1_data =
  865. cat(tag(2, value_wire_type), GetDefaultValue(value_type));
  866. string key2_data =
  867. cat(tag(1, key_wire_type), GetNonDefaultValue(key_type));
  868. string value2_data =
  869. cat(tag(2, value_wire_type), GetNonDefaultValue(value_type));
  870. for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
  871. const FieldDescriptor* field =
  872. GetFieldForMapType(key_type, value_type, is_proto3);
  873. {
  874. // Tests map with default key and value.
  875. string proto = cat(tag(field->number(),
  876. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  877. delim(cat(key1_data, value1_data)));
  878. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  879. test_message->MergeFromString(proto);
  880. string text = test_message->DebugString();
  881. RunValidProtobufTest(
  882. StrCat("ValidDataMap",
  883. key_type_name,
  884. value_type_name,
  885. ".Default"),
  886. REQUIRED, proto, text, is_proto3);
  887. }
  888. {
  889. // Tests map with missing default key and value.
  890. string proto = cat(tag(field->number(),
  891. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  892. delim(""));
  893. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  894. test_message->MergeFromString(proto);
  895. string text = test_message->DebugString();
  896. RunValidProtobufTest(
  897. StrCat("ValidDataMap",
  898. key_type_name,
  899. value_type_name,
  900. ".MissingDefault"),
  901. REQUIRED, proto, text, is_proto3);
  902. }
  903. {
  904. // Tests map with non-default key and value.
  905. string proto = cat(tag(field->number(),
  906. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  907. delim(cat(key2_data, value2_data)));
  908. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  909. test_message->MergeFromString(proto);
  910. string text = test_message->DebugString();
  911. RunValidProtobufTest(
  912. StrCat("ValidDataMap",
  913. key_type_name,
  914. value_type_name,
  915. ".NonDefault"),
  916. REQUIRED, proto, text, is_proto3);
  917. }
  918. {
  919. // Tests map with unordered key and value.
  920. string proto = cat(tag(field->number(),
  921. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  922. delim(cat(value2_data, key2_data)));
  923. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  924. test_message->MergeFromString(proto);
  925. string text = test_message->DebugString();
  926. RunValidProtobufTest(
  927. StrCat("ValidDataMap",
  928. key_type_name,
  929. value_type_name,
  930. ".Unordered"),
  931. REQUIRED, proto, text, is_proto3);
  932. }
  933. {
  934. // Tests map with duplicate key.
  935. string proto1 = cat(tag(field->number(),
  936. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  937. delim(cat(key2_data, value1_data)));
  938. string proto2 = cat(tag(field->number(),
  939. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  940. delim(cat(key2_data, value2_data)));
  941. string proto = cat(proto1, proto2);
  942. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  943. test_message->MergeFromString(proto2);
  944. string text = test_message->DebugString();
  945. RunValidProtobufTest(
  946. StrCat("ValidDataMap",
  947. key_type_name,
  948. value_type_name,
  949. ".DuplicateKey"),
  950. REQUIRED, proto, text, is_proto3);
  951. }
  952. {
  953. // Tests map with duplicate key in map entry.
  954. string proto = cat(tag(field->number(),
  955. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  956. delim(cat(key1_data, key2_data, value2_data)));
  957. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  958. test_message->MergeFromString(proto);
  959. string text = test_message->DebugString();
  960. RunValidProtobufTest(
  961. StrCat("ValidDataMap",
  962. key_type_name,
  963. value_type_name,
  964. ".DuplicateKeyInMapEntry"),
  965. REQUIRED, proto, text, is_proto3);
  966. }
  967. {
  968. // Tests map with duplicate value in map entry.
  969. string proto = cat(tag(field->number(),
  970. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  971. delim(cat(key2_data, value1_data, value2_data)));
  972. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  973. test_message->MergeFromString(proto);
  974. string text = test_message->DebugString();
  975. RunValidProtobufTest(
  976. StrCat("ValidDataMap",
  977. key_type_name,
  978. value_type_name,
  979. ".DuplicateValueInMapEntry"),
  980. REQUIRED, proto, text, is_proto3);
  981. }
  982. }
  983. }
  984. void BinaryAndJsonConformanceSuite::TestOverwriteMessageValueMap() {
  985. string key_data =
  986. cat(tag(1, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(""));
  987. string field1_data = cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1));
  988. string field2_data = cat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1));
  989. string field31_data = cat(tag(31, WireFormatLite::WIRETYPE_VARINT), varint(1));
  990. string submsg1_data = delim(cat(field1_data, field31_data));
  991. string submsg2_data = delim(cat(field2_data, field31_data));
  992. string value1_data =
  993. cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  994. delim(cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  995. submsg1_data)));
  996. string value2_data =
  997. cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  998. delim(cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  999. submsg2_data)));
  1000. for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
  1001. const FieldDescriptor* field =
  1002. GetFieldForMapType(
  1003. FieldDescriptor::TYPE_STRING,
  1004. FieldDescriptor::TYPE_MESSAGE, is_proto3);
  1005. string proto1 = cat(tag(field->number(),
  1006. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  1007. delim(cat(key_data, value1_data)));
  1008. string proto2 = cat(tag(field->number(),
  1009. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  1010. delim(cat(key_data, value2_data)));
  1011. string proto = cat(proto1, proto2);
  1012. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  1013. test_message->MergeFromString(proto2);
  1014. string text = test_message->DebugString();
  1015. RunValidProtobufTest(
  1016. "ValidDataMap.STRING.MESSAGE.MergeValue",
  1017. REQUIRED, proto, text, is_proto3);
  1018. }
  1019. }
  1020. void BinaryAndJsonConformanceSuite::TestValidDataForOneofType(
  1021. FieldDescriptor::Type type) {
  1022. const string type_name =
  1023. UpperCase(string(".") + FieldDescriptor::TypeName(type));
  1024. WireFormatLite::WireType wire_type =
  1025. WireFormatLite::WireTypeForFieldType(
  1026. static_cast<WireFormatLite::FieldType>(type));
  1027. for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
  1028. const FieldDescriptor* field = GetFieldForOneofType(type, is_proto3);
  1029. const string default_value =
  1030. cat(tag(field->number(), wire_type), GetDefaultValue(type));
  1031. const string non_default_value =
  1032. cat(tag(field->number(), wire_type), GetNonDefaultValue(type));
  1033. {
  1034. // Tests oneof with default value.
  1035. const string proto = default_value;
  1036. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  1037. test_message->MergeFromString(proto);
  1038. string text = test_message->DebugString();
  1039. RunValidProtobufTest(StrCat("ValidDataOneof", type_name, ".DefaultValue"),
  1040. REQUIRED, proto, text, is_proto3);
  1041. RunValidBinaryProtobufTest(
  1042. StrCat("ValidDataOneofBinary", type_name, ".DefaultValue"),
  1043. RECOMMENDED, proto, proto, is_proto3);
  1044. }
  1045. {
  1046. // Tests oneof with non-default value.
  1047. const string proto = non_default_value;
  1048. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  1049. test_message->MergeFromString(proto);
  1050. string text = test_message->DebugString();
  1051. RunValidProtobufTest(
  1052. StrCat("ValidDataOneof", type_name, ".NonDefaultValue"),
  1053. REQUIRED, proto, text, is_proto3);
  1054. RunValidBinaryProtobufTest(
  1055. StrCat("ValidDataOneofBinary", type_name, ".NonDefaultValue"),
  1056. RECOMMENDED, proto, proto, is_proto3);
  1057. }
  1058. {
  1059. // Tests oneof with multiple values of the same field.
  1060. const string proto = StrCat(default_value, non_default_value);
  1061. const string expected_proto = non_default_value;
  1062. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  1063. test_message->MergeFromString(expected_proto);
  1064. string text = test_message->DebugString();
  1065. RunValidProtobufTest(
  1066. StrCat("ValidDataOneof", type_name, ".MultipleValuesForSameField"),
  1067. REQUIRED, proto, text, is_proto3);
  1068. RunValidBinaryProtobufTest(
  1069. StrCat("ValidDataOneofBinary", type_name,
  1070. ".MultipleValuesForSameField"),
  1071. RECOMMENDED, proto, expected_proto, is_proto3);
  1072. }
  1073. {
  1074. // Tests oneof with multiple values of the different fields.
  1075. const FieldDescriptor* other_field =
  1076. GetFieldForOneofType(type, is_proto3, true);
  1077. FieldDescriptor::Type other_type = other_field->type();
  1078. WireFormatLite::WireType other_wire_type =
  1079. WireFormatLite::WireTypeForFieldType(
  1080. static_cast<WireFormatLite::FieldType>(other_type));
  1081. const string other_value =
  1082. cat(tag(other_field->number(), other_wire_type),
  1083. GetDefaultValue(other_type));
  1084. const string proto = StrCat(other_value, non_default_value);
  1085. const string expected_proto = non_default_value;
  1086. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  1087. test_message->MergeFromString(expected_proto);
  1088. string text = test_message->DebugString();
  1089. RunValidProtobufTest(
  1090. StrCat("ValidDataOneof", type_name,
  1091. ".MultipleValuesForDifferentField"),
  1092. REQUIRED, proto, text, is_proto3);
  1093. RunValidBinaryProtobufTest(
  1094. StrCat("ValidDataOneofBinary", type_name,
  1095. ".MultipleValuesForDifferentField"),
  1096. RECOMMENDED, proto, expected_proto, is_proto3);
  1097. }
  1098. }
  1099. }
  1100. void BinaryAndJsonConformanceSuite::TestMergeOneofMessage() {
  1101. string field1_data = cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1));
  1102. string field2a_data = cat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1));
  1103. string field2b_data = cat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1));
  1104. string field89_data = cat(tag(89, WireFormatLite::WIRETYPE_VARINT),
  1105. varint(1));
  1106. string submsg1_data =
  1107. cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  1108. delim(cat(field1_data, field2a_data, field89_data)));
  1109. string submsg2_data =
  1110. cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  1111. delim(cat(field2b_data, field89_data)));
  1112. string merged_data = cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  1113. delim(cat(field1_data, field2b_data,
  1114. field89_data, field89_data)));
  1115. for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
  1116. const FieldDescriptor* field =
  1117. GetFieldForOneofType(FieldDescriptor::TYPE_MESSAGE, is_proto3);
  1118. string proto1 = cat(tag(field->number(),
  1119. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  1120. delim(submsg1_data));
  1121. string proto2 = cat(tag(field->number(),
  1122. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  1123. delim(submsg2_data));
  1124. string proto = cat(proto1, proto2);
  1125. string expected_proto =
  1126. cat(tag(field->number(),
  1127. WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  1128. delim(merged_data));
  1129. std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
  1130. test_message->MergeFromString(expected_proto);
  1131. string text = test_message->DebugString();
  1132. RunValidProtobufTest(
  1133. "ValidDataOneof.MESSAGE.Merge",
  1134. REQUIRED, proto, text, is_proto3);
  1135. RunValidBinaryProtobufTest(
  1136. "ValidDataOneofBinary.MESSAGE.Merge",
  1137. RECOMMENDED, proto, expected_proto, is_proto3);
  1138. }
  1139. }
  1140. void BinaryAndJsonConformanceSuite::TestIllegalTags() {
  1141. // field num 0 is illegal
  1142. string nullfield[] = {
  1143. "\1DEADBEEF",
  1144. "\2\1\1",
  1145. "\3\4",
  1146. "\5DEAD"
  1147. };
  1148. for (int i = 0; i < 4; i++) {
  1149. string name = "IllegalZeroFieldNum_Case_0";
  1150. name.back() += i;
  1151. ExpectParseFailureForProto(nullfield[i], name, REQUIRED);
  1152. }
  1153. }
  1154. template <class MessageType>
  1155. void BinaryAndJsonConformanceSuite::TestOneofMessage (
  1156. MessageType &message, bool is_proto3) {
  1157. message.set_oneof_uint32(0);
  1158. RunValidProtobufTestWithMessage(
  1159. "OneofZeroUint32", RECOMMENDED, &message, "oneof_uint32: 0", is_proto3);
  1160. message.mutable_oneof_nested_message()->set_a(0);
  1161. RunValidProtobufTestWithMessage(
  1162. "OneofZeroMessage", RECOMMENDED, &message,
  1163. is_proto3 ? "oneof_nested_message: {}" : "oneof_nested_message: {a: 0}",
  1164. is_proto3);
  1165. message.mutable_oneof_nested_message()->set_a(1);
  1166. RunValidProtobufTestWithMessage(
  1167. "OneofZeroMessageSetTwice", RECOMMENDED, &message,
  1168. "oneof_nested_message: {a: 1}",
  1169. is_proto3);
  1170. message.set_oneof_string("");
  1171. RunValidProtobufTestWithMessage(
  1172. "OneofZeroString", RECOMMENDED, &message, "oneof_string: \"\"", is_proto3);
  1173. message.set_oneof_bytes("");
  1174. RunValidProtobufTestWithMessage(
  1175. "OneofZeroBytes", RECOMMENDED, &message, "oneof_bytes: \"\"", is_proto3);
  1176. message.set_oneof_bool(false);
  1177. RunValidProtobufTestWithMessage(
  1178. "OneofZeroBool", RECOMMENDED, &message, "oneof_bool: false", is_proto3);
  1179. message.set_oneof_uint64(0);
  1180. RunValidProtobufTestWithMessage(
  1181. "OneofZeroUint64", RECOMMENDED, &message, "oneof_uint64: 0", is_proto3);
  1182. message.set_oneof_float(0.0f);
  1183. RunValidProtobufTestWithMessage(
  1184. "OneofZeroFloat", RECOMMENDED, &message, "oneof_float: 0", is_proto3);
  1185. message.set_oneof_double(0.0);
  1186. RunValidProtobufTestWithMessage(
  1187. "OneofZeroDouble", RECOMMENDED, &message, "oneof_double: 0", is_proto3);
  1188. message.set_oneof_enum(MessageType::FOO);
  1189. RunValidProtobufTestWithMessage(
  1190. "OneofZeroEnum", RECOMMENDED, &message, "oneof_enum: FOO", is_proto3);
  1191. }
  1192. template <class MessageType>
  1193. void BinaryAndJsonConformanceSuite::TestUnknownMessage(
  1194. MessageType& message, bool is_proto3) {
  1195. message.ParseFromString("\xA8\x1F\x01");
  1196. RunValidBinaryProtobufTest("UnknownVarint", REQUIRED,
  1197. message.SerializeAsString(), is_proto3);
  1198. }
  1199. void BinaryAndJsonConformanceSuite::RunSuiteImpl() {
  1200. // Hack to get the list of test failures based on whether
  1201. // GOOGLE3_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER is enabled or not.
  1202. conformance::FailureSet failure_set;
  1203. ConformanceRequest req;
  1204. ConformanceResponse res;
  1205. req.set_message_type(failure_set.GetTypeName());
  1206. req.set_protobuf_payload("");
  1207. req.set_requested_output_format(conformance::WireFormat::PROTOBUF);
  1208. RunTest("FindFailures", req, &res);
  1209. GOOGLE_CHECK(failure_set.MergeFromString(res.protobuf_payload()));
  1210. for (const string& failure : failure_set.failure()) {
  1211. AddExpectedFailedTest(failure);
  1212. }
  1213. type_resolver_.reset(NewTypeResolverForDescriptorPool(
  1214. kTypeUrlPrefix, DescriptorPool::generated_pool()));
  1215. type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor());
  1216. for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
  1217. if (i == FieldDescriptor::TYPE_GROUP) continue;
  1218. TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
  1219. }
  1220. TestIllegalTags();
  1221. int64 kInt64Min = -9223372036854775808ULL;
  1222. int64 kInt64Max = 9223372036854775807ULL;
  1223. uint64 kUint64Max = 18446744073709551615ULL;
  1224. int32 kInt32Max = 2147483647;
  1225. int32 kInt32Min = -2147483648;
  1226. uint32 kUint32Max = 4294967295UL;
  1227. TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, {
  1228. {dbl(0), dbl(0)},
  1229. {dbl(0.1), dbl(0.1)},
  1230. {dbl(1.7976931348623157e+308), dbl(1.7976931348623157e+308)},
  1231. {dbl(2.22507385850720138309e-308), dbl(2.22507385850720138309e-308)},
  1232. });
  1233. TestValidDataForType(FieldDescriptor::TYPE_FLOAT, {
  1234. {flt(0), flt(0)},
  1235. {flt(0.1), flt(0.1)},
  1236. {flt(1.00000075e-36), flt(1.00000075e-36)},
  1237. {flt(3.402823e+38), flt(3.402823e+38)}, // 3.40282347e+38
  1238. {flt(1.17549435e-38f), flt(1.17549435e-38)},
  1239. });
  1240. TestValidDataForType(FieldDescriptor::TYPE_INT64, {
  1241. {varint(0), varint(0)},
  1242. {varint(12345), varint(12345)},
  1243. {varint(kInt64Max), varint(kInt64Max)},
  1244. {varint(kInt64Min), varint(kInt64Min)},
  1245. });
  1246. TestValidDataForType(FieldDescriptor::TYPE_UINT64, {
  1247. {varint(0), varint(0)},
  1248. {varint(12345), varint(12345)},
  1249. {varint(kUint64Max), varint(kUint64Max)},
  1250. });
  1251. TestValidDataForType(FieldDescriptor::TYPE_INT32, {
  1252. {varint(0), varint(0)},
  1253. {varint(12345), varint(12345)},
  1254. {longvarint(12345, 2), varint(12345)},
  1255. {longvarint(12345, 7), varint(12345)},
  1256. {varint(kInt32Max), varint(kInt32Max)},
  1257. {varint(kInt32Min), varint(kInt32Min)},
  1258. {varint(1LL << 33), varint(0)},
  1259. {varint((1LL << 33) - 1), varint(-1)},
  1260. });
  1261. TestValidDataForType(FieldDescriptor::TYPE_UINT32, {
  1262. {varint(0), varint(0)},
  1263. {varint(12345), varint(12345)},
  1264. {longvarint(12345, 2), varint(12345)},
  1265. {longvarint(12345, 7), varint(12345)},
  1266. {varint(kUint32Max), varint(kUint32Max)}, // UINT32_MAX
  1267. {varint(1LL << 33), varint(0)},
  1268. {varint((1LL << 33) - 1), varint((1LL << 32) - 1)},
  1269. });
  1270. TestValidDataForType(FieldDescriptor::TYPE_FIXED64, {
  1271. {u64(0), u64(0)},
  1272. {u64(12345), u64(12345)},
  1273. {u64(kUint64Max), u64(kUint64Max)},
  1274. });
  1275. TestValidDataForType(FieldDescriptor::TYPE_FIXED32, {
  1276. {u32(0), u32(0)},
  1277. {u32(12345), u32(12345)},
  1278. {u32(kUint32Max), u32(kUint32Max)}, // UINT32_MAX
  1279. });
  1280. TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, {
  1281. {u64(0), u64(0)},
  1282. {u64(12345), u64(12345)},
  1283. {u64(kInt64Max), u64(kInt64Max)},
  1284. {u64(kInt64Min), u64(kInt64Min)},
  1285. });
  1286. TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, {
  1287. {u32(0), u32(0)},
  1288. {u32(12345), u32(12345)},
  1289. {u32(kInt32Max), u32(kInt32Max)},
  1290. {u32(kInt32Min), u32(kInt32Min)},
  1291. });
  1292. TestValidDataForType(FieldDescriptor::TYPE_BOOL, {
  1293. {varint(0), varint(0)},
  1294. {varint(1), varint(1)},
  1295. {varint(12345678), varint(1)},
  1296. });
  1297. TestValidDataForType(FieldDescriptor::TYPE_SINT32, {
  1298. {zz32(0), zz32(0)},
  1299. {zz32(12345), zz32(12345)},
  1300. {zz32(kInt32Max), zz32(kInt32Max)},
  1301. {zz32(kInt32Min), zz32(kInt32Min)},
  1302. });
  1303. TestValidDataForType(FieldDescriptor::TYPE_SINT64, {
  1304. {zz64(0), zz64(0)},
  1305. {zz64(12345), zz64(12345)},
  1306. {zz64(kInt64Max), zz64(kInt64Max)},
  1307. {zz64(kInt64Min), zz64(kInt64Min)},
  1308. });
  1309. TestValidDataForType(FieldDescriptor::TYPE_STRING, {
  1310. {delim(""), delim("")},
  1311. {delim("Hello world!"), delim("Hello world!")},
  1312. {delim("\'\"\?\\\a\b\f\n\r\t\v"),
  1313. delim("\'\"\?\\\a\b\f\n\r\t\v")}, // escape
  1314. {delim("谷歌"), delim("谷歌")}, // Google in Chinese
  1315. {delim("\u8C37\u6B4C"), delim("谷歌")}, // unicode escape
  1316. {delim("\u8c37\u6b4c"), delim("谷歌")}, // lowercase unicode
  1317. {delim("\xF0\x9F\x98\x81"), delim("\xF0\x9F\x98\x81")}, // emoji: 😁
  1318. });
  1319. TestValidDataForType(FieldDescriptor::TYPE_BYTES, {
  1320. {delim(""), delim("")},
  1321. {delim("\x01\x02"), delim("\x01\x02")},
  1322. {delim("\xfb"), delim("\xfb")},
  1323. });
  1324. TestValidDataForType(FieldDescriptor::TYPE_ENUM, {
  1325. {varint(0), varint(0)},
  1326. {varint(1), varint(1)},
  1327. {varint(2), varint(2)},
  1328. {varint(-1), varint(-1)},
  1329. });
  1330. TestValidDataForRepeatedScalarMessage();
  1331. TestValidDataForType(FieldDescriptor::TYPE_MESSAGE, {
  1332. {delim(""), delim("")},
  1333. {delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234))),
  1334. delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234)))},
  1335. });
  1336. TestValidDataForMapType(
  1337. FieldDescriptor::TYPE_INT32,
  1338. FieldDescriptor::TYPE_INT32);
  1339. TestValidDataForMapType(
  1340. FieldDescriptor::TYPE_INT64,
  1341. FieldDescriptor::TYPE_INT64);
  1342. TestValidDataForMapType(
  1343. FieldDescriptor::TYPE_UINT32,
  1344. FieldDescriptor::TYPE_UINT32);
  1345. TestValidDataForMapType(
  1346. FieldDescriptor::TYPE_UINT64,
  1347. FieldDescriptor::TYPE_UINT64);
  1348. TestValidDataForMapType(
  1349. FieldDescriptor::TYPE_SINT32,
  1350. FieldDescriptor::TYPE_SINT32);
  1351. TestValidDataForMapType(
  1352. FieldDescriptor::TYPE_SINT64,
  1353. FieldDescriptor::TYPE_SINT64);
  1354. TestValidDataForMapType(
  1355. FieldDescriptor::TYPE_FIXED32,
  1356. FieldDescriptor::TYPE_FIXED32);
  1357. TestValidDataForMapType(
  1358. FieldDescriptor::TYPE_FIXED64,
  1359. FieldDescriptor::TYPE_FIXED64);
  1360. TestValidDataForMapType(
  1361. FieldDescriptor::TYPE_SFIXED32,
  1362. FieldDescriptor::TYPE_SFIXED32);
  1363. TestValidDataForMapType(
  1364. FieldDescriptor::TYPE_SFIXED64,
  1365. FieldDescriptor::TYPE_SFIXED64);
  1366. TestValidDataForMapType(
  1367. FieldDescriptor::TYPE_INT32,
  1368. FieldDescriptor::TYPE_FLOAT);
  1369. TestValidDataForMapType(
  1370. FieldDescriptor::TYPE_INT32,
  1371. FieldDescriptor::TYPE_DOUBLE);
  1372. TestValidDataForMapType(
  1373. FieldDescriptor::TYPE_BOOL,
  1374. FieldDescriptor::TYPE_BOOL);
  1375. TestValidDataForMapType(
  1376. FieldDescriptor::TYPE_STRING,
  1377. FieldDescriptor::TYPE_STRING);
  1378. TestValidDataForMapType(
  1379. FieldDescriptor::TYPE_STRING,
  1380. FieldDescriptor::TYPE_BYTES);
  1381. TestValidDataForMapType(
  1382. FieldDescriptor::TYPE_STRING,
  1383. FieldDescriptor::TYPE_ENUM);
  1384. TestValidDataForMapType(
  1385. FieldDescriptor::TYPE_STRING,
  1386. FieldDescriptor::TYPE_MESSAGE);
  1387. // Additional test to check overwriting message value map.
  1388. TestOverwriteMessageValueMap();
  1389. TestValidDataForOneofType(FieldDescriptor::TYPE_UINT32);
  1390. TestValidDataForOneofType(FieldDescriptor::TYPE_BOOL);
  1391. TestValidDataForOneofType(FieldDescriptor::TYPE_UINT64);
  1392. TestValidDataForOneofType(FieldDescriptor::TYPE_FLOAT);
  1393. TestValidDataForOneofType(FieldDescriptor::TYPE_DOUBLE);
  1394. TestValidDataForOneofType(FieldDescriptor::TYPE_STRING);
  1395. TestValidDataForOneofType(FieldDescriptor::TYPE_BYTES);
  1396. TestValidDataForOneofType(FieldDescriptor::TYPE_ENUM);
  1397. TestValidDataForOneofType(FieldDescriptor::TYPE_MESSAGE);
  1398. // Additional test to check merging oneof message.
  1399. TestMergeOneofMessage();
  1400. // TODO(haberman):
  1401. // TestValidDataForType(FieldDescriptor::TYPE_GROUP
  1402. RunValidJsonTest("HelloWorld", REQUIRED,
  1403. "{\"optionalString\":\"Hello, World!\"}",
  1404. "optional_string: 'Hello, World!'");
  1405. // NOTE: The spec for JSON support is still being sorted out, these may not
  1406. // all be correct.
  1407. // Test field name conventions.
  1408. RunValidJsonTest(
  1409. "FieldNameInSnakeCase", REQUIRED,
  1410. R"({
  1411. "fieldname1": 1,
  1412. "fieldName2": 2,
  1413. "FieldName3": 3,
  1414. "fieldName4": 4
  1415. })",
  1416. R"(
  1417. fieldname1: 1
  1418. field_name2: 2
  1419. _field_name3: 3
  1420. field__name4_: 4
  1421. )");
  1422. RunValidJsonTest(
  1423. "FieldNameWithNumbers", REQUIRED,
  1424. R"({
  1425. "field0name5": 5,
  1426. "field0Name6": 6
  1427. })",
  1428. R"(
  1429. field0name5: 5
  1430. field_0_name6: 6
  1431. )");
  1432. RunValidJsonTest(
  1433. "FieldNameWithMixedCases", REQUIRED,
  1434. R"({
  1435. "fieldName7": 7,
  1436. "FieldName8": 8,
  1437. "fieldName9": 9,
  1438. "FieldName10": 10,
  1439. "FIELDNAME11": 11,
  1440. "FIELDName12": 12
  1441. })",
  1442. R"(
  1443. fieldName7: 7
  1444. FieldName8: 8
  1445. field_Name9: 9
  1446. Field_Name10: 10
  1447. FIELD_NAME11: 11
  1448. FIELD_name12: 12
  1449. )");
  1450. RunValidJsonTest(
  1451. "FieldNameWithDoubleUnderscores", RECOMMENDED,
  1452. R"({
  1453. "FieldName13": 13,
  1454. "FieldName14": 14,
  1455. "fieldName15": 15,
  1456. "fieldName16": 16,
  1457. "fieldName17": 17,
  1458. "FieldName18": 18
  1459. })",
  1460. R"(
  1461. __field_name13: 13
  1462. __Field_name14: 14
  1463. field__name15: 15
  1464. field__Name16: 16
  1465. field_name17__: 17
  1466. Field_name18__: 18
  1467. )");
  1468. // Using the original proto field name in JSON is also allowed.
  1469. RunValidJsonTest(
  1470. "OriginalProtoFieldName", REQUIRED,
  1471. R"({
  1472. "fieldname1": 1,
  1473. "field_name2": 2,
  1474. "_field_name3": 3,
  1475. "field__name4_": 4,
  1476. "field0name5": 5,
  1477. "field_0_name6": 6,
  1478. "fieldName7": 7,
  1479. "FieldName8": 8,
  1480. "field_Name9": 9,
  1481. "Field_Name10": 10,
  1482. "FIELD_NAME11": 11,
  1483. "FIELD_name12": 12,
  1484. "__field_name13": 13,
  1485. "__Field_name14": 14,
  1486. "field__name15": 15,
  1487. "field__Name16": 16,
  1488. "field_name17__": 17,
  1489. "Field_name18__": 18
  1490. })",
  1491. R"(
  1492. fieldname1: 1
  1493. field_name2: 2
  1494. _field_name3: 3
  1495. field__name4_: 4
  1496. field0name5: 5
  1497. field_0_name6: 6
  1498. fieldName7: 7
  1499. FieldName8: 8
  1500. field_Name9: 9
  1501. Field_Name10: 10
  1502. FIELD_NAME11: 11
  1503. FIELD_name12: 12
  1504. __field_name13: 13
  1505. __Field_name14: 14
  1506. field__name15: 15
  1507. field__Name16: 16
  1508. field_name17__: 17
  1509. Field_name18__: 18
  1510. )");
  1511. // Field names can be escaped.
  1512. RunValidJsonTest(
  1513. "FieldNameEscaped", REQUIRED,
  1514. R"({"fieldn\u0061me1": 1})",
  1515. "fieldname1: 1");
  1516. // String ends with escape character.
  1517. ExpectParseFailureForJson(
  1518. "StringEndsWithEscapeChar", RECOMMENDED,
  1519. "{\"optionalString\": \"abc\\");
  1520. // Field names must be quoted (or it's not valid JSON).
  1521. ExpectParseFailureForJson(
  1522. "FieldNameNotQuoted", RECOMMENDED,
  1523. "{fieldname1: 1}");
  1524. // Trailing comma is not allowed (not valid JSON).
  1525. ExpectParseFailureForJson(
  1526. "TrailingCommaInAnObject", RECOMMENDED,
  1527. R"({"fieldname1":1,})");
  1528. ExpectParseFailureForJson(
  1529. "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
  1530. R"({"fieldname1":1 ,})");
  1531. ExpectParseFailureForJson(
  1532. "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
  1533. R"({"fieldname1":1 , })");
  1534. ExpectParseFailureForJson(
  1535. "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
  1536. R"({
  1537. "fieldname1":1,
  1538. })");
  1539. // JSON doesn't support comments.
  1540. ExpectParseFailureForJson(
  1541. "JsonWithComments", RECOMMENDED,
  1542. R"({
  1543. // This is a comment.
  1544. "fieldname1": 1
  1545. })");
  1546. // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
  1547. RunValidJsonTest(
  1548. "OneLineNoSpaces", RECOMMENDED,
  1549. "{\"optionalInt32\":1,\"optionalInt64\":2}",
  1550. R"(
  1551. optional_int32: 1
  1552. optional_int64: 2
  1553. )");
  1554. RunValidJsonTest(
  1555. "OneLineWithSpaces", RECOMMENDED,
  1556. "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
  1557. R"(
  1558. optional_int32: 1
  1559. optional_int64: 2
  1560. )");
  1561. RunValidJsonTest(
  1562. "MultilineNoSpaces", RECOMMENDED,
  1563. "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
  1564. R"(
  1565. optional_int32: 1
  1566. optional_int64: 2
  1567. )");
  1568. RunValidJsonTest(
  1569. "MultilineWithSpaces", RECOMMENDED,
  1570. "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n",
  1571. R"(
  1572. optional_int32: 1
  1573. optional_int64: 2
  1574. )");
  1575. // Missing comma between key/value pairs.
  1576. ExpectParseFailureForJson(
  1577. "MissingCommaOneLine", RECOMMENDED,
  1578. "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
  1579. ExpectParseFailureForJson(
  1580. "MissingCommaMultiline", RECOMMENDED,
  1581. "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}");
  1582. // Duplicated field names are not allowed.
  1583. ExpectParseFailureForJson(
  1584. "FieldNameDuplicate", RECOMMENDED,
  1585. R"({
  1586. "optionalNestedMessage": {a: 1},
  1587. "optionalNestedMessage": {}
  1588. })");
  1589. ExpectParseFailureForJson(
  1590. "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
  1591. R"({
  1592. "optional_nested_message": {a: 1},
  1593. "optionalNestedMessage": {}
  1594. })");
  1595. ExpectParseFailureForJson(
  1596. "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
  1597. R"({
  1598. "optionalNestedMessage": {a: 1},
  1599. "optional_nested_message": {}
  1600. })");
  1601. // Serializers should use lowerCamelCase by default.
  1602. RunValidJsonTestWithValidator(
  1603. "FieldNameInLowerCamelCase", REQUIRED,
  1604. R"({
  1605. "fieldname1": 1,
  1606. "fieldName2": 2,
  1607. "FieldName3": 3,
  1608. "fieldName4": 4
  1609. })",
  1610. [](const Json::Value& value) {
  1611. return value.isMember("fieldname1") &&
  1612. value.isMember("fieldName2") &&
  1613. value.isMember("FieldName3") &&
  1614. value.isMember("fieldName4");
  1615. });
  1616. RunValidJsonTestWithValidator(
  1617. "FieldNameWithNumbers", REQUIRED,
  1618. R"({
  1619. "field0name5": 5,
  1620. "field0Name6": 6
  1621. })",
  1622. [](const Json::Value& value) {
  1623. return value.isMember("field0name5") &&
  1624. value.isMember("field0Name6");
  1625. });
  1626. RunValidJsonTestWithValidator(
  1627. "FieldNameWithMixedCases", REQUIRED,
  1628. R"({
  1629. "fieldName7": 7,
  1630. "FieldName8": 8,
  1631. "fieldName9": 9,
  1632. "FieldName10": 10,
  1633. "FIELDNAME11": 11,
  1634. "FIELDName12": 12
  1635. })",
  1636. [](const Json::Value& value) {
  1637. return value.isMember("fieldName7") &&
  1638. value.isMember("FieldName8") &&
  1639. value.isMember("fieldName9") &&
  1640. value.isMember("FieldName10") &&
  1641. value.isMember("FIELDNAME11") &&
  1642. value.isMember("FIELDName12");
  1643. });
  1644. RunValidJsonTestWithValidator(
  1645. "FieldNameWithDoubleUnderscores", RECOMMENDED,
  1646. R"({
  1647. "FieldName13": 13,
  1648. "FieldName14": 14,
  1649. "fieldName15": 15,
  1650. "fieldName16": 16,
  1651. "fieldName17": 17,
  1652. "FieldName18": 18
  1653. })",
  1654. [](const Json::Value& value) {
  1655. return value.isMember("FieldName13") &&
  1656. value.isMember("FieldName14") &&
  1657. value.isMember("fieldName15") &&
  1658. value.isMember("fieldName16") &&
  1659. value.isMember("fieldName17") &&
  1660. value.isMember("FieldName18");
  1661. });
  1662. // Integer fields.
  1663. RunValidJsonTest(
  1664. "Int32FieldMaxValue", REQUIRED,
  1665. R"({"optionalInt32": 2147483647})",
  1666. "optional_int32: 2147483647");
  1667. RunValidJsonTest(
  1668. "Int32FieldMinValue", REQUIRED,
  1669. R"({"optionalInt32": -2147483648})",
  1670. "optional_int32: -2147483648");
  1671. RunValidJsonTest(
  1672. "Uint32FieldMaxValue", REQUIRED,
  1673. R"({"optionalUint32": 4294967295})",
  1674. "optional_uint32: 4294967295");
  1675. RunValidJsonTest(
  1676. "Int64FieldMaxValue", REQUIRED,
  1677. R"({"optionalInt64": "9223372036854775807"})",
  1678. "optional_int64: 9223372036854775807");
  1679. RunValidJsonTest(
  1680. "Int64FieldMinValue", REQUIRED,
  1681. R"({"optionalInt64": "-9223372036854775808"})",
  1682. "optional_int64: -9223372036854775808");
  1683. RunValidJsonTest(
  1684. "Uint64FieldMaxValue", REQUIRED,
  1685. R"({"optionalUint64": "18446744073709551615"})",
  1686. "optional_uint64: 18446744073709551615");
  1687. // While not the largest Int64, this is the largest
  1688. // Int64 which can be exactly represented within an
  1689. // IEEE-754 64-bit float, which is the expected level
  1690. // of interoperability guarantee. Larger values may
  1691. // work in some implementations, but should not be
  1692. // relied upon.
  1693. RunValidJsonTest(
  1694. "Int64FieldMaxValueNotQuoted", REQUIRED,
  1695. R"({"optionalInt64": 9223372036854774784})",
  1696. "optional_int64: 9223372036854774784");
  1697. RunValidJsonTest(
  1698. "Int64FieldMinValueNotQuoted", REQUIRED,
  1699. R"({"optionalInt64": -9223372036854775808})",
  1700. "optional_int64: -9223372036854775808");
  1701. // Largest interoperable Uint64; see comment above
  1702. // for Int64FieldMaxValueNotQuoted.
  1703. RunValidJsonTest(
  1704. "Uint64FieldMaxValueNotQuoted", REQUIRED,
  1705. R"({"optionalUint64": 18446744073709549568})",
  1706. "optional_uint64: 18446744073709549568");
  1707. // Values can be represented as JSON strings.
  1708. RunValidJsonTest(
  1709. "Int32FieldStringValue", REQUIRED,
  1710. R"({"optionalInt32": "2147483647"})",
  1711. "optional_int32: 2147483647");
  1712. RunValidJsonTest(
  1713. "Int32FieldStringValueEscaped", REQUIRED,
  1714. R"({"optionalInt32": "2\u003147483647"})",
  1715. "optional_int32: 2147483647");
  1716. // Parsers reject out-of-bound integer values.
  1717. ExpectParseFailureForJson(
  1718. "Int32FieldTooLarge", REQUIRED,
  1719. R"({"optionalInt32": 2147483648})");
  1720. ExpectParseFailureForJson(
  1721. "Int32FieldTooSmall", REQUIRED,
  1722. R"({"optionalInt32": -2147483649})");
  1723. ExpectParseFailureForJson(
  1724. "Uint32FieldTooLarge", REQUIRED,
  1725. R"({"optionalUint32": 4294967296})");
  1726. ExpectParseFailureForJson(
  1727. "Int64FieldTooLarge", REQUIRED,
  1728. R"({"optionalInt64": "9223372036854775808"})");
  1729. ExpectParseFailureForJson(
  1730. "Int64FieldTooSmall", REQUIRED,
  1731. R"({"optionalInt64": "-9223372036854775809"})");
  1732. ExpectParseFailureForJson(
  1733. "Uint64FieldTooLarge", REQUIRED,
  1734. R"({"optionalUint64": "18446744073709551616"})");
  1735. // Parser reject non-integer numeric values as well.
  1736. ExpectParseFailureForJson(
  1737. "Int32FieldNotInteger", REQUIRED,
  1738. R"({"optionalInt32": 0.5})");
  1739. ExpectParseFailureForJson(
  1740. "Uint32FieldNotInteger", REQUIRED,
  1741. R"({"optionalUint32": 0.5})");
  1742. ExpectParseFailureForJson(
  1743. "Int64FieldNotInteger", REQUIRED,
  1744. R"({"optionalInt64": "0.5"})");
  1745. ExpectParseFailureForJson(
  1746. "Uint64FieldNotInteger", REQUIRED,
  1747. R"({"optionalUint64": "0.5"})");
  1748. // Integers but represented as float values are accepted.
  1749. RunValidJsonTest(
  1750. "Int32FieldFloatTrailingZero", REQUIRED,
  1751. R"({"optionalInt32": 100000.000})",
  1752. "optional_int32: 100000");
  1753. RunValidJsonTest(
  1754. "Int32FieldExponentialFormat", REQUIRED,
  1755. R"({"optionalInt32": 1e5})",
  1756. "optional_int32: 100000");
  1757. RunValidJsonTest(
  1758. "Int32FieldMaxFloatValue", REQUIRED,
  1759. R"({"optionalInt32": 2.147483647e9})",
  1760. "optional_int32: 2147483647");
  1761. RunValidJsonTest(
  1762. "Int32FieldMinFloatValue", REQUIRED,
  1763. R"({"optionalInt32": -2.147483648e9})",
  1764. "optional_int32: -2147483648");
  1765. RunValidJsonTest(
  1766. "Uint32FieldMaxFloatValue", REQUIRED,
  1767. R"({"optionalUint32": 4.294967295e9})",
  1768. "optional_uint32: 4294967295");
  1769. // Parser reject non-numeric values.
  1770. ExpectParseFailureForJson(
  1771. "Int32FieldNotNumber", REQUIRED,
  1772. R"({"optionalInt32": "3x3"})");
  1773. ExpectParseFailureForJson(
  1774. "Uint32FieldNotNumber", REQUIRED,
  1775. R"({"optionalUint32": "3x3"})");
  1776. ExpectParseFailureForJson(
  1777. "Int64FieldNotNumber", REQUIRED,
  1778. R"({"optionalInt64": "3x3"})");
  1779. ExpectParseFailureForJson(
  1780. "Uint64FieldNotNumber", REQUIRED,
  1781. R"({"optionalUint64": "3x3"})");
  1782. // JSON does not allow "+" on numric values.
  1783. ExpectParseFailureForJson(
  1784. "Int32FieldPlusSign", REQUIRED,
  1785. R"({"optionalInt32": +1})");
  1786. // JSON doesn't allow leading 0s.
  1787. ExpectParseFailureForJson(
  1788. "Int32FieldLeadingZero", REQUIRED,
  1789. R"({"optionalInt32": 01})");
  1790. ExpectParseFailureForJson(
  1791. "Int32FieldNegativeWithLeadingZero", REQUIRED,
  1792. R"({"optionalInt32": -01})");
  1793. // String values must follow the same syntax rule. Specifically leading
  1794. // or trailing spaces are not allowed.
  1795. ExpectParseFailureForJson(
  1796. "Int32FieldLeadingSpace", REQUIRED,
  1797. R"({"optionalInt32": " 1"})");
  1798. ExpectParseFailureForJson(
  1799. "Int32FieldTrailingSpace", REQUIRED,
  1800. R"({"optionalInt32": "1 "})");
  1801. // 64-bit values are serialized as strings.
  1802. RunValidJsonTestWithValidator(
  1803. "Int64FieldBeString", RECOMMENDED,
  1804. R"({"optionalInt64": 1})",
  1805. [](const Json::Value& value) {
  1806. return value["optionalInt64"].type() == Json::stringValue &&
  1807. value["optionalInt64"].asString() == "1";
  1808. });
  1809. RunValidJsonTestWithValidator(
  1810. "Uint64FieldBeString", RECOMMENDED,
  1811. R"({"optionalUint64": 1})",
  1812. [](const Json::Value& value) {
  1813. return value["optionalUint64"].type() == Json::stringValue &&
  1814. value["optionalUint64"].asString() == "1";
  1815. });
  1816. // Bool fields.
  1817. RunValidJsonTest(
  1818. "BoolFieldTrue", REQUIRED,
  1819. R"({"optionalBool":true})",
  1820. "optional_bool: true");
  1821. RunValidJsonTest(
  1822. "BoolFieldFalse", REQUIRED,
  1823. R"({"optionalBool":false})",
  1824. "optional_bool: false");
  1825. // Other forms are not allowed.
  1826. ExpectParseFailureForJson(
  1827. "BoolFieldIntegerZero", RECOMMENDED,
  1828. R"({"optionalBool":0})");
  1829. ExpectParseFailureForJson(
  1830. "BoolFieldIntegerOne", RECOMMENDED,
  1831. R"({"optionalBool":1})");
  1832. ExpectParseFailureForJson(
  1833. "BoolFieldCamelCaseTrue", RECOMMENDED,
  1834. R"({"optionalBool":True})");
  1835. ExpectParseFailureForJson(
  1836. "BoolFieldCamelCaseFalse", RECOMMENDED,
  1837. R"({"optionalBool":False})");
  1838. ExpectParseFailureForJson(
  1839. "BoolFieldAllCapitalTrue", RECOMMENDED,
  1840. R"({"optionalBool":TRUE})");
  1841. ExpectParseFailureForJson(
  1842. "BoolFieldAllCapitalFalse", RECOMMENDED,
  1843. R"({"optionalBool":FALSE})");
  1844. ExpectParseFailureForJson(
  1845. "BoolFieldDoubleQuotedTrue", RECOMMENDED,
  1846. R"({"optionalBool":"true"})");
  1847. ExpectParseFailureForJson(
  1848. "BoolFieldDoubleQuotedFalse", RECOMMENDED,
  1849. R"({"optionalBool":"false"})");
  1850. // Float fields.
  1851. RunValidJsonTest(
  1852. "FloatFieldMinPositiveValue", REQUIRED,
  1853. R"({"optionalFloat": 1.175494e-38})",
  1854. "optional_float: 1.175494e-38");
  1855. RunValidJsonTest(
  1856. "FloatFieldMaxNegativeValue", REQUIRED,
  1857. R"({"optionalFloat": -1.175494e-38})",
  1858. "optional_float: -1.175494e-38");
  1859. RunValidJsonTest(
  1860. "FloatFieldMaxPositiveValue", REQUIRED,
  1861. R"({"optionalFloat": 3.402823e+38})",
  1862. "optional_float: 3.402823e+38");
  1863. RunValidJsonTest(
  1864. "FloatFieldMinNegativeValue", REQUIRED,
  1865. R"({"optionalFloat": 3.402823e+38})",
  1866. "optional_float: 3.402823e+38");
  1867. // Values can be quoted.
  1868. RunValidJsonTest(
  1869. "FloatFieldQuotedValue", REQUIRED,
  1870. R"({"optionalFloat": "1"})",
  1871. "optional_float: 1");
  1872. // Special values.
  1873. RunValidJsonTest(
  1874. "FloatFieldNan", REQUIRED,
  1875. R"({"optionalFloat": "NaN"})",
  1876. "optional_float: nan");
  1877. RunValidJsonTest(
  1878. "FloatFieldInfinity", REQUIRED,
  1879. R"({"optionalFloat": "Infinity"})",
  1880. "optional_float: inf");
  1881. RunValidJsonTest(
  1882. "FloatFieldNegativeInfinity", REQUIRED,
  1883. R"({"optionalFloat": "-Infinity"})",
  1884. "optional_float: -inf");
  1885. // Non-cannonical Nan will be correctly normalized.
  1886. {
  1887. TestAllTypesProto3 message;
  1888. // IEEE floating-point standard 32-bit quiet NaN:
  1889. // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
  1890. message.set_optional_float(
  1891. WireFormatLite::DecodeFloat(0x7FA12345));
  1892. RunValidJsonTestWithProtobufInput(
  1893. "FloatFieldNormalizeQuietNan", REQUIRED, message,
  1894. "optional_float: nan");
  1895. // IEEE floating-point standard 64-bit signaling NaN:
  1896. // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
  1897. message.set_optional_float(
  1898. WireFormatLite::DecodeFloat(0xFFB54321));
  1899. RunValidJsonTestWithProtobufInput(
  1900. "FloatFieldNormalizeSignalingNan", REQUIRED, message,
  1901. "optional_float: nan");
  1902. }
  1903. // Special values must be quoted.
  1904. ExpectParseFailureForJson(
  1905. "FloatFieldNanNotQuoted", RECOMMENDED,
  1906. R"({"optionalFloat": NaN})");
  1907. ExpectParseFailureForJson(
  1908. "FloatFieldInfinityNotQuoted", RECOMMENDED,
  1909. R"({"optionalFloat": Infinity})");
  1910. ExpectParseFailureForJson(
  1911. "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
  1912. R"({"optionalFloat": -Infinity})");
  1913. // Parsers should reject out-of-bound values.
  1914. ExpectParseFailureForJson(
  1915. "FloatFieldTooSmall", REQUIRED,
  1916. R"({"optionalFloat": -3.502823e+38})");
  1917. ExpectParseFailureForJson(
  1918. "FloatFieldTooLarge", REQUIRED,
  1919. R"({"optionalFloat": 3.502823e+38})");
  1920. // Double fields.
  1921. RunValidJsonTest(
  1922. "DoubleFieldMinPositiveValue", REQUIRED,
  1923. R"({"optionalDouble": 2.22507e-308})",
  1924. "optional_double: 2.22507e-308");
  1925. RunValidJsonTest(
  1926. "DoubleFieldMaxNegativeValue", REQUIRED,
  1927. R"({"optionalDouble": -2.22507e-308})",
  1928. "optional_double: -2.22507e-308");
  1929. RunValidJsonTest(
  1930. "DoubleFieldMaxPositiveValue", REQUIRED,
  1931. R"({"optionalDouble": 1.79769e+308})",
  1932. "optional_double: 1.79769e+308");
  1933. RunValidJsonTest(
  1934. "DoubleFieldMinNegativeValue", REQUIRED,
  1935. R"({"optionalDouble": -1.79769e+308})",
  1936. "optional_double: -1.79769e+308");
  1937. // Values can be quoted.
  1938. RunValidJsonTest(
  1939. "DoubleFieldQuotedValue", REQUIRED,
  1940. R"({"optionalDouble": "1"})",
  1941. "optional_double: 1");
  1942. // Speical values.
  1943. RunValidJsonTest(
  1944. "DoubleFieldNan", REQUIRED,
  1945. R"({"optionalDouble": "NaN"})",
  1946. "optional_double: nan");
  1947. RunValidJsonTest(
  1948. "DoubleFieldInfinity", REQUIRED,
  1949. R"({"optionalDouble": "Infinity"})",
  1950. "optional_double: inf");
  1951. RunValidJsonTest(
  1952. "DoubleFieldNegativeInfinity", REQUIRED,
  1953. R"({"optionalDouble": "-Infinity"})",
  1954. "optional_double: -inf");
  1955. // Non-cannonical Nan will be correctly normalized.
  1956. {
  1957. TestAllTypesProto3 message;
  1958. message.set_optional_double(
  1959. WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
  1960. RunValidJsonTestWithProtobufInput(
  1961. "DoubleFieldNormalizeQuietNan", REQUIRED, message,
  1962. "optional_double: nan");
  1963. message.set_optional_double(
  1964. WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
  1965. RunValidJsonTestWithProtobufInput(
  1966. "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
  1967. "optional_double: nan");
  1968. }
  1969. // Special values must be quoted.
  1970. ExpectParseFailureForJson(
  1971. "DoubleFieldNanNotQuoted", RECOMMENDED,
  1972. R"({"optionalDouble": NaN})");
  1973. ExpectParseFailureForJson(
  1974. "DoubleFieldInfinityNotQuoted", RECOMMENDED,
  1975. R"({"optionalDouble": Infinity})");
  1976. ExpectParseFailureForJson(
  1977. "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
  1978. R"({"optionalDouble": -Infinity})");
  1979. // Parsers should reject out-of-bound values.
  1980. ExpectParseFailureForJson(
  1981. "DoubleFieldTooSmall", REQUIRED,
  1982. R"({"optionalDouble": -1.89769e+308})");
  1983. ExpectParseFailureForJson(
  1984. "DoubleFieldTooLarge", REQUIRED,
  1985. R"({"optionalDouble": +1.89769e+308})");
  1986. // Enum fields.
  1987. RunValidJsonTest(
  1988. "EnumField", REQUIRED,
  1989. R"({"optionalNestedEnum": "FOO"})",
  1990. "optional_nested_enum: FOO");
  1991. // Enum fields with alias
  1992. RunValidJsonTest(
  1993. "EnumFieldWithAlias", REQUIRED,
  1994. R"({"optionalAliasedEnum": "ALIAS_BAZ"})",
  1995. "optional_aliased_enum: ALIAS_BAZ");
  1996. RunValidJsonTest(
  1997. "EnumFieldWithAliasUseAlias", REQUIRED,
  1998. R"({"optionalAliasedEnum": "QUX"})",
  1999. "optional_aliased_enum: ALIAS_BAZ");
  2000. RunValidJsonTest(
  2001. "EnumFieldWithAliasLowerCase", REQUIRED,
  2002. R"({"optionalAliasedEnum": "qux"})",
  2003. "optional_aliased_enum: ALIAS_BAZ");
  2004. RunValidJsonTest(
  2005. "EnumFieldWithAliasDifferentCase", REQUIRED,
  2006. R"({"optionalAliasedEnum": "bAz"})",
  2007. "optional_aliased_enum: ALIAS_BAZ");
  2008. // Enum values must be represented as strings.
  2009. ExpectParseFailureForJson(
  2010. "EnumFieldNotQuoted", REQUIRED,
  2011. R"({"optionalNestedEnum": FOO})");
  2012. // Numeric values are allowed.
  2013. RunValidJsonTest(
  2014. "EnumFieldNumericValueZero", REQUIRED,
  2015. R"({"optionalNestedEnum": 0})",
  2016. "optional_nested_enum: FOO");
  2017. RunValidJsonTest(
  2018. "EnumFieldNumericValueNonZero", REQUIRED,
  2019. R"({"optionalNestedEnum": 1})",
  2020. "optional_nested_enum: BAR");
  2021. // Unknown enum values are represented as numeric values.
  2022. RunValidJsonTestWithValidator(
  2023. "EnumFieldUnknownValue", REQUIRED,
  2024. R"({"optionalNestedEnum": 123})",
  2025. [](const Json::Value& value) {
  2026. return value["optionalNestedEnum"].type() == Json::intValue &&
  2027. value["optionalNestedEnum"].asInt() == 123;
  2028. });
  2029. // String fields.
  2030. RunValidJsonTest(
  2031. "StringField", REQUIRED,
  2032. R"({"optionalString": "Hello world!"})",
  2033. "optional_string: \"Hello world!\"");
  2034. RunValidJsonTest(
  2035. "StringFieldUnicode", REQUIRED,
  2036. // Google in Chinese.
  2037. R"({"optionalString": "谷歌"})",
  2038. R"(optional_string: "谷歌")");
  2039. RunValidJsonTest(
  2040. "StringFieldEscape", REQUIRED,
  2041. R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
  2042. R"(optional_string: "\"\\/\b\f\n\r\t")");
  2043. RunValidJsonTest(
  2044. "StringFieldUnicodeEscape", REQUIRED,
  2045. R"({"optionalString": "\u8C37\u6B4C"})",
  2046. R"(optional_string: "谷歌")");
  2047. RunValidJsonTest(
  2048. "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
  2049. R"({"optionalString": "\u8c37\u6b4c"})",
  2050. R"(optional_string: "谷歌")");
  2051. RunValidJsonTest(
  2052. "StringFieldSurrogatePair", REQUIRED,
  2053. // The character is an emoji: grinning face with smiling eyes. 😁
  2054. R"({"optionalString": "\uD83D\uDE01"})",
  2055. R"(optional_string: "\xF0\x9F\x98\x81")");
  2056. // Unicode escapes must start with "\u" (lowercase u).
  2057. ExpectParseFailureForJson(
  2058. "StringFieldUppercaseEscapeLetter", RECOMMENDED,
  2059. R"({"optionalString": "\U8C37\U6b4C"})");
  2060. ExpectParseFailureForJson(
  2061. "StringFieldInvalidEscape", RECOMMENDED,
  2062. R"({"optionalString": "\uXXXX\u6B4C"})");
  2063. ExpectParseFailureForJson(
  2064. "StringFieldUnterminatedEscape", RECOMMENDED,
  2065. R"({"optionalString": "\u8C3"})");
  2066. ExpectParseFailureForJson(
  2067. "StringFieldUnpairedHighSurrogate", RECOMMENDED,
  2068. R"({"optionalString": "\uD800"})");
  2069. ExpectParseFailureForJson(
  2070. "StringFieldUnpairedLowSurrogate", RECOMMENDED,
  2071. R"({"optionalString": "\uDC00"})");
  2072. ExpectParseFailureForJson(
  2073. "StringFieldSurrogateInWrongOrder", RECOMMENDED,
  2074. R"({"optionalString": "\uDE01\uD83D"})");
  2075. ExpectParseFailureForJson(
  2076. "StringFieldNotAString", REQUIRED,
  2077. R"({"optionalString": 12345})");
  2078. // Bytes fields.
  2079. RunValidJsonTest(
  2080. "BytesField", REQUIRED,
  2081. R"({"optionalBytes": "AQI="})",
  2082. R"(optional_bytes: "\x01\x02")");
  2083. RunValidJsonTest(
  2084. "BytesFieldBase64Url", RECOMMENDED,
  2085. R"({"optionalBytes": "-_"})",
  2086. R"(optional_bytes: "\xfb")");
  2087. // Message fields.
  2088. RunValidJsonTest(
  2089. "MessageField", REQUIRED,
  2090. R"({"optionalNestedMessage": {"a": 1234}})",
  2091. "optional_nested_message: {a: 1234}");
  2092. // Oneof fields.
  2093. ExpectParseFailureForJson(
  2094. "OneofFieldDuplicate", REQUIRED,
  2095. R"({"oneofUint32": 1, "oneofString": "test"})");
  2096. // Ensure zero values for oneof make it out/backs.
  2097. TestAllTypesProto3 messageProto3;
  2098. TestAllTypesProto2 messageProto2;
  2099. TestOneofMessage(messageProto3, true);
  2100. TestOneofMessage(messageProto2, false);
  2101. RunValidJsonTest(
  2102. "OneofZeroUint32", RECOMMENDED,
  2103. R"({"oneofUint32": 0})", "oneof_uint32: 0");
  2104. RunValidJsonTest(
  2105. "OneofZeroMessage", RECOMMENDED,
  2106. R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
  2107. RunValidJsonTest(
  2108. "OneofZeroString", RECOMMENDED,
  2109. R"({"oneofString": ""})", "oneof_string: \"\"");
  2110. RunValidJsonTest(
  2111. "OneofZeroBytes", RECOMMENDED,
  2112. R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
  2113. RunValidJsonTest(
  2114. "OneofZeroBool", RECOMMENDED,
  2115. R"({"oneofBool": false})", "oneof_bool: false");
  2116. RunValidJsonTest(
  2117. "OneofZeroUint64", RECOMMENDED,
  2118. R"({"oneofUint64": 0})", "oneof_uint64: 0");
  2119. RunValidJsonTest(
  2120. "OneofZeroFloat", RECOMMENDED,
  2121. R"({"oneofFloat": 0.0})", "oneof_float: 0");
  2122. RunValidJsonTest(
  2123. "OneofZeroDouble", RECOMMENDED,
  2124. R"({"oneofDouble": 0.0})", "oneof_double: 0");
  2125. RunValidJsonTest(
  2126. "OneofZeroEnum", RECOMMENDED,
  2127. R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
  2128. // Repeated fields.
  2129. RunValidJsonTest(
  2130. "PrimitiveRepeatedField", REQUIRED,
  2131. R"({"repeatedInt32": [1, 2, 3, 4]})",
  2132. "repeated_int32: [1, 2, 3, 4]");
  2133. RunValidJsonTest(
  2134. "EnumRepeatedField", REQUIRED,
  2135. R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
  2136. "repeated_nested_enum: [FOO, BAR, BAZ]");
  2137. RunValidJsonTest(
  2138. "StringRepeatedField", REQUIRED,
  2139. R"({"repeatedString": ["Hello", "world"]})",
  2140. R"(repeated_string: ["Hello", "world"])");
  2141. RunValidJsonTest(
  2142. "BytesRepeatedField", REQUIRED,
  2143. R"({"repeatedBytes": ["AAEC", "AQI="]})",
  2144. R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
  2145. RunValidJsonTest(
  2146. "MessageRepeatedField", REQUIRED,
  2147. R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
  2148. "repeated_nested_message: {a: 1234}"
  2149. "repeated_nested_message: {a: 5678}");
  2150. // Repeated field elements are of incorrect type.
  2151. ExpectParseFailureForJson(
  2152. "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
  2153. R"({"repeatedInt32": [1, false, 3, 4]})");
  2154. ExpectParseFailureForJson(
  2155. "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
  2156. R"({"repeatedInt32": [1, 2, "name", 4]})");
  2157. ExpectParseFailureForJson(
  2158. "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
  2159. R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
  2160. ExpectParseFailureForJson(
  2161. "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
  2162. R"({"repeatedString": ["1", 2, "3", "4"]})");
  2163. ExpectParseFailureForJson(
  2164. "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
  2165. R"({"repeatedString": ["1", "2", false, "4"]})");
  2166. ExpectParseFailureForJson(
  2167. "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
  2168. R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
  2169. ExpectParseFailureForJson(
  2170. "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
  2171. R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
  2172. ExpectParseFailureForJson(
  2173. "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
  2174. R"({"repeatedNestedMessage": [{"a": 1}, false]})");
  2175. ExpectParseFailureForJson(
  2176. "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
  2177. R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
  2178. // Trailing comma in the repeated field is not allowed.
  2179. ExpectParseFailureForJson(
  2180. "RepeatedFieldTrailingComma", RECOMMENDED,
  2181. R"({"repeatedInt32": [1, 2, 3, 4,]})");
  2182. ExpectParseFailureForJson(
  2183. "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
  2184. "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
  2185. ExpectParseFailureForJson(
  2186. "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
  2187. "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
  2188. ExpectParseFailureForJson(
  2189. "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
  2190. "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}");
  2191. // Map fields.
  2192. RunValidJsonTest(
  2193. "Int32MapField", REQUIRED,
  2194. R"({"mapInt32Int32": {"1": 2, "3": 4}})",
  2195. "map_int32_int32: {key: 1 value: 2}"
  2196. "map_int32_int32: {key: 3 value: 4}");
  2197. ExpectParseFailureForJson(
  2198. "Int32MapFieldKeyNotQuoted", RECOMMENDED,
  2199. R"({"mapInt32Int32": {1: 2, 3: 4}})");
  2200. RunValidJsonTest(
  2201. "Uint32MapField", REQUIRED,
  2202. R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
  2203. "map_uint32_uint32: {key: 1 value: 2}"
  2204. "map_uint32_uint32: {key: 3 value: 4}");
  2205. ExpectParseFailureForJson(
  2206. "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
  2207. R"({"mapUint32Uint32": {1: 2, 3: 4}})");
  2208. RunValidJsonTest(
  2209. "Int64MapField", REQUIRED,
  2210. R"({"mapInt64Int64": {"1": 2, "3": 4}})",
  2211. "map_int64_int64: {key: 1 value: 2}"
  2212. "map_int64_int64: {key: 3 value: 4}");
  2213. ExpectParseFailureForJson(
  2214. "Int64MapFieldKeyNotQuoted", RECOMMENDED,
  2215. R"({"mapInt64Int64": {1: 2, 3: 4}})");
  2216. RunValidJsonTest(
  2217. "Uint64MapField", REQUIRED,
  2218. R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
  2219. "map_uint64_uint64: {key: 1 value: 2}"
  2220. "map_uint64_uint64: {key: 3 value: 4}");
  2221. ExpectParseFailureForJson(
  2222. "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
  2223. R"({"mapUint64Uint64": {1: 2, 3: 4}})");
  2224. RunValidJsonTest(
  2225. "BoolMapField", REQUIRED,
  2226. R"({"mapBoolBool": {"true": true, "false": false}})",
  2227. "map_bool_bool: {key: true value: true}"
  2228. "map_bool_bool: {key: false value: false}");
  2229. ExpectParseFailureForJson(
  2230. "BoolMapFieldKeyNotQuoted", RECOMMENDED,
  2231. R"({"mapBoolBool": {true: true, false: false}})");
  2232. RunValidJsonTest(
  2233. "MessageMapField", REQUIRED,
  2234. R"({
  2235. "mapStringNestedMessage": {
  2236. "hello": {"a": 1234},
  2237. "world": {"a": 5678}
  2238. }
  2239. })",
  2240. R"(
  2241. map_string_nested_message: {
  2242. key: "hello"
  2243. value: {a: 1234}
  2244. }
  2245. map_string_nested_message: {
  2246. key: "world"
  2247. value: {a: 5678}
  2248. }
  2249. )");
  2250. // Since Map keys are represented as JSON strings, escaping should be allowed.
  2251. RunValidJsonTest(
  2252. "Int32MapEscapedKey", REQUIRED,
  2253. R"({"mapInt32Int32": {"\u0031": 2}})",
  2254. "map_int32_int32: {key: 1 value: 2}");
  2255. RunValidJsonTest(
  2256. "Int64MapEscapedKey", REQUIRED,
  2257. R"({"mapInt64Int64": {"\u0031": 2}})",
  2258. "map_int64_int64: {key: 1 value: 2}");
  2259. RunValidJsonTest(
  2260. "BoolMapEscapedKey", REQUIRED,
  2261. R"({"mapBoolBool": {"tr\u0075e": true}})",
  2262. "map_bool_bool: {key: true value: true}");
  2263. // "null" is accepted for all fields types.
  2264. RunValidJsonTest(
  2265. "AllFieldAcceptNull", REQUIRED,
  2266. R"({
  2267. "optionalInt32": null,
  2268. "optionalInt64": null,
  2269. "optionalUint32": null,
  2270. "optionalUint64": null,
  2271. "optionalSint32": null,
  2272. "optionalSint64": null,
  2273. "optionalFixed32": null,
  2274. "optionalFixed64": null,
  2275. "optionalSfixed32": null,
  2276. "optionalSfixed64": null,
  2277. "optionalFloat": null,
  2278. "optionalDouble": null,
  2279. "optionalBool": null,
  2280. "optionalString": null,
  2281. "optionalBytes": null,
  2282. "optionalNestedEnum": null,
  2283. "optionalNestedMessage": null,
  2284. "repeatedInt32": null,
  2285. "repeatedInt64": null,
  2286. "repeatedUint32": null,
  2287. "repeatedUint64": null,
  2288. "repeatedSint32": null,
  2289. "repeatedSint64": null,
  2290. "repeatedFixed32": null,
  2291. "repeatedFixed64": null,
  2292. "repeatedSfixed32": null,
  2293. "repeatedSfixed64": null,
  2294. "repeatedFloat": null,
  2295. "repeatedDouble": null,
  2296. "repeatedBool": null,
  2297. "repeatedString": null,
  2298. "repeatedBytes": null,
  2299. "repeatedNestedEnum": null,
  2300. "repeatedNestedMessage": null,
  2301. "mapInt32Int32": null,
  2302. "mapBoolBool": null,
  2303. "mapStringNestedMessage": null
  2304. })",
  2305. "");
  2306. // Repeated field elements cannot be null.
  2307. ExpectParseFailureForJson(
  2308. "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
  2309. R"({"repeatedInt32": [1, null, 2]})");
  2310. ExpectParseFailureForJson(
  2311. "RepeatedFieldMessageElementIsNull", RECOMMENDED,
  2312. R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
  2313. // Map field keys cannot be null.
  2314. ExpectParseFailureForJson(
  2315. "MapFieldKeyIsNull", RECOMMENDED,
  2316. R"({"mapInt32Int32": {null: 1}})");
  2317. // Map field values cannot be null.
  2318. ExpectParseFailureForJson(
  2319. "MapFieldValueIsNull", RECOMMENDED,
  2320. R"({"mapInt32Int32": {"0": null}})");
  2321. // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
  2322. // quotes.
  2323. ExpectParseFailureForJson(
  2324. "StringFieldSingleQuoteKey", RECOMMENDED,
  2325. R"({'optionalString': "Hello world!"})");
  2326. ExpectParseFailureForJson(
  2327. "StringFieldSingleQuoteValue", RECOMMENDED,
  2328. R"({"optionalString": 'Hello world!'})");
  2329. ExpectParseFailureForJson(
  2330. "StringFieldSingleQuoteBoth", RECOMMENDED,
  2331. R"({'optionalString': 'Hello world!'})");
  2332. // Unknown fields.
  2333. {
  2334. TestAllTypesProto3 messageProto3;
  2335. TestAllTypesProto2 messageProto2;
  2336. //TODO(yilunchong): update this behavior when unknown field's behavior
  2337. // changed in open source. Also delete
  2338. // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput
  2339. // from failure list of python_cpp python java
  2340. TestUnknownMessage(messageProto3, true);
  2341. TestUnknownMessage(messageProto2, false);
  2342. }
  2343. // Wrapper types.
  2344. RunValidJsonTest(
  2345. "OptionalBoolWrapper", REQUIRED,
  2346. R"({"optionalBoolWrapper": false})",
  2347. "optional_bool_wrapper: {value: false}");
  2348. RunValidJsonTest(
  2349. "OptionalInt32Wrapper", REQUIRED,
  2350. R"({"optionalInt32Wrapper": 0})",
  2351. "optional_int32_wrapper: {value: 0}");
  2352. RunValidJsonTest(
  2353. "OptionalUint32Wrapper", REQUIRED,
  2354. R"({"optionalUint32Wrapper": 0})",
  2355. "optional_uint32_wrapper: {value: 0}");
  2356. RunValidJsonTest(
  2357. "OptionalInt64Wrapper", REQUIRED,
  2358. R"({"optionalInt64Wrapper": 0})",
  2359. "optional_int64_wrapper: {value: 0}");
  2360. RunValidJsonTest(
  2361. "OptionalUint64Wrapper", REQUIRED,
  2362. R"({"optionalUint64Wrapper": 0})",
  2363. "optional_uint64_wrapper: {value: 0}");
  2364. RunValidJsonTest(
  2365. "OptionalFloatWrapper", REQUIRED,
  2366. R"({"optionalFloatWrapper": 0})",
  2367. "optional_float_wrapper: {value: 0}");
  2368. RunValidJsonTest(
  2369. "OptionalDoubleWrapper", REQUIRED,
  2370. R"({"optionalDoubleWrapper": 0})",
  2371. "optional_double_wrapper: {value: 0}");
  2372. RunValidJsonTest(
  2373. "OptionalStringWrapper", REQUIRED,
  2374. R"({"optionalStringWrapper": ""})",
  2375. R"(optional_string_wrapper: {value: ""})");
  2376. RunValidJsonTest(
  2377. "OptionalBytesWrapper", REQUIRED,
  2378. R"({"optionalBytesWrapper": ""})",
  2379. R"(optional_bytes_wrapper: {value: ""})");
  2380. RunValidJsonTest(
  2381. "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
  2382. R"({
  2383. "optionalBoolWrapper": true,
  2384. "optionalInt32Wrapper": 1,
  2385. "optionalUint32Wrapper": 1,
  2386. "optionalInt64Wrapper": "1",
  2387. "optionalUint64Wrapper": "1",
  2388. "optionalFloatWrapper": 1,
  2389. "optionalDoubleWrapper": 1,
  2390. "optionalStringWrapper": "1",
  2391. "optionalBytesWrapper": "AQI="
  2392. })",
  2393. R"(
  2394. optional_bool_wrapper: {value: true}
  2395. optional_int32_wrapper: {value: 1}
  2396. optional_uint32_wrapper: {value: 1}
  2397. optional_int64_wrapper: {value: 1}
  2398. optional_uint64_wrapper: {value: 1}
  2399. optional_float_wrapper: {value: 1}
  2400. optional_double_wrapper: {value: 1}
  2401. optional_string_wrapper: {value: "1"}
  2402. optional_bytes_wrapper: {value: "\x01\x02"}
  2403. )");
  2404. RunValidJsonTest(
  2405. "RepeatedBoolWrapper", REQUIRED,
  2406. R"({"repeatedBoolWrapper": [true, false]})",
  2407. "repeated_bool_wrapper: {value: true}"
  2408. "repeated_bool_wrapper: {value: false}");
  2409. RunValidJsonTest(
  2410. "RepeatedInt32Wrapper", REQUIRED,
  2411. R"({"repeatedInt32Wrapper": [0, 1]})",
  2412. "repeated_int32_wrapper: {value: 0}"
  2413. "repeated_int32_wrapper: {value: 1}");
  2414. RunValidJsonTest(
  2415. "RepeatedUint32Wrapper", REQUIRED,
  2416. R"({"repeatedUint32Wrapper": [0, 1]})",
  2417. "repeated_uint32_wrapper: {value: 0}"
  2418. "repeated_uint32_wrapper: {value: 1}");
  2419. RunValidJsonTest(
  2420. "RepeatedInt64Wrapper", REQUIRED,
  2421. R"({"repeatedInt64Wrapper": [0, 1]})",
  2422. "repeated_int64_wrapper: {value: 0}"
  2423. "repeated_int64_wrapper: {value: 1}");
  2424. RunValidJsonTest(
  2425. "RepeatedUint64Wrapper", REQUIRED,
  2426. R"({"repeatedUint64Wrapper": [0, 1]})",
  2427. "repeated_uint64_wrapper: {value: 0}"
  2428. "repeated_uint64_wrapper: {value: 1}");
  2429. RunValidJsonTest(
  2430. "RepeatedFloatWrapper", REQUIRED,
  2431. R"({"repeatedFloatWrapper": [0, 1]})",
  2432. "repeated_float_wrapper: {value: 0}"
  2433. "repeated_float_wrapper: {value: 1}");
  2434. RunValidJsonTest(
  2435. "RepeatedDoubleWrapper", REQUIRED,
  2436. R"({"repeatedDoubleWrapper": [0, 1]})",
  2437. "repeated_double_wrapper: {value: 0}"
  2438. "repeated_double_wrapper: {value: 1}");
  2439. RunValidJsonTest(
  2440. "RepeatedStringWrapper", REQUIRED,
  2441. R"({"repeatedStringWrapper": ["", "AQI="]})",
  2442. R"(
  2443. repeated_string_wrapper: {value: ""}
  2444. repeated_string_wrapper: {value: "AQI="}
  2445. )");
  2446. RunValidJsonTest(
  2447. "RepeatedBytesWrapper", REQUIRED,
  2448. R"({"repeatedBytesWrapper": ["", "AQI="]})",
  2449. R"(
  2450. repeated_bytes_wrapper: {value: ""}
  2451. repeated_bytes_wrapper: {value: "\x01\x02"}
  2452. )");
  2453. RunValidJsonTest(
  2454. "WrapperTypesWithNullValue", REQUIRED,
  2455. R"({
  2456. "optionalBoolWrapper": null,
  2457. "optionalInt32Wrapper": null,
  2458. "optionalUint32Wrapper": null,
  2459. "optionalInt64Wrapper": null,
  2460. "optionalUint64Wrapper": null,
  2461. "optionalFloatWrapper": null,
  2462. "optionalDoubleWrapper": null,
  2463. "optionalStringWrapper": null,
  2464. "optionalBytesWrapper": null,
  2465. "repeatedBoolWrapper": null,
  2466. "repeatedInt32Wrapper": null,
  2467. "repeatedUint32Wrapper": null,
  2468. "repeatedInt64Wrapper": null,
  2469. "repeatedUint64Wrapper": null,
  2470. "repeatedFloatWrapper": null,
  2471. "repeatedDoubleWrapper": null,
  2472. "repeatedStringWrapper": null,
  2473. "repeatedBytesWrapper": null
  2474. })",
  2475. "");
  2476. // Duration
  2477. RunValidJsonTest(
  2478. "DurationMinValue", REQUIRED,
  2479. R"({"optionalDuration": "-315576000000.999999999s"})",
  2480. "optional_duration: {seconds: -315576000000 nanos: -999999999}");
  2481. RunValidJsonTest(
  2482. "DurationMaxValue", REQUIRED,
  2483. R"({"optionalDuration": "315576000000.999999999s"})",
  2484. "optional_duration: {seconds: 315576000000 nanos: 999999999}");
  2485. RunValidJsonTest(
  2486. "DurationRepeatedValue", REQUIRED,
  2487. R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
  2488. "repeated_duration: {seconds: 1 nanos: 500000000}"
  2489. "repeated_duration: {seconds: -1 nanos: -500000000}");
  2490. RunValidJsonTest(
  2491. "DurationNull", REQUIRED,
  2492. R"({"optionalDuration": null})",
  2493. "");
  2494. ExpectParseFailureForJson(
  2495. "DurationMissingS", REQUIRED,
  2496. R"({"optionalDuration": "1"})");
  2497. ExpectParseFailureForJson(
  2498. "DurationJsonInputTooSmall", REQUIRED,
  2499. R"({"optionalDuration": "-315576000001.000000000s"})");
  2500. ExpectParseFailureForJson(
  2501. "DurationJsonInputTooLarge", REQUIRED,
  2502. R"({"optionalDuration": "315576000001.000000000s"})");
  2503. ExpectSerializeFailureForJson(
  2504. "DurationProtoInputTooSmall", REQUIRED,
  2505. "optional_duration: {seconds: -315576000001 nanos: 0}");
  2506. ExpectSerializeFailureForJson(
  2507. "DurationProtoInputTooLarge", REQUIRED,
  2508. "optional_duration: {seconds: 315576000001 nanos: 0}");
  2509. RunValidJsonTestWithValidator(
  2510. "DurationHasZeroFractionalDigit", RECOMMENDED,
  2511. R"({"optionalDuration": "1.000000000s"})",
  2512. [](const Json::Value& value) {
  2513. return value["optionalDuration"].asString() == "1s";
  2514. });
  2515. RunValidJsonTestWithValidator(
  2516. "DurationHas3FractionalDigits", RECOMMENDED,
  2517. R"({"optionalDuration": "1.010000000s"})",
  2518. [](const Json::Value& value) {
  2519. return value["optionalDuration"].asString() == "1.010s";
  2520. });
  2521. RunValidJsonTestWithValidator(
  2522. "DurationHas6FractionalDigits", RECOMMENDED,
  2523. R"({"optionalDuration": "1.000010000s"})",
  2524. [](const Json::Value& value) {
  2525. return value["optionalDuration"].asString() == "1.000010s";
  2526. });
  2527. RunValidJsonTestWithValidator(
  2528. "DurationHas9FractionalDigits", RECOMMENDED,
  2529. R"({"optionalDuration": "1.000000010s"})",
  2530. [](const Json::Value& value) {
  2531. return value["optionalDuration"].asString() == "1.000000010s";
  2532. });
  2533. // Timestamp
  2534. RunValidJsonTest(
  2535. "TimestampMinValue", REQUIRED,
  2536. R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
  2537. "optional_timestamp: {seconds: -62135596800}");
  2538. RunValidJsonTest(
  2539. "TimestampMaxValue", REQUIRED,
  2540. R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
  2541. "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
  2542. RunValidJsonTest(
  2543. "TimestampRepeatedValue", REQUIRED,
  2544. R"({
  2545. "repeatedTimestamp": [
  2546. "0001-01-01T00:00:00Z",
  2547. "9999-12-31T23:59:59.999999999Z"
  2548. ]
  2549. })",
  2550. "repeated_timestamp: {seconds: -62135596800}"
  2551. "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
  2552. RunValidJsonTest("TimestampWithPositiveOffset", REQUIRED,
  2553. R"({"optionalTimestamp": "1970-01-01T08:00:01+08:00"})",
  2554. "optional_timestamp: {seconds: 1}");
  2555. RunValidJsonTest("TimestampWithNegativeOffset", REQUIRED,
  2556. R"({"optionalTimestamp": "1969-12-31T16:00:01-08:00"})",
  2557. "optional_timestamp: {seconds: 1}");
  2558. RunValidJsonTest(
  2559. "TimestampNull", REQUIRED,
  2560. R"({"optionalTimestamp": null})",
  2561. "");
  2562. ExpectParseFailureForJson(
  2563. "TimestampJsonInputTooSmall", REQUIRED,
  2564. R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  2565. ExpectParseFailureForJson(
  2566. "TimestampJsonInputTooLarge", REQUIRED,
  2567. R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  2568. ExpectParseFailureForJson(
  2569. "TimestampJsonInputMissingZ", REQUIRED,
  2570. R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  2571. ExpectParseFailureForJson(
  2572. "TimestampJsonInputMissingT", REQUIRED,
  2573. R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  2574. ExpectParseFailureForJson(
  2575. "TimestampJsonInputLowercaseZ", REQUIRED,
  2576. R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  2577. ExpectParseFailureForJson(
  2578. "TimestampJsonInputLowercaseT", REQUIRED,
  2579. R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  2580. ExpectSerializeFailureForJson(
  2581. "TimestampProtoInputTooSmall", REQUIRED,
  2582. "optional_timestamp: {seconds: -62135596801}");
  2583. ExpectSerializeFailureForJson(
  2584. "TimestampProtoInputTooLarge", REQUIRED,
  2585. "optional_timestamp: {seconds: 253402300800}");
  2586. RunValidJsonTestWithValidator(
  2587. "TimestampZeroNormalized", RECOMMENDED,
  2588. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  2589. [](const Json::Value& value) {
  2590. return value["optionalTimestamp"].asString() ==
  2591. "1970-01-01T00:00:00Z";
  2592. });
  2593. RunValidJsonTestWithValidator(
  2594. "TimestampHasZeroFractionalDigit", RECOMMENDED,
  2595. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
  2596. [](const Json::Value& value) {
  2597. return value["optionalTimestamp"].asString() ==
  2598. "1970-01-01T00:00:00Z";
  2599. });
  2600. RunValidJsonTestWithValidator(
  2601. "TimestampHas3FractionalDigits", RECOMMENDED,
  2602. R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
  2603. [](const Json::Value& value) {
  2604. return value["optionalTimestamp"].asString() ==
  2605. "1970-01-01T00:00:00.010Z";
  2606. });
  2607. RunValidJsonTestWithValidator(
  2608. "TimestampHas6FractionalDigits", RECOMMENDED,
  2609. R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
  2610. [](const Json::Value& value) {
  2611. return value["optionalTimestamp"].asString() ==
  2612. "1970-01-01T00:00:00.000010Z";
  2613. });
  2614. RunValidJsonTestWithValidator(
  2615. "TimestampHas9FractionalDigits", RECOMMENDED,
  2616. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
  2617. [](const Json::Value& value) {
  2618. return value["optionalTimestamp"].asString() ==
  2619. "1970-01-01T00:00:00.000000010Z";
  2620. });
  2621. // FieldMask
  2622. RunValidJsonTest(
  2623. "FieldMask", REQUIRED,
  2624. R"({"optionalFieldMask": "foo,barBaz"})",
  2625. R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  2626. RunValidJsonTest(
  2627. "EmptyFieldMask", REQUIRED,
  2628. R"({"optionalFieldMask": ""})",
  2629. R"(optional_field_mask: {})");
  2630. ExpectParseFailureForJson(
  2631. "FieldMaskInvalidCharacter", RECOMMENDED,
  2632. R"({"optionalFieldMask": "foo,bar_bar"})");
  2633. ExpectSerializeFailureForJson(
  2634. "FieldMaskPathsDontRoundTrip", RECOMMENDED,
  2635. R"(optional_field_mask: {paths: "fooBar"})");
  2636. ExpectSerializeFailureForJson(
  2637. "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
  2638. R"(optional_field_mask: {paths: "foo_3_bar"})");
  2639. ExpectSerializeFailureForJson(
  2640. "FieldMaskTooManyUnderscore", RECOMMENDED,
  2641. R"(optional_field_mask: {paths: "foo__bar"})");
  2642. // Struct
  2643. RunValidJsonTest(
  2644. "Struct", REQUIRED,
  2645. R"({
  2646. "optionalStruct": {
  2647. "nullValue": null,
  2648. "intValue": 1234,
  2649. "boolValue": true,
  2650. "doubleValue": 1234.5678,
  2651. "stringValue": "Hello world!",
  2652. "listValue": [1234, "5678"],
  2653. "objectValue": {
  2654. "value": 0
  2655. }
  2656. }
  2657. })",
  2658. R"(
  2659. optional_struct: {
  2660. fields: {
  2661. key: "nullValue"
  2662. value: {null_value: NULL_VALUE}
  2663. }
  2664. fields: {
  2665. key: "intValue"
  2666. value: {number_value: 1234}
  2667. }
  2668. fields: {
  2669. key: "boolValue"
  2670. value: {bool_value: true}
  2671. }
  2672. fields: {
  2673. key: "doubleValue"
  2674. value: {number_value: 1234.5678}
  2675. }
  2676. fields: {
  2677. key: "stringValue"
  2678. value: {string_value: "Hello world!"}
  2679. }
  2680. fields: {
  2681. key: "listValue"
  2682. value: {
  2683. list_value: {
  2684. values: {
  2685. number_value: 1234
  2686. }
  2687. values: {
  2688. string_value: "5678"
  2689. }
  2690. }
  2691. }
  2692. }
  2693. fields: {
  2694. key: "objectValue"
  2695. value: {
  2696. struct_value: {
  2697. fields: {
  2698. key: "value"
  2699. value: {
  2700. number_value: 0
  2701. }
  2702. }
  2703. }
  2704. }
  2705. }
  2706. }
  2707. )");
  2708. RunValidJsonTest(
  2709. "StructWithEmptyListValue", REQUIRED,
  2710. R"({
  2711. "optionalStruct": {
  2712. "listValue": []
  2713. }
  2714. })",
  2715. R"(
  2716. optional_struct: {
  2717. fields: {
  2718. key: "listValue"
  2719. value: {
  2720. list_value: {
  2721. }
  2722. }
  2723. }
  2724. }
  2725. )");
  2726. // Value
  2727. RunValidJsonTest(
  2728. "ValueAcceptInteger", REQUIRED,
  2729. R"({"optionalValue": 1})",
  2730. "optional_value: { number_value: 1}");
  2731. RunValidJsonTest(
  2732. "ValueAcceptFloat", REQUIRED,
  2733. R"({"optionalValue": 1.5})",
  2734. "optional_value: { number_value: 1.5}");
  2735. RunValidJsonTest(
  2736. "ValueAcceptBool", REQUIRED,
  2737. R"({"optionalValue": false})",
  2738. "optional_value: { bool_value: false}");
  2739. RunValidJsonTest(
  2740. "ValueAcceptNull", REQUIRED,
  2741. R"({"optionalValue": null})",
  2742. "optional_value: { null_value: NULL_VALUE}");
  2743. RunValidJsonTest(
  2744. "ValueAcceptString", REQUIRED,
  2745. R"({"optionalValue": "hello"})",
  2746. R"(optional_value: { string_value: "hello"})");
  2747. RunValidJsonTest(
  2748. "ValueAcceptList", REQUIRED,
  2749. R"({"optionalValue": [0, "hello"]})",
  2750. R"(
  2751. optional_value: {
  2752. list_value: {
  2753. values: {
  2754. number_value: 0
  2755. }
  2756. values: {
  2757. string_value: "hello"
  2758. }
  2759. }
  2760. }
  2761. )");
  2762. RunValidJsonTest(
  2763. "ValueAcceptObject", REQUIRED,
  2764. R"({"optionalValue": {"value": 1}})",
  2765. R"(
  2766. optional_value: {
  2767. struct_value: {
  2768. fields: {
  2769. key: "value"
  2770. value: {
  2771. number_value: 1
  2772. }
  2773. }
  2774. }
  2775. }
  2776. )");
  2777. RunValidJsonTest(
  2778. "RepeatedValue", REQUIRED,
  2779. R"({
  2780. "repeatedValue": [["a"]]
  2781. })",
  2782. R"(
  2783. repeated_value: [
  2784. {
  2785. list_value: {
  2786. values: [
  2787. { string_value: "a"}
  2788. ]
  2789. }
  2790. }
  2791. ]
  2792. )");
  2793. RunValidJsonTest(
  2794. "RepeatedListValue", REQUIRED,
  2795. R"({
  2796. "repeatedListValue": [["a"]]
  2797. })",
  2798. R"(
  2799. repeated_list_value: [
  2800. {
  2801. values: [
  2802. { string_value: "a"}
  2803. ]
  2804. }
  2805. ]
  2806. )");
  2807. // Any
  2808. RunValidJsonTest(
  2809. "Any", REQUIRED,
  2810. R"({
  2811. "optionalAny": {
  2812. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2813. "optionalInt32": 12345
  2814. }
  2815. })",
  2816. R"(
  2817. optional_any: {
  2818. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2819. optional_int32: 12345
  2820. }
  2821. }
  2822. )");
  2823. RunValidJsonTest(
  2824. "AnyNested", REQUIRED,
  2825. R"({
  2826. "optionalAny": {
  2827. "@type": "type.googleapis.com/google.protobuf.Any",
  2828. "value": {
  2829. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2830. "optionalInt32": 12345
  2831. }
  2832. }
  2833. })",
  2834. R"(
  2835. optional_any: {
  2836. [type.googleapis.com/google.protobuf.Any] {
  2837. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2838. optional_int32: 12345
  2839. }
  2840. }
  2841. }
  2842. )");
  2843. // The special "@type" tag is not required to appear first.
  2844. RunValidJsonTest(
  2845. "AnyUnorderedTypeTag", REQUIRED,
  2846. R"({
  2847. "optionalAny": {
  2848. "optionalInt32": 12345,
  2849. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
  2850. }
  2851. })",
  2852. R"(
  2853. optional_any: {
  2854. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2855. optional_int32: 12345
  2856. }
  2857. }
  2858. )");
  2859. // Well-known types in Any.
  2860. RunValidJsonTest(
  2861. "AnyWithInt32ValueWrapper", REQUIRED,
  2862. R"({
  2863. "optionalAny": {
  2864. "@type": "type.googleapis.com/google.protobuf.Int32Value",
  2865. "value": 12345
  2866. }
  2867. })",
  2868. R"(
  2869. optional_any: {
  2870. [type.googleapis.com/google.protobuf.Int32Value] {
  2871. value: 12345
  2872. }
  2873. }
  2874. )");
  2875. RunValidJsonTest(
  2876. "AnyWithDuration", REQUIRED,
  2877. R"({
  2878. "optionalAny": {
  2879. "@type": "type.googleapis.com/google.protobuf.Duration",
  2880. "value": "1.5s"
  2881. }
  2882. })",
  2883. R"(
  2884. optional_any: {
  2885. [type.googleapis.com/google.protobuf.Duration] {
  2886. seconds: 1
  2887. nanos: 500000000
  2888. }
  2889. }
  2890. )");
  2891. RunValidJsonTest(
  2892. "AnyWithTimestamp", REQUIRED,
  2893. R"({
  2894. "optionalAny": {
  2895. "@type": "type.googleapis.com/google.protobuf.Timestamp",
  2896. "value": "1970-01-01T00:00:00Z"
  2897. }
  2898. })",
  2899. R"(
  2900. optional_any: {
  2901. [type.googleapis.com/google.protobuf.Timestamp] {
  2902. seconds: 0
  2903. nanos: 0
  2904. }
  2905. }
  2906. )");
  2907. RunValidJsonTest(
  2908. "AnyWithFieldMask", REQUIRED,
  2909. R"({
  2910. "optionalAny": {
  2911. "@type": "type.googleapis.com/google.protobuf.FieldMask",
  2912. "value": "foo,barBaz"
  2913. }
  2914. })",
  2915. R"(
  2916. optional_any: {
  2917. [type.googleapis.com/google.protobuf.FieldMask] {
  2918. paths: ["foo", "bar_baz"]
  2919. }
  2920. }
  2921. )");
  2922. RunValidJsonTest(
  2923. "AnyWithStruct", REQUIRED,
  2924. R"({
  2925. "optionalAny": {
  2926. "@type": "type.googleapis.com/google.protobuf.Struct",
  2927. "value": {
  2928. "foo": 1
  2929. }
  2930. }
  2931. })",
  2932. R"(
  2933. optional_any: {
  2934. [type.googleapis.com/google.protobuf.Struct] {
  2935. fields: {
  2936. key: "foo"
  2937. value: {
  2938. number_value: 1
  2939. }
  2940. }
  2941. }
  2942. }
  2943. )");
  2944. RunValidJsonTest(
  2945. "AnyWithValueForJsonObject", REQUIRED,
  2946. R"({
  2947. "optionalAny": {
  2948. "@type": "type.googleapis.com/google.protobuf.Value",
  2949. "value": {
  2950. "foo": 1
  2951. }
  2952. }
  2953. })",
  2954. R"(
  2955. optional_any: {
  2956. [type.googleapis.com/google.protobuf.Value] {
  2957. struct_value: {
  2958. fields: {
  2959. key: "foo"
  2960. value: {
  2961. number_value: 1
  2962. }
  2963. }
  2964. }
  2965. }
  2966. }
  2967. )");
  2968. RunValidJsonTest(
  2969. "AnyWithValueForInteger", REQUIRED,
  2970. R"({
  2971. "optionalAny": {
  2972. "@type": "type.googleapis.com/google.protobuf.Value",
  2973. "value": 1
  2974. }
  2975. })",
  2976. R"(
  2977. optional_any: {
  2978. [type.googleapis.com/google.protobuf.Value] {
  2979. number_value: 1
  2980. }
  2981. }
  2982. )");
  2983. RunValidJsonIgnoreUnknownTest(
  2984. "IgnoreUnknownJsonNumber", REQUIRED,
  2985. R"({
  2986. "unknown": 1
  2987. })",
  2988. "");
  2989. RunValidJsonIgnoreUnknownTest(
  2990. "IgnoreUnknownJsonString", REQUIRED,
  2991. R"({
  2992. "unknown": "a"
  2993. })",
  2994. "");
  2995. RunValidJsonIgnoreUnknownTest(
  2996. "IgnoreUnknownJsonTrue", REQUIRED,
  2997. R"({
  2998. "unknown": true
  2999. })",
  3000. "");
  3001. RunValidJsonIgnoreUnknownTest(
  3002. "IgnoreUnknownJsonFalse", REQUIRED,
  3003. R"({
  3004. "unknown": false
  3005. })",
  3006. "");
  3007. RunValidJsonIgnoreUnknownTest(
  3008. "IgnoreUnknownJsonNull", REQUIRED,
  3009. R"({
  3010. "unknown": null
  3011. })",
  3012. "");
  3013. RunValidJsonIgnoreUnknownTest(
  3014. "IgnoreUnknownJsonObject", REQUIRED,
  3015. R"({
  3016. "unknown": {"a": 1}
  3017. })",
  3018. "");
  3019. ExpectParseFailureForJson("RejectTopLevelNull", REQUIRED, "null");
  3020. }
  3021. } // namespace protobuf
  3022. } // namespace google