conformance_test.cc 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  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. RunValidJsonTest(
  1866. "DurationNull", REQUIRED,
  1867. R"({"optionalDuration": null})",
  1868. "");
  1869. ExpectParseFailureForJson(
  1870. "DurationMissingS", REQUIRED,
  1871. R"({"optionalDuration": "1"})");
  1872. ExpectParseFailureForJson(
  1873. "DurationJsonInputTooSmall", REQUIRED,
  1874. R"({"optionalDuration": "-315576000001.000000000s"})");
  1875. ExpectParseFailureForJson(
  1876. "DurationJsonInputTooLarge", REQUIRED,
  1877. R"({"optionalDuration": "315576000001.000000000s"})");
  1878. ExpectSerializeFailureForJson(
  1879. "DurationProtoInputTooSmall", REQUIRED,
  1880. "optional_duration: {seconds: -315576000001 nanos: 0}");
  1881. ExpectSerializeFailureForJson(
  1882. "DurationProtoInputTooLarge", REQUIRED,
  1883. "optional_duration: {seconds: 315576000001 nanos: 0}");
  1884. RunValidJsonTestWithValidator(
  1885. "DurationHasZeroFractionalDigit", RECOMMENDED,
  1886. R"({"optionalDuration": "1.000000000s"})",
  1887. [](const Json::Value& value) {
  1888. return value["optionalDuration"].asString() == "1s";
  1889. });
  1890. RunValidJsonTestWithValidator(
  1891. "DurationHas3FractionalDigits", RECOMMENDED,
  1892. R"({"optionalDuration": "1.010000000s"})",
  1893. [](const Json::Value& value) {
  1894. return value["optionalDuration"].asString() == "1.010s";
  1895. });
  1896. RunValidJsonTestWithValidator(
  1897. "DurationHas6FractionalDigits", RECOMMENDED,
  1898. R"({"optionalDuration": "1.000010000s"})",
  1899. [](const Json::Value& value) {
  1900. return value["optionalDuration"].asString() == "1.000010s";
  1901. });
  1902. RunValidJsonTestWithValidator(
  1903. "DurationHas9FractionalDigits", RECOMMENDED,
  1904. R"({"optionalDuration": "1.000000010s"})",
  1905. [](const Json::Value& value) {
  1906. return value["optionalDuration"].asString() == "1.000000010s";
  1907. });
  1908. // Timestamp
  1909. RunValidJsonTest(
  1910. "TimestampMinValue", REQUIRED,
  1911. R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
  1912. "optional_timestamp: {seconds: -62135596800}");
  1913. RunValidJsonTest(
  1914. "TimestampMaxValue", REQUIRED,
  1915. R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
  1916. "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1917. RunValidJsonTest(
  1918. "TimestampRepeatedValue", REQUIRED,
  1919. R"({
  1920. "repeatedTimestamp": [
  1921. "0001-01-01T00:00:00Z",
  1922. "9999-12-31T23:59:59.999999999Z"
  1923. ]
  1924. })",
  1925. "repeated_timestamp: {seconds: -62135596800}"
  1926. "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1927. RunValidJsonTest(
  1928. "TimestampWithPositiveOffset", REQUIRED,
  1929. R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
  1930. "optional_timestamp: {seconds: 0}");
  1931. RunValidJsonTest(
  1932. "TimestampWithNegativeOffset", REQUIRED,
  1933. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  1934. "optional_timestamp: {seconds: 0}");
  1935. RunValidJsonTest(
  1936. "TimestampNull", REQUIRED,
  1937. R"({"optionalTimestamp": null})",
  1938. "");
  1939. ExpectParseFailureForJson(
  1940. "TimestampJsonInputTooSmall", REQUIRED,
  1941. R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  1942. ExpectParseFailureForJson(
  1943. "TimestampJsonInputTooLarge", REQUIRED,
  1944. R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  1945. ExpectParseFailureForJson(
  1946. "TimestampJsonInputMissingZ", REQUIRED,
  1947. R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  1948. ExpectParseFailureForJson(
  1949. "TimestampJsonInputMissingT", REQUIRED,
  1950. R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  1951. ExpectParseFailureForJson(
  1952. "TimestampJsonInputLowercaseZ", REQUIRED,
  1953. R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  1954. ExpectParseFailureForJson(
  1955. "TimestampJsonInputLowercaseT", REQUIRED,
  1956. R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  1957. ExpectSerializeFailureForJson(
  1958. "TimestampProtoInputTooSmall", REQUIRED,
  1959. "optional_timestamp: {seconds: -62135596801}");
  1960. ExpectSerializeFailureForJson(
  1961. "TimestampProtoInputTooLarge", REQUIRED,
  1962. "optional_timestamp: {seconds: 253402300800}");
  1963. RunValidJsonTestWithValidator(
  1964. "TimestampZeroNormalized", RECOMMENDED,
  1965. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  1966. [](const Json::Value& value) {
  1967. return value["optionalTimestamp"].asString() ==
  1968. "1970-01-01T00:00:00Z";
  1969. });
  1970. RunValidJsonTestWithValidator(
  1971. "TimestampHasZeroFractionalDigit", RECOMMENDED,
  1972. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
  1973. [](const Json::Value& value) {
  1974. return value["optionalTimestamp"].asString() ==
  1975. "1970-01-01T00:00:00Z";
  1976. });
  1977. RunValidJsonTestWithValidator(
  1978. "TimestampHas3FractionalDigits", RECOMMENDED,
  1979. R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
  1980. [](const Json::Value& value) {
  1981. return value["optionalTimestamp"].asString() ==
  1982. "1970-01-01T00:00:00.010Z";
  1983. });
  1984. RunValidJsonTestWithValidator(
  1985. "TimestampHas6FractionalDigits", RECOMMENDED,
  1986. R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
  1987. [](const Json::Value& value) {
  1988. return value["optionalTimestamp"].asString() ==
  1989. "1970-01-01T00:00:00.000010Z";
  1990. });
  1991. RunValidJsonTestWithValidator(
  1992. "TimestampHas9FractionalDigits", RECOMMENDED,
  1993. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
  1994. [](const Json::Value& value) {
  1995. return value["optionalTimestamp"].asString() ==
  1996. "1970-01-01T00:00:00.000000010Z";
  1997. });
  1998. // FieldMask
  1999. RunValidJsonTest(
  2000. "FieldMask", REQUIRED,
  2001. R"({"optionalFieldMask": "foo,barBaz"})",
  2002. R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  2003. ExpectParseFailureForJson(
  2004. "FieldMaskInvalidCharacter", RECOMMENDED,
  2005. R"({"optionalFieldMask": "foo,bar_bar"})");
  2006. ExpectSerializeFailureForJson(
  2007. "FieldMaskPathsDontRoundTrip", RECOMMENDED,
  2008. R"(optional_field_mask: {paths: "fooBar"})");
  2009. ExpectSerializeFailureForJson(
  2010. "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
  2011. R"(optional_field_mask: {paths: "foo_3_bar"})");
  2012. ExpectSerializeFailureForJson(
  2013. "FieldMaskTooManyUnderscore", RECOMMENDED,
  2014. R"(optional_field_mask: {paths: "foo__bar"})");
  2015. // Struct
  2016. RunValidJsonTest(
  2017. "Struct", REQUIRED,
  2018. R"({
  2019. "optionalStruct": {
  2020. "nullValue": null,
  2021. "intValue": 1234,
  2022. "boolValue": true,
  2023. "doubleValue": 1234.5678,
  2024. "stringValue": "Hello world!",
  2025. "listValue": [1234, "5678"],
  2026. "objectValue": {
  2027. "value": 0
  2028. }
  2029. }
  2030. })",
  2031. R"(
  2032. optional_struct: {
  2033. fields: {
  2034. key: "nullValue"
  2035. value: {null_value: NULL_VALUE}
  2036. }
  2037. fields: {
  2038. key: "intValue"
  2039. value: {number_value: 1234}
  2040. }
  2041. fields: {
  2042. key: "boolValue"
  2043. value: {bool_value: true}
  2044. }
  2045. fields: {
  2046. key: "doubleValue"
  2047. value: {number_value: 1234.5678}
  2048. }
  2049. fields: {
  2050. key: "stringValue"
  2051. value: {string_value: "Hello world!"}
  2052. }
  2053. fields: {
  2054. key: "listValue"
  2055. value: {
  2056. list_value: {
  2057. values: {
  2058. number_value: 1234
  2059. }
  2060. values: {
  2061. string_value: "5678"
  2062. }
  2063. }
  2064. }
  2065. }
  2066. fields: {
  2067. key: "objectValue"
  2068. value: {
  2069. struct_value: {
  2070. fields: {
  2071. key: "value"
  2072. value: {
  2073. number_value: 0
  2074. }
  2075. }
  2076. }
  2077. }
  2078. }
  2079. }
  2080. )");
  2081. // Value
  2082. RunValidJsonTest(
  2083. "ValueAcceptInteger", REQUIRED,
  2084. R"({"optionalValue": 1})",
  2085. "optional_value: { number_value: 1}");
  2086. RunValidJsonTest(
  2087. "ValueAcceptFloat", REQUIRED,
  2088. R"({"optionalValue": 1.5})",
  2089. "optional_value: { number_value: 1.5}");
  2090. RunValidJsonTest(
  2091. "ValueAcceptBool", REQUIRED,
  2092. R"({"optionalValue": false})",
  2093. "optional_value: { bool_value: false}");
  2094. RunValidJsonTest(
  2095. "ValueAcceptNull", REQUIRED,
  2096. R"({"optionalValue": null})",
  2097. "optional_value: { null_value: NULL_VALUE}");
  2098. RunValidJsonTest(
  2099. "ValueAcceptString", REQUIRED,
  2100. R"({"optionalValue": "hello"})",
  2101. R"(optional_value: { string_value: "hello"})");
  2102. RunValidJsonTest(
  2103. "ValueAcceptList", REQUIRED,
  2104. R"({"optionalValue": [0, "hello"]})",
  2105. R"(
  2106. optional_value: {
  2107. list_value: {
  2108. values: {
  2109. number_value: 0
  2110. }
  2111. values: {
  2112. string_value: "hello"
  2113. }
  2114. }
  2115. }
  2116. )");
  2117. RunValidJsonTest(
  2118. "ValueAcceptObject", REQUIRED,
  2119. R"({"optionalValue": {"value": 1}})",
  2120. R"(
  2121. optional_value: {
  2122. struct_value: {
  2123. fields: {
  2124. key: "value"
  2125. value: {
  2126. number_value: 1
  2127. }
  2128. }
  2129. }
  2130. }
  2131. )");
  2132. // Any
  2133. RunValidJsonTest(
  2134. "Any", REQUIRED,
  2135. R"({
  2136. "optionalAny": {
  2137. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2138. "optionalInt32": 12345
  2139. }
  2140. })",
  2141. R"(
  2142. optional_any: {
  2143. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2144. optional_int32: 12345
  2145. }
  2146. }
  2147. )");
  2148. RunValidJsonTest(
  2149. "AnyNested", REQUIRED,
  2150. R"({
  2151. "optionalAny": {
  2152. "@type": "type.googleapis.com/google.protobuf.Any",
  2153. "value": {
  2154. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2155. "optionalInt32": 12345
  2156. }
  2157. }
  2158. })",
  2159. R"(
  2160. optional_any: {
  2161. [type.googleapis.com/google.protobuf.Any] {
  2162. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2163. optional_int32: 12345
  2164. }
  2165. }
  2166. }
  2167. )");
  2168. // The special "@type" tag is not required to appear first.
  2169. RunValidJsonTest(
  2170. "AnyUnorderedTypeTag", REQUIRED,
  2171. R"({
  2172. "optionalAny": {
  2173. "optionalInt32": 12345,
  2174. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
  2175. }
  2176. })",
  2177. R"(
  2178. optional_any: {
  2179. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2180. optional_int32: 12345
  2181. }
  2182. }
  2183. )");
  2184. // Well-known types in Any.
  2185. RunValidJsonTest(
  2186. "AnyWithInt32ValueWrapper", REQUIRED,
  2187. R"({
  2188. "optionalAny": {
  2189. "@type": "type.googleapis.com/google.protobuf.Int32Value",
  2190. "value": 12345
  2191. }
  2192. })",
  2193. R"(
  2194. optional_any: {
  2195. [type.googleapis.com/google.protobuf.Int32Value] {
  2196. value: 12345
  2197. }
  2198. }
  2199. )");
  2200. RunValidJsonTest(
  2201. "AnyWithDuration", REQUIRED,
  2202. R"({
  2203. "optionalAny": {
  2204. "@type": "type.googleapis.com/google.protobuf.Duration",
  2205. "value": "1.5s"
  2206. }
  2207. })",
  2208. R"(
  2209. optional_any: {
  2210. [type.googleapis.com/google.protobuf.Duration] {
  2211. seconds: 1
  2212. nanos: 500000000
  2213. }
  2214. }
  2215. )");
  2216. RunValidJsonTest(
  2217. "AnyWithTimestamp", REQUIRED,
  2218. R"({
  2219. "optionalAny": {
  2220. "@type": "type.googleapis.com/google.protobuf.Timestamp",
  2221. "value": "1970-01-01T00:00:00Z"
  2222. }
  2223. })",
  2224. R"(
  2225. optional_any: {
  2226. [type.googleapis.com/google.protobuf.Timestamp] {
  2227. seconds: 0
  2228. nanos: 0
  2229. }
  2230. }
  2231. )");
  2232. RunValidJsonTest(
  2233. "AnyWithFieldMask", REQUIRED,
  2234. R"({
  2235. "optionalAny": {
  2236. "@type": "type.googleapis.com/google.protobuf.FieldMask",
  2237. "value": "foo,barBaz"
  2238. }
  2239. })",
  2240. R"(
  2241. optional_any: {
  2242. [type.googleapis.com/google.protobuf.FieldMask] {
  2243. paths: ["foo", "bar_baz"]
  2244. }
  2245. }
  2246. )");
  2247. RunValidJsonTest(
  2248. "AnyWithStruct", REQUIRED,
  2249. R"({
  2250. "optionalAny": {
  2251. "@type": "type.googleapis.com/google.protobuf.Struct",
  2252. "value": {
  2253. "foo": 1
  2254. }
  2255. }
  2256. })",
  2257. R"(
  2258. optional_any: {
  2259. [type.googleapis.com/google.protobuf.Struct] {
  2260. fields: {
  2261. key: "foo"
  2262. value: {
  2263. number_value: 1
  2264. }
  2265. }
  2266. }
  2267. }
  2268. )");
  2269. RunValidJsonTest(
  2270. "AnyWithValueForJsonObject", REQUIRED,
  2271. R"({
  2272. "optionalAny": {
  2273. "@type": "type.googleapis.com/google.protobuf.Value",
  2274. "value": {
  2275. "foo": 1
  2276. }
  2277. }
  2278. })",
  2279. R"(
  2280. optional_any: {
  2281. [type.googleapis.com/google.protobuf.Value] {
  2282. struct_value: {
  2283. fields: {
  2284. key: "foo"
  2285. value: {
  2286. number_value: 1
  2287. }
  2288. }
  2289. }
  2290. }
  2291. }
  2292. )");
  2293. RunValidJsonTest(
  2294. "AnyWithValueForInteger", REQUIRED,
  2295. R"({
  2296. "optionalAny": {
  2297. "@type": "type.googleapis.com/google.protobuf.Value",
  2298. "value": 1
  2299. }
  2300. })",
  2301. R"(
  2302. optional_any: {
  2303. [type.googleapis.com/google.protobuf.Value] {
  2304. number_value: 1
  2305. }
  2306. }
  2307. )");
  2308. bool ok = true;
  2309. if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt",
  2310. "These tests were listed in the failure list, but they "
  2311. "don't exist. Remove them from the failure list by "
  2312. "running:\n"
  2313. " ./update_failure_list.py " + failure_list_filename_ +
  2314. " --remove nonexistent_tests.txt")) {
  2315. ok = false;
  2316. }
  2317. if (!CheckSetEmpty(unexpected_failing_tests_, "failing_tests.txt",
  2318. "These tests failed. If they can't be fixed right now, "
  2319. "you can add them to the failure list so the overall "
  2320. "suite can succeed. Add them to the failure list by "
  2321. "running:\n"
  2322. " ./update_failure_list.py " + failure_list_filename_ +
  2323. " --add failing_tests.txt")) {
  2324. ok = false;
  2325. }
  2326. if (!CheckSetEmpty(unexpected_succeeding_tests_, "succeeding_tests.txt",
  2327. "These tests succeeded, even though they were listed in "
  2328. "the failure list. Remove them from the failure list "
  2329. "by running:\n"
  2330. " ./update_failure_list.py " + failure_list_filename_ +
  2331. " --remove succeeding_tests.txt")) {
  2332. ok = false;
  2333. }
  2334. if (verbose_) {
  2335. CheckSetEmpty(skipped_, "",
  2336. "These tests were skipped (probably because support for some "
  2337. "features is not implemented)");
  2338. }
  2339. StringAppendF(&output_,
  2340. "CONFORMANCE SUITE %s: %d successes, %d skipped, "
  2341. "%d expected failures, %d unexpected failures.\n",
  2342. ok ? "PASSED" : "FAILED", successes_, skipped_.size(),
  2343. expected_failures_, unexpected_failing_tests_.size());
  2344. StringAppendF(&output_, "\n");
  2345. output->assign(output_);
  2346. return ok;
  2347. }
  2348. } // namespace protobuf
  2349. } // namespace google