conformance_test.cc 64 KB

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