conformance_test.cc 65 KB

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