conformance_test.cc 64 KB

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