binary_json_conformance_suite.cc 92 KB

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