conformance_test.cc 83 KB

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