conformance_test.cc 85 KB

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