binary_json_conformance_suite.cc 85 KB

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