binary_json_conformance_suite.cc 81 KB

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