conformance_test.cc 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562
  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. TestUnknownMessage(messageProto3, true);
  1779. TestUnknownMessage(messageProto2, false);
  1780. }
  1781. // Wrapper types.
  1782. RunValidJsonTest(
  1783. "OptionalBoolWrapper", REQUIRED,
  1784. R"({"optionalBoolWrapper": false})",
  1785. "optional_bool_wrapper: {value: false}");
  1786. RunValidJsonTest(
  1787. "OptionalInt32Wrapper", REQUIRED,
  1788. R"({"optionalInt32Wrapper": 0})",
  1789. "optional_int32_wrapper: {value: 0}");
  1790. RunValidJsonTest(
  1791. "OptionalUint32Wrapper", REQUIRED,
  1792. R"({"optionalUint32Wrapper": 0})",
  1793. "optional_uint32_wrapper: {value: 0}");
  1794. RunValidJsonTest(
  1795. "OptionalInt64Wrapper", REQUIRED,
  1796. R"({"optionalInt64Wrapper": 0})",
  1797. "optional_int64_wrapper: {value: 0}");
  1798. RunValidJsonTest(
  1799. "OptionalUint64Wrapper", REQUIRED,
  1800. R"({"optionalUint64Wrapper": 0})",
  1801. "optional_uint64_wrapper: {value: 0}");
  1802. RunValidJsonTest(
  1803. "OptionalFloatWrapper", REQUIRED,
  1804. R"({"optionalFloatWrapper": 0})",
  1805. "optional_float_wrapper: {value: 0}");
  1806. RunValidJsonTest(
  1807. "OptionalDoubleWrapper", REQUIRED,
  1808. R"({"optionalDoubleWrapper": 0})",
  1809. "optional_double_wrapper: {value: 0}");
  1810. RunValidJsonTest(
  1811. "OptionalStringWrapper", REQUIRED,
  1812. R"({"optionalStringWrapper": ""})",
  1813. R"(optional_string_wrapper: {value: ""})");
  1814. RunValidJsonTest(
  1815. "OptionalBytesWrapper", REQUIRED,
  1816. R"({"optionalBytesWrapper": ""})",
  1817. R"(optional_bytes_wrapper: {value: ""})");
  1818. RunValidJsonTest(
  1819. "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
  1820. R"({
  1821. "optionalBoolWrapper": true,
  1822. "optionalInt32Wrapper": 1,
  1823. "optionalUint32Wrapper": 1,
  1824. "optionalInt64Wrapper": "1",
  1825. "optionalUint64Wrapper": "1",
  1826. "optionalFloatWrapper": 1,
  1827. "optionalDoubleWrapper": 1,
  1828. "optionalStringWrapper": "1",
  1829. "optionalBytesWrapper": "AQI="
  1830. })",
  1831. R"(
  1832. optional_bool_wrapper: {value: true}
  1833. optional_int32_wrapper: {value: 1}
  1834. optional_uint32_wrapper: {value: 1}
  1835. optional_int64_wrapper: {value: 1}
  1836. optional_uint64_wrapper: {value: 1}
  1837. optional_float_wrapper: {value: 1}
  1838. optional_double_wrapper: {value: 1}
  1839. optional_string_wrapper: {value: "1"}
  1840. optional_bytes_wrapper: {value: "\x01\x02"}
  1841. )");
  1842. RunValidJsonTest(
  1843. "RepeatedBoolWrapper", REQUIRED,
  1844. R"({"repeatedBoolWrapper": [true, false]})",
  1845. "repeated_bool_wrapper: {value: true}"
  1846. "repeated_bool_wrapper: {value: false}");
  1847. RunValidJsonTest(
  1848. "RepeatedInt32Wrapper", REQUIRED,
  1849. R"({"repeatedInt32Wrapper": [0, 1]})",
  1850. "repeated_int32_wrapper: {value: 0}"
  1851. "repeated_int32_wrapper: {value: 1}");
  1852. RunValidJsonTest(
  1853. "RepeatedUint32Wrapper", REQUIRED,
  1854. R"({"repeatedUint32Wrapper": [0, 1]})",
  1855. "repeated_uint32_wrapper: {value: 0}"
  1856. "repeated_uint32_wrapper: {value: 1}");
  1857. RunValidJsonTest(
  1858. "RepeatedInt64Wrapper", REQUIRED,
  1859. R"({"repeatedInt64Wrapper": [0, 1]})",
  1860. "repeated_int64_wrapper: {value: 0}"
  1861. "repeated_int64_wrapper: {value: 1}");
  1862. RunValidJsonTest(
  1863. "RepeatedUint64Wrapper", REQUIRED,
  1864. R"({"repeatedUint64Wrapper": [0, 1]})",
  1865. "repeated_uint64_wrapper: {value: 0}"
  1866. "repeated_uint64_wrapper: {value: 1}");
  1867. RunValidJsonTest(
  1868. "RepeatedFloatWrapper", REQUIRED,
  1869. R"({"repeatedFloatWrapper": [0, 1]})",
  1870. "repeated_float_wrapper: {value: 0}"
  1871. "repeated_float_wrapper: {value: 1}");
  1872. RunValidJsonTest(
  1873. "RepeatedDoubleWrapper", REQUIRED,
  1874. R"({"repeatedDoubleWrapper": [0, 1]})",
  1875. "repeated_double_wrapper: {value: 0}"
  1876. "repeated_double_wrapper: {value: 1}");
  1877. RunValidJsonTest(
  1878. "RepeatedStringWrapper", REQUIRED,
  1879. R"({"repeatedStringWrapper": ["", "AQI="]})",
  1880. R"(
  1881. repeated_string_wrapper: {value: ""}
  1882. repeated_string_wrapper: {value: "AQI="}
  1883. )");
  1884. RunValidJsonTest(
  1885. "RepeatedBytesWrapper", REQUIRED,
  1886. R"({"repeatedBytesWrapper": ["", "AQI="]})",
  1887. R"(
  1888. repeated_bytes_wrapper: {value: ""}
  1889. repeated_bytes_wrapper: {value: "\x01\x02"}
  1890. )");
  1891. RunValidJsonTest(
  1892. "WrapperTypesWithNullValue", REQUIRED,
  1893. R"({
  1894. "optionalBoolWrapper": null,
  1895. "optionalInt32Wrapper": null,
  1896. "optionalUint32Wrapper": null,
  1897. "optionalInt64Wrapper": null,
  1898. "optionalUint64Wrapper": null,
  1899. "optionalFloatWrapper": null,
  1900. "optionalDoubleWrapper": null,
  1901. "optionalStringWrapper": null,
  1902. "optionalBytesWrapper": null,
  1903. "repeatedBoolWrapper": null,
  1904. "repeatedInt32Wrapper": null,
  1905. "repeatedUint32Wrapper": null,
  1906. "repeatedInt64Wrapper": null,
  1907. "repeatedUint64Wrapper": null,
  1908. "repeatedFloatWrapper": null,
  1909. "repeatedDoubleWrapper": null,
  1910. "repeatedStringWrapper": null,
  1911. "repeatedBytesWrapper": null
  1912. })",
  1913. "");
  1914. // Duration
  1915. RunValidJsonTest(
  1916. "DurationMinValue", REQUIRED,
  1917. R"({"optionalDuration": "-315576000000.999999999s"})",
  1918. "optional_duration: {seconds: -315576000000 nanos: -999999999}");
  1919. RunValidJsonTest(
  1920. "DurationMaxValue", REQUIRED,
  1921. R"({"optionalDuration": "315576000000.999999999s"})",
  1922. "optional_duration: {seconds: 315576000000 nanos: 999999999}");
  1923. RunValidJsonTest(
  1924. "DurationRepeatedValue", REQUIRED,
  1925. R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
  1926. "repeated_duration: {seconds: 1 nanos: 500000000}"
  1927. "repeated_duration: {seconds: -1 nanos: -500000000}");
  1928. RunValidJsonTest(
  1929. "DurationNull", REQUIRED,
  1930. R"({"optionalDuration": null})",
  1931. "");
  1932. ExpectParseFailureForJson(
  1933. "DurationMissingS", REQUIRED,
  1934. R"({"optionalDuration": "1"})");
  1935. ExpectParseFailureForJson(
  1936. "DurationJsonInputTooSmall", REQUIRED,
  1937. R"({"optionalDuration": "-315576000001.000000000s"})");
  1938. ExpectParseFailureForJson(
  1939. "DurationJsonInputTooLarge", REQUIRED,
  1940. R"({"optionalDuration": "315576000001.000000000s"})");
  1941. ExpectSerializeFailureForJson(
  1942. "DurationProtoInputTooSmall", REQUIRED,
  1943. "optional_duration: {seconds: -315576000001 nanos: 0}");
  1944. ExpectSerializeFailureForJson(
  1945. "DurationProtoInputTooLarge", REQUIRED,
  1946. "optional_duration: {seconds: 315576000001 nanos: 0}");
  1947. RunValidJsonTestWithValidator(
  1948. "DurationHasZeroFractionalDigit", RECOMMENDED,
  1949. R"({"optionalDuration": "1.000000000s"})",
  1950. [](const Json::Value& value) {
  1951. return value["optionalDuration"].asString() == "1s";
  1952. });
  1953. RunValidJsonTestWithValidator(
  1954. "DurationHas3FractionalDigits", RECOMMENDED,
  1955. R"({"optionalDuration": "1.010000000s"})",
  1956. [](const Json::Value& value) {
  1957. return value["optionalDuration"].asString() == "1.010s";
  1958. });
  1959. RunValidJsonTestWithValidator(
  1960. "DurationHas6FractionalDigits", RECOMMENDED,
  1961. R"({"optionalDuration": "1.000010000s"})",
  1962. [](const Json::Value& value) {
  1963. return value["optionalDuration"].asString() == "1.000010s";
  1964. });
  1965. RunValidJsonTestWithValidator(
  1966. "DurationHas9FractionalDigits", RECOMMENDED,
  1967. R"({"optionalDuration": "1.000000010s"})",
  1968. [](const Json::Value& value) {
  1969. return value["optionalDuration"].asString() == "1.000000010s";
  1970. });
  1971. // Timestamp
  1972. RunValidJsonTest(
  1973. "TimestampMinValue", REQUIRED,
  1974. R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
  1975. "optional_timestamp: {seconds: -62135596800}");
  1976. RunValidJsonTest(
  1977. "TimestampMaxValue", REQUIRED,
  1978. R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
  1979. "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1980. RunValidJsonTest(
  1981. "TimestampRepeatedValue", REQUIRED,
  1982. R"({
  1983. "repeatedTimestamp": [
  1984. "0001-01-01T00:00:00Z",
  1985. "9999-12-31T23:59:59.999999999Z"
  1986. ]
  1987. })",
  1988. "repeated_timestamp: {seconds: -62135596800}"
  1989. "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1990. RunValidJsonTest(
  1991. "TimestampWithPositiveOffset", REQUIRED,
  1992. R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
  1993. "optional_timestamp: {seconds: 0}");
  1994. RunValidJsonTest(
  1995. "TimestampWithNegativeOffset", REQUIRED,
  1996. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  1997. "optional_timestamp: {seconds: 0}");
  1998. RunValidJsonTest(
  1999. "TimestampNull", REQUIRED,
  2000. R"({"optionalTimestamp": null})",
  2001. "");
  2002. ExpectParseFailureForJson(
  2003. "TimestampJsonInputTooSmall", REQUIRED,
  2004. R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  2005. ExpectParseFailureForJson(
  2006. "TimestampJsonInputTooLarge", REQUIRED,
  2007. R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  2008. ExpectParseFailureForJson(
  2009. "TimestampJsonInputMissingZ", REQUIRED,
  2010. R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  2011. ExpectParseFailureForJson(
  2012. "TimestampJsonInputMissingT", REQUIRED,
  2013. R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  2014. ExpectParseFailureForJson(
  2015. "TimestampJsonInputLowercaseZ", REQUIRED,
  2016. R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  2017. ExpectParseFailureForJson(
  2018. "TimestampJsonInputLowercaseT", REQUIRED,
  2019. R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  2020. ExpectSerializeFailureForJson(
  2021. "TimestampProtoInputTooSmall", REQUIRED,
  2022. "optional_timestamp: {seconds: -62135596801}");
  2023. ExpectSerializeFailureForJson(
  2024. "TimestampProtoInputTooLarge", REQUIRED,
  2025. "optional_timestamp: {seconds: 253402300800}");
  2026. RunValidJsonTestWithValidator(
  2027. "TimestampZeroNormalized", RECOMMENDED,
  2028. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  2029. [](const Json::Value& value) {
  2030. return value["optionalTimestamp"].asString() ==
  2031. "1970-01-01T00:00:00Z";
  2032. });
  2033. RunValidJsonTestWithValidator(
  2034. "TimestampHasZeroFractionalDigit", RECOMMENDED,
  2035. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
  2036. [](const Json::Value& value) {
  2037. return value["optionalTimestamp"].asString() ==
  2038. "1970-01-01T00:00:00Z";
  2039. });
  2040. RunValidJsonTestWithValidator(
  2041. "TimestampHas3FractionalDigits", RECOMMENDED,
  2042. R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
  2043. [](const Json::Value& value) {
  2044. return value["optionalTimestamp"].asString() ==
  2045. "1970-01-01T00:00:00.010Z";
  2046. });
  2047. RunValidJsonTestWithValidator(
  2048. "TimestampHas6FractionalDigits", RECOMMENDED,
  2049. R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
  2050. [](const Json::Value& value) {
  2051. return value["optionalTimestamp"].asString() ==
  2052. "1970-01-01T00:00:00.000010Z";
  2053. });
  2054. RunValidJsonTestWithValidator(
  2055. "TimestampHas9FractionalDigits", RECOMMENDED,
  2056. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
  2057. [](const Json::Value& value) {
  2058. return value["optionalTimestamp"].asString() ==
  2059. "1970-01-01T00:00:00.000000010Z";
  2060. });
  2061. // FieldMask
  2062. RunValidJsonTest(
  2063. "FieldMask", REQUIRED,
  2064. R"({"optionalFieldMask": "foo,barBaz"})",
  2065. R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  2066. ExpectParseFailureForJson(
  2067. "FieldMaskInvalidCharacter", RECOMMENDED,
  2068. R"({"optionalFieldMask": "foo,bar_bar"})");
  2069. ExpectSerializeFailureForJson(
  2070. "FieldMaskPathsDontRoundTrip", RECOMMENDED,
  2071. R"(optional_field_mask: {paths: "fooBar"})");
  2072. ExpectSerializeFailureForJson(
  2073. "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
  2074. R"(optional_field_mask: {paths: "foo_3_bar"})");
  2075. ExpectSerializeFailureForJson(
  2076. "FieldMaskTooManyUnderscore", RECOMMENDED,
  2077. R"(optional_field_mask: {paths: "foo__bar"})");
  2078. // Struct
  2079. RunValidJsonTest(
  2080. "Struct", REQUIRED,
  2081. R"({
  2082. "optionalStruct": {
  2083. "nullValue": null,
  2084. "intValue": 1234,
  2085. "boolValue": true,
  2086. "doubleValue": 1234.5678,
  2087. "stringValue": "Hello world!",
  2088. "listValue": [1234, "5678"],
  2089. "objectValue": {
  2090. "value": 0
  2091. }
  2092. }
  2093. })",
  2094. R"(
  2095. optional_struct: {
  2096. fields: {
  2097. key: "nullValue"
  2098. value: {null_value: NULL_VALUE}
  2099. }
  2100. fields: {
  2101. key: "intValue"
  2102. value: {number_value: 1234}
  2103. }
  2104. fields: {
  2105. key: "boolValue"
  2106. value: {bool_value: true}
  2107. }
  2108. fields: {
  2109. key: "doubleValue"
  2110. value: {number_value: 1234.5678}
  2111. }
  2112. fields: {
  2113. key: "stringValue"
  2114. value: {string_value: "Hello world!"}
  2115. }
  2116. fields: {
  2117. key: "listValue"
  2118. value: {
  2119. list_value: {
  2120. values: {
  2121. number_value: 1234
  2122. }
  2123. values: {
  2124. string_value: "5678"
  2125. }
  2126. }
  2127. }
  2128. }
  2129. fields: {
  2130. key: "objectValue"
  2131. value: {
  2132. struct_value: {
  2133. fields: {
  2134. key: "value"
  2135. value: {
  2136. number_value: 0
  2137. }
  2138. }
  2139. }
  2140. }
  2141. }
  2142. }
  2143. )");
  2144. // Value
  2145. RunValidJsonTest(
  2146. "ValueAcceptInteger", REQUIRED,
  2147. R"({"optionalValue": 1})",
  2148. "optional_value: { number_value: 1}");
  2149. RunValidJsonTest(
  2150. "ValueAcceptFloat", REQUIRED,
  2151. R"({"optionalValue": 1.5})",
  2152. "optional_value: { number_value: 1.5}");
  2153. RunValidJsonTest(
  2154. "ValueAcceptBool", REQUIRED,
  2155. R"({"optionalValue": false})",
  2156. "optional_value: { bool_value: false}");
  2157. RunValidJsonTest(
  2158. "ValueAcceptNull", REQUIRED,
  2159. R"({"optionalValue": null})",
  2160. "optional_value: { null_value: NULL_VALUE}");
  2161. RunValidJsonTest(
  2162. "ValueAcceptString", REQUIRED,
  2163. R"({"optionalValue": "hello"})",
  2164. R"(optional_value: { string_value: "hello"})");
  2165. RunValidJsonTest(
  2166. "ValueAcceptList", REQUIRED,
  2167. R"({"optionalValue": [0, "hello"]})",
  2168. R"(
  2169. optional_value: {
  2170. list_value: {
  2171. values: {
  2172. number_value: 0
  2173. }
  2174. values: {
  2175. string_value: "hello"
  2176. }
  2177. }
  2178. }
  2179. )");
  2180. RunValidJsonTest(
  2181. "ValueAcceptObject", REQUIRED,
  2182. R"({"optionalValue": {"value": 1}})",
  2183. R"(
  2184. optional_value: {
  2185. struct_value: {
  2186. fields: {
  2187. key: "value"
  2188. value: {
  2189. number_value: 1
  2190. }
  2191. }
  2192. }
  2193. }
  2194. )");
  2195. // Any
  2196. RunValidJsonTest(
  2197. "Any", REQUIRED,
  2198. R"({
  2199. "optionalAny": {
  2200. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2201. "optionalInt32": 12345
  2202. }
  2203. })",
  2204. R"(
  2205. optional_any: {
  2206. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2207. optional_int32: 12345
  2208. }
  2209. }
  2210. )");
  2211. RunValidJsonTest(
  2212. "AnyNested", REQUIRED,
  2213. R"({
  2214. "optionalAny": {
  2215. "@type": "type.googleapis.com/google.protobuf.Any",
  2216. "value": {
  2217. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2218. "optionalInt32": 12345
  2219. }
  2220. }
  2221. })",
  2222. R"(
  2223. optional_any: {
  2224. [type.googleapis.com/google.protobuf.Any] {
  2225. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2226. optional_int32: 12345
  2227. }
  2228. }
  2229. }
  2230. )");
  2231. // The special "@type" tag is not required to appear first.
  2232. RunValidJsonTest(
  2233. "AnyUnorderedTypeTag", REQUIRED,
  2234. R"({
  2235. "optionalAny": {
  2236. "optionalInt32": 12345,
  2237. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
  2238. }
  2239. })",
  2240. R"(
  2241. optional_any: {
  2242. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2243. optional_int32: 12345
  2244. }
  2245. }
  2246. )");
  2247. // Well-known types in Any.
  2248. RunValidJsonTest(
  2249. "AnyWithInt32ValueWrapper", REQUIRED,
  2250. R"({
  2251. "optionalAny": {
  2252. "@type": "type.googleapis.com/google.protobuf.Int32Value",
  2253. "value": 12345
  2254. }
  2255. })",
  2256. R"(
  2257. optional_any: {
  2258. [type.googleapis.com/google.protobuf.Int32Value] {
  2259. value: 12345
  2260. }
  2261. }
  2262. )");
  2263. RunValidJsonTest(
  2264. "AnyWithDuration", REQUIRED,
  2265. R"({
  2266. "optionalAny": {
  2267. "@type": "type.googleapis.com/google.protobuf.Duration",
  2268. "value": "1.5s"
  2269. }
  2270. })",
  2271. R"(
  2272. optional_any: {
  2273. [type.googleapis.com/google.protobuf.Duration] {
  2274. seconds: 1
  2275. nanos: 500000000
  2276. }
  2277. }
  2278. )");
  2279. RunValidJsonTest(
  2280. "AnyWithTimestamp", REQUIRED,
  2281. R"({
  2282. "optionalAny": {
  2283. "@type": "type.googleapis.com/google.protobuf.Timestamp",
  2284. "value": "1970-01-01T00:00:00Z"
  2285. }
  2286. })",
  2287. R"(
  2288. optional_any: {
  2289. [type.googleapis.com/google.protobuf.Timestamp] {
  2290. seconds: 0
  2291. nanos: 0
  2292. }
  2293. }
  2294. )");
  2295. RunValidJsonTest(
  2296. "AnyWithFieldMask", REQUIRED,
  2297. R"({
  2298. "optionalAny": {
  2299. "@type": "type.googleapis.com/google.protobuf.FieldMask",
  2300. "value": "foo,barBaz"
  2301. }
  2302. })",
  2303. R"(
  2304. optional_any: {
  2305. [type.googleapis.com/google.protobuf.FieldMask] {
  2306. paths: ["foo", "bar_baz"]
  2307. }
  2308. }
  2309. )");
  2310. RunValidJsonTest(
  2311. "AnyWithStruct", REQUIRED,
  2312. R"({
  2313. "optionalAny": {
  2314. "@type": "type.googleapis.com/google.protobuf.Struct",
  2315. "value": {
  2316. "foo": 1
  2317. }
  2318. }
  2319. })",
  2320. R"(
  2321. optional_any: {
  2322. [type.googleapis.com/google.protobuf.Struct] {
  2323. fields: {
  2324. key: "foo"
  2325. value: {
  2326. number_value: 1
  2327. }
  2328. }
  2329. }
  2330. }
  2331. )");
  2332. RunValidJsonTest(
  2333. "AnyWithValueForJsonObject", REQUIRED,
  2334. R"({
  2335. "optionalAny": {
  2336. "@type": "type.googleapis.com/google.protobuf.Value",
  2337. "value": {
  2338. "foo": 1
  2339. }
  2340. }
  2341. })",
  2342. R"(
  2343. optional_any: {
  2344. [type.googleapis.com/google.protobuf.Value] {
  2345. struct_value: {
  2346. fields: {
  2347. key: "foo"
  2348. value: {
  2349. number_value: 1
  2350. }
  2351. }
  2352. }
  2353. }
  2354. }
  2355. )");
  2356. RunValidJsonTest(
  2357. "AnyWithValueForInteger", REQUIRED,
  2358. R"({
  2359. "optionalAny": {
  2360. "@type": "type.googleapis.com/google.protobuf.Value",
  2361. "value": 1
  2362. }
  2363. })",
  2364. R"(
  2365. optional_any: {
  2366. [type.googleapis.com/google.protobuf.Value] {
  2367. number_value: 1
  2368. }
  2369. }
  2370. )");
  2371. bool ok = true;
  2372. if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt",
  2373. "These tests were listed in the failure list, but they "
  2374. "don't exist. Remove them from the failure list by "
  2375. "running:\n"
  2376. " ./update_failure_list.py " + failure_list_filename_ +
  2377. " --remove nonexistent_tests.txt")) {
  2378. ok = false;
  2379. }
  2380. if (!CheckSetEmpty(unexpected_failing_tests_, "failing_tests.txt",
  2381. "These tests failed. If they can't be fixed right now, "
  2382. "you can add them to the failure list so the overall "
  2383. "suite can succeed. Add them to the failure list by "
  2384. "running:\n"
  2385. " ./update_failure_list.py " + failure_list_filename_ +
  2386. " --add failing_tests.txt")) {
  2387. ok = false;
  2388. }
  2389. if (!CheckSetEmpty(unexpected_succeeding_tests_, "succeeding_tests.txt",
  2390. "These tests succeeded, even though they were listed in "
  2391. "the failure list. Remove them from the failure list "
  2392. "by running:\n"
  2393. " ./update_failure_list.py " + failure_list_filename_ +
  2394. " --remove succeeding_tests.txt")) {
  2395. ok = false;
  2396. }
  2397. if (verbose_) {
  2398. CheckSetEmpty(skipped_, "",
  2399. "These tests were skipped (probably because support for some "
  2400. "features is not implemented)");
  2401. }
  2402. StringAppendF(&output_,
  2403. "CONFORMANCE SUITE %s: %d successes, %d skipped, "
  2404. "%d expected failures, %d unexpected failures.\n",
  2405. ok ? "PASSED" : "FAILED", successes_, skipped_.size(),
  2406. expected_failures_, unexpected_failing_tests_.size());
  2407. StringAppendF(&output_, "\n");
  2408. output->assign(output_);
  2409. return ok;
  2410. }
  2411. } // namespace protobuf
  2412. } // namespace google