binary_json_conformance_suite.cc 93 KB

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