conformance_test.cc 69 KB

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