conformance_test.cc 86 KB

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