conformance_test.cc 66 KB

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