binary_json_conformance_suite.cc 117 KB

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