conformance_test.cc 82 KB

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