binary_json_conformance_suite.cc 105 KB

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