binary_json_conformance_suite.cc 82 KB

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