binary_json_conformance_suite.cc 83 KB

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