conformance_test_impl.cc 81 KB

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