conformance_test.cc 89 KB

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