binary_json_conformance_suite.cc 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396
  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 fields with alias
  1287. RunValidJsonTest(
  1288. "EnumFieldWithAlias", REQUIRED,
  1289. R"({"optionalAliasedEnum": "ALIAS_BAZ"})",
  1290. "optional_aliased_enum: ALIAS_BAZ");
  1291. RunValidJsonTest(
  1292. "EnumFieldWithAliasUseAlias", REQUIRED,
  1293. R"({"optionalAliasedEnum": "QUX"})",
  1294. "optional_aliased_enum: ALIAS_BAZ");
  1295. RunValidJsonTest(
  1296. "EnumFieldWithAliasLowerCase", REQUIRED,
  1297. R"({"optionalAliasedEnum": "qux"})",
  1298. "optional_aliased_enum: ALIAS_BAZ");
  1299. RunValidJsonTest(
  1300. "EnumFieldWithAliasDifferentCase", REQUIRED,
  1301. R"({"optionalAliasedEnum": "bAz"})",
  1302. "optional_aliased_enum: ALIAS_BAZ");
  1303. // Enum values must be represented as strings.
  1304. ExpectParseFailureForJson(
  1305. "EnumFieldNotQuoted", REQUIRED,
  1306. R"({"optionalNestedEnum": FOO})");
  1307. // Numeric values are allowed.
  1308. RunValidJsonTest(
  1309. "EnumFieldNumericValueZero", REQUIRED,
  1310. R"({"optionalNestedEnum": 0})",
  1311. "optional_nested_enum: FOO");
  1312. RunValidJsonTest(
  1313. "EnumFieldNumericValueNonZero", REQUIRED,
  1314. R"({"optionalNestedEnum": 1})",
  1315. "optional_nested_enum: BAR");
  1316. // Unknown enum values are represented as numeric values.
  1317. RunValidJsonTestWithValidator(
  1318. "EnumFieldUnknownValue", REQUIRED,
  1319. R"({"optionalNestedEnum": 123})",
  1320. [](const Json::Value& value) {
  1321. return value["optionalNestedEnum"].type() == Json::intValue &&
  1322. value["optionalNestedEnum"].asInt() == 123;
  1323. });
  1324. // String fields.
  1325. RunValidJsonTest(
  1326. "StringField", REQUIRED,
  1327. R"({"optionalString": "Hello world!"})",
  1328. "optional_string: \"Hello world!\"");
  1329. RunValidJsonTest(
  1330. "StringFieldUnicode", REQUIRED,
  1331. // Google in Chinese.
  1332. R"({"optionalString": "谷歌"})",
  1333. R"(optional_string: "谷歌")");
  1334. RunValidJsonTest(
  1335. "StringFieldEscape", REQUIRED,
  1336. R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
  1337. R"(optional_string: "\"\\/\b\f\n\r\t")");
  1338. RunValidJsonTest(
  1339. "StringFieldUnicodeEscape", REQUIRED,
  1340. R"({"optionalString": "\u8C37\u6B4C"})",
  1341. R"(optional_string: "谷歌")");
  1342. RunValidJsonTest(
  1343. "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
  1344. R"({"optionalString": "\u8c37\u6b4c"})",
  1345. R"(optional_string: "谷歌")");
  1346. RunValidJsonTest(
  1347. "StringFieldSurrogatePair", REQUIRED,
  1348. // The character is an emoji: grinning face with smiling eyes. 😁
  1349. R"({"optionalString": "\uD83D\uDE01"})",
  1350. R"(optional_string: "\xF0\x9F\x98\x81")");
  1351. // Unicode escapes must start with "\u" (lowercase u).
  1352. ExpectParseFailureForJson(
  1353. "StringFieldUppercaseEscapeLetter", RECOMMENDED,
  1354. R"({"optionalString": "\U8C37\U6b4C"})");
  1355. ExpectParseFailureForJson(
  1356. "StringFieldInvalidEscape", RECOMMENDED,
  1357. R"({"optionalString": "\uXXXX\u6B4C"})");
  1358. ExpectParseFailureForJson(
  1359. "StringFieldUnterminatedEscape", RECOMMENDED,
  1360. R"({"optionalString": "\u8C3"})");
  1361. ExpectParseFailureForJson(
  1362. "StringFieldUnpairedHighSurrogate", RECOMMENDED,
  1363. R"({"optionalString": "\uD800"})");
  1364. ExpectParseFailureForJson(
  1365. "StringFieldUnpairedLowSurrogate", RECOMMENDED,
  1366. R"({"optionalString": "\uDC00"})");
  1367. ExpectParseFailureForJson(
  1368. "StringFieldSurrogateInWrongOrder", RECOMMENDED,
  1369. R"({"optionalString": "\uDE01\uD83D"})");
  1370. ExpectParseFailureForJson(
  1371. "StringFieldNotAString", REQUIRED,
  1372. R"({"optionalString": 12345})");
  1373. // Bytes fields.
  1374. RunValidJsonTest(
  1375. "BytesField", REQUIRED,
  1376. R"({"optionalBytes": "AQI="})",
  1377. R"(optional_bytes: "\x01\x02")");
  1378. RunValidJsonTest(
  1379. "BytesFieldBase64Url", RECOMMENDED,
  1380. R"({"optionalBytes": "-_"})",
  1381. R"(optional_bytes: "\xfb")");
  1382. // Message fields.
  1383. RunValidJsonTest(
  1384. "MessageField", REQUIRED,
  1385. R"({"optionalNestedMessage": {"a": 1234}})",
  1386. "optional_nested_message: {a: 1234}");
  1387. // Oneof fields.
  1388. ExpectParseFailureForJson(
  1389. "OneofFieldDuplicate", REQUIRED,
  1390. R"({"oneofUint32": 1, "oneofString": "test"})");
  1391. // Ensure zero values for oneof make it out/backs.
  1392. TestAllTypesProto3 messageProto3;
  1393. TestAllTypesProto2 messageProto2;
  1394. TestOneofMessage(messageProto3, true);
  1395. TestOneofMessage(messageProto2, false);
  1396. RunValidJsonTest(
  1397. "OneofZeroUint32", RECOMMENDED,
  1398. R"({"oneofUint32": 0})", "oneof_uint32: 0");
  1399. RunValidJsonTest(
  1400. "OneofZeroMessage", RECOMMENDED,
  1401. R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
  1402. RunValidJsonTest(
  1403. "OneofZeroString", RECOMMENDED,
  1404. R"({"oneofString": ""})", "oneof_string: \"\"");
  1405. RunValidJsonTest(
  1406. "OneofZeroBytes", RECOMMENDED,
  1407. R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
  1408. RunValidJsonTest(
  1409. "OneofZeroBool", RECOMMENDED,
  1410. R"({"oneofBool": false})", "oneof_bool: false");
  1411. RunValidJsonTest(
  1412. "OneofZeroUint64", RECOMMENDED,
  1413. R"({"oneofUint64": 0})", "oneof_uint64: 0");
  1414. RunValidJsonTest(
  1415. "OneofZeroFloat", RECOMMENDED,
  1416. R"({"oneofFloat": 0.0})", "oneof_float: 0");
  1417. RunValidJsonTest(
  1418. "OneofZeroDouble", RECOMMENDED,
  1419. R"({"oneofDouble": 0.0})", "oneof_double: 0");
  1420. RunValidJsonTest(
  1421. "OneofZeroEnum", RECOMMENDED,
  1422. R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
  1423. // Repeated fields.
  1424. RunValidJsonTest(
  1425. "PrimitiveRepeatedField", REQUIRED,
  1426. R"({"repeatedInt32": [1, 2, 3, 4]})",
  1427. "repeated_int32: [1, 2, 3, 4]");
  1428. RunValidJsonTest(
  1429. "EnumRepeatedField", REQUIRED,
  1430. R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
  1431. "repeated_nested_enum: [FOO, BAR, BAZ]");
  1432. RunValidJsonTest(
  1433. "StringRepeatedField", REQUIRED,
  1434. R"({"repeatedString": ["Hello", "world"]})",
  1435. R"(repeated_string: ["Hello", "world"])");
  1436. RunValidJsonTest(
  1437. "BytesRepeatedField", REQUIRED,
  1438. R"({"repeatedBytes": ["AAEC", "AQI="]})",
  1439. R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
  1440. RunValidJsonTest(
  1441. "MessageRepeatedField", REQUIRED,
  1442. R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
  1443. "repeated_nested_message: {a: 1234}"
  1444. "repeated_nested_message: {a: 5678}");
  1445. // Repeated field elements are of incorrect type.
  1446. ExpectParseFailureForJson(
  1447. "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
  1448. R"({"repeatedInt32": [1, false, 3, 4]})");
  1449. ExpectParseFailureForJson(
  1450. "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
  1451. R"({"repeatedInt32": [1, 2, "name", 4]})");
  1452. ExpectParseFailureForJson(
  1453. "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
  1454. R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
  1455. ExpectParseFailureForJson(
  1456. "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
  1457. R"({"repeatedString": ["1", 2, "3", "4"]})");
  1458. ExpectParseFailureForJson(
  1459. "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
  1460. R"({"repeatedString": ["1", "2", false, "4"]})");
  1461. ExpectParseFailureForJson(
  1462. "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
  1463. R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
  1464. ExpectParseFailureForJson(
  1465. "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
  1466. R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
  1467. ExpectParseFailureForJson(
  1468. "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
  1469. R"({"repeatedNestedMessage": [{"a": 1}, false]})");
  1470. ExpectParseFailureForJson(
  1471. "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
  1472. R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
  1473. // Trailing comma in the repeated field is not allowed.
  1474. ExpectParseFailureForJson(
  1475. "RepeatedFieldTrailingComma", RECOMMENDED,
  1476. R"({"repeatedInt32": [1, 2, 3, 4,]})");
  1477. ExpectParseFailureForJson(
  1478. "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
  1479. "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
  1480. ExpectParseFailureForJson(
  1481. "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
  1482. "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
  1483. ExpectParseFailureForJson(
  1484. "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
  1485. "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}");
  1486. // Map fields.
  1487. RunValidJsonTest(
  1488. "Int32MapField", REQUIRED,
  1489. R"({"mapInt32Int32": {"1": 2, "3": 4}})",
  1490. "map_int32_int32: {key: 1 value: 2}"
  1491. "map_int32_int32: {key: 3 value: 4}");
  1492. ExpectParseFailureForJson(
  1493. "Int32MapFieldKeyNotQuoted", RECOMMENDED,
  1494. R"({"mapInt32Int32": {1: 2, 3: 4}})");
  1495. RunValidJsonTest(
  1496. "Uint32MapField", REQUIRED,
  1497. R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
  1498. "map_uint32_uint32: {key: 1 value: 2}"
  1499. "map_uint32_uint32: {key: 3 value: 4}");
  1500. ExpectParseFailureForJson(
  1501. "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
  1502. R"({"mapUint32Uint32": {1: 2, 3: 4}})");
  1503. RunValidJsonTest(
  1504. "Int64MapField", REQUIRED,
  1505. R"({"mapInt64Int64": {"1": 2, "3": 4}})",
  1506. "map_int64_int64: {key: 1 value: 2}"
  1507. "map_int64_int64: {key: 3 value: 4}");
  1508. ExpectParseFailureForJson(
  1509. "Int64MapFieldKeyNotQuoted", RECOMMENDED,
  1510. R"({"mapInt64Int64": {1: 2, 3: 4}})");
  1511. RunValidJsonTest(
  1512. "Uint64MapField", REQUIRED,
  1513. R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
  1514. "map_uint64_uint64: {key: 1 value: 2}"
  1515. "map_uint64_uint64: {key: 3 value: 4}");
  1516. ExpectParseFailureForJson(
  1517. "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
  1518. R"({"mapUint64Uint64": {1: 2, 3: 4}})");
  1519. RunValidJsonTest(
  1520. "BoolMapField", REQUIRED,
  1521. R"({"mapBoolBool": {"true": true, "false": false}})",
  1522. "map_bool_bool: {key: true value: true}"
  1523. "map_bool_bool: {key: false value: false}");
  1524. ExpectParseFailureForJson(
  1525. "BoolMapFieldKeyNotQuoted", RECOMMENDED,
  1526. R"({"mapBoolBool": {true: true, false: false}})");
  1527. RunValidJsonTest(
  1528. "MessageMapField", REQUIRED,
  1529. R"({
  1530. "mapStringNestedMessage": {
  1531. "hello": {"a": 1234},
  1532. "world": {"a": 5678}
  1533. }
  1534. })",
  1535. R"(
  1536. map_string_nested_message: {
  1537. key: "hello"
  1538. value: {a: 1234}
  1539. }
  1540. map_string_nested_message: {
  1541. key: "world"
  1542. value: {a: 5678}
  1543. }
  1544. )");
  1545. // Since Map keys are represented as JSON strings, escaping should be allowed.
  1546. RunValidJsonTest(
  1547. "Int32MapEscapedKey", REQUIRED,
  1548. R"({"mapInt32Int32": {"\u0031": 2}})",
  1549. "map_int32_int32: {key: 1 value: 2}");
  1550. RunValidJsonTest(
  1551. "Int64MapEscapedKey", REQUIRED,
  1552. R"({"mapInt64Int64": {"\u0031": 2}})",
  1553. "map_int64_int64: {key: 1 value: 2}");
  1554. RunValidJsonTest(
  1555. "BoolMapEscapedKey", REQUIRED,
  1556. R"({"mapBoolBool": {"tr\u0075e": true}})",
  1557. "map_bool_bool: {key: true value: true}");
  1558. // "null" is accepted for all fields types.
  1559. RunValidJsonTest(
  1560. "AllFieldAcceptNull", REQUIRED,
  1561. R"({
  1562. "optionalInt32": null,
  1563. "optionalInt64": null,
  1564. "optionalUint32": null,
  1565. "optionalUint64": null,
  1566. "optionalSint32": null,
  1567. "optionalSint64": null,
  1568. "optionalFixed32": null,
  1569. "optionalFixed64": null,
  1570. "optionalSfixed32": null,
  1571. "optionalSfixed64": null,
  1572. "optionalFloat": null,
  1573. "optionalDouble": null,
  1574. "optionalBool": null,
  1575. "optionalString": null,
  1576. "optionalBytes": null,
  1577. "optionalNestedEnum": null,
  1578. "optionalNestedMessage": null,
  1579. "repeatedInt32": null,
  1580. "repeatedInt64": null,
  1581. "repeatedUint32": null,
  1582. "repeatedUint64": null,
  1583. "repeatedSint32": null,
  1584. "repeatedSint64": null,
  1585. "repeatedFixed32": null,
  1586. "repeatedFixed64": null,
  1587. "repeatedSfixed32": null,
  1588. "repeatedSfixed64": null,
  1589. "repeatedFloat": null,
  1590. "repeatedDouble": null,
  1591. "repeatedBool": null,
  1592. "repeatedString": null,
  1593. "repeatedBytes": null,
  1594. "repeatedNestedEnum": null,
  1595. "repeatedNestedMessage": null,
  1596. "mapInt32Int32": null,
  1597. "mapBoolBool": null,
  1598. "mapStringNestedMessage": null
  1599. })",
  1600. "");
  1601. // Repeated field elements cannot be null.
  1602. ExpectParseFailureForJson(
  1603. "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
  1604. R"({"repeatedInt32": [1, null, 2]})");
  1605. ExpectParseFailureForJson(
  1606. "RepeatedFieldMessageElementIsNull", RECOMMENDED,
  1607. R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
  1608. // Map field keys cannot be null.
  1609. ExpectParseFailureForJson(
  1610. "MapFieldKeyIsNull", RECOMMENDED,
  1611. R"({"mapInt32Int32": {null: 1}})");
  1612. // Map field values cannot be null.
  1613. ExpectParseFailureForJson(
  1614. "MapFieldValueIsNull", RECOMMENDED,
  1615. R"({"mapInt32Int32": {"0": null}})");
  1616. // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
  1617. // quotes.
  1618. ExpectParseFailureForJson(
  1619. "StringFieldSingleQuoteKey", RECOMMENDED,
  1620. R"({'optionalString': "Hello world!"})");
  1621. ExpectParseFailureForJson(
  1622. "StringFieldSingleQuoteValue", RECOMMENDED,
  1623. R"({"optionalString": 'Hello world!'})");
  1624. ExpectParseFailureForJson(
  1625. "StringFieldSingleQuoteBoth", RECOMMENDED,
  1626. R"({'optionalString': 'Hello world!'})");
  1627. // Unknown fields.
  1628. {
  1629. TestAllTypesProto3 messageProto3;
  1630. TestAllTypesProto2 messageProto2;
  1631. //TODO(yilunchong): update this behavior when unknown field's behavior
  1632. // changed in open source. Also delete
  1633. // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput
  1634. // from failure list of python_cpp python java
  1635. TestUnknownMessage(messageProto3, true);
  1636. TestUnknownMessage(messageProto2, false);
  1637. }
  1638. // Wrapper types.
  1639. RunValidJsonTest(
  1640. "OptionalBoolWrapper", REQUIRED,
  1641. R"({"optionalBoolWrapper": false})",
  1642. "optional_bool_wrapper: {value: false}");
  1643. RunValidJsonTest(
  1644. "OptionalInt32Wrapper", REQUIRED,
  1645. R"({"optionalInt32Wrapper": 0})",
  1646. "optional_int32_wrapper: {value: 0}");
  1647. RunValidJsonTest(
  1648. "OptionalUint32Wrapper", REQUIRED,
  1649. R"({"optionalUint32Wrapper": 0})",
  1650. "optional_uint32_wrapper: {value: 0}");
  1651. RunValidJsonTest(
  1652. "OptionalInt64Wrapper", REQUIRED,
  1653. R"({"optionalInt64Wrapper": 0})",
  1654. "optional_int64_wrapper: {value: 0}");
  1655. RunValidJsonTest(
  1656. "OptionalUint64Wrapper", REQUIRED,
  1657. R"({"optionalUint64Wrapper": 0})",
  1658. "optional_uint64_wrapper: {value: 0}");
  1659. RunValidJsonTest(
  1660. "OptionalFloatWrapper", REQUIRED,
  1661. R"({"optionalFloatWrapper": 0})",
  1662. "optional_float_wrapper: {value: 0}");
  1663. RunValidJsonTest(
  1664. "OptionalDoubleWrapper", REQUIRED,
  1665. R"({"optionalDoubleWrapper": 0})",
  1666. "optional_double_wrapper: {value: 0}");
  1667. RunValidJsonTest(
  1668. "OptionalStringWrapper", REQUIRED,
  1669. R"({"optionalStringWrapper": ""})",
  1670. R"(optional_string_wrapper: {value: ""})");
  1671. RunValidJsonTest(
  1672. "OptionalBytesWrapper", REQUIRED,
  1673. R"({"optionalBytesWrapper": ""})",
  1674. R"(optional_bytes_wrapper: {value: ""})");
  1675. RunValidJsonTest(
  1676. "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
  1677. R"({
  1678. "optionalBoolWrapper": true,
  1679. "optionalInt32Wrapper": 1,
  1680. "optionalUint32Wrapper": 1,
  1681. "optionalInt64Wrapper": "1",
  1682. "optionalUint64Wrapper": "1",
  1683. "optionalFloatWrapper": 1,
  1684. "optionalDoubleWrapper": 1,
  1685. "optionalStringWrapper": "1",
  1686. "optionalBytesWrapper": "AQI="
  1687. })",
  1688. R"(
  1689. optional_bool_wrapper: {value: true}
  1690. optional_int32_wrapper: {value: 1}
  1691. optional_uint32_wrapper: {value: 1}
  1692. optional_int64_wrapper: {value: 1}
  1693. optional_uint64_wrapper: {value: 1}
  1694. optional_float_wrapper: {value: 1}
  1695. optional_double_wrapper: {value: 1}
  1696. optional_string_wrapper: {value: "1"}
  1697. optional_bytes_wrapper: {value: "\x01\x02"}
  1698. )");
  1699. RunValidJsonTest(
  1700. "RepeatedBoolWrapper", REQUIRED,
  1701. R"({"repeatedBoolWrapper": [true, false]})",
  1702. "repeated_bool_wrapper: {value: true}"
  1703. "repeated_bool_wrapper: {value: false}");
  1704. RunValidJsonTest(
  1705. "RepeatedInt32Wrapper", REQUIRED,
  1706. R"({"repeatedInt32Wrapper": [0, 1]})",
  1707. "repeated_int32_wrapper: {value: 0}"
  1708. "repeated_int32_wrapper: {value: 1}");
  1709. RunValidJsonTest(
  1710. "RepeatedUint32Wrapper", REQUIRED,
  1711. R"({"repeatedUint32Wrapper": [0, 1]})",
  1712. "repeated_uint32_wrapper: {value: 0}"
  1713. "repeated_uint32_wrapper: {value: 1}");
  1714. RunValidJsonTest(
  1715. "RepeatedInt64Wrapper", REQUIRED,
  1716. R"({"repeatedInt64Wrapper": [0, 1]})",
  1717. "repeated_int64_wrapper: {value: 0}"
  1718. "repeated_int64_wrapper: {value: 1}");
  1719. RunValidJsonTest(
  1720. "RepeatedUint64Wrapper", REQUIRED,
  1721. R"({"repeatedUint64Wrapper": [0, 1]})",
  1722. "repeated_uint64_wrapper: {value: 0}"
  1723. "repeated_uint64_wrapper: {value: 1}");
  1724. RunValidJsonTest(
  1725. "RepeatedFloatWrapper", REQUIRED,
  1726. R"({"repeatedFloatWrapper": [0, 1]})",
  1727. "repeated_float_wrapper: {value: 0}"
  1728. "repeated_float_wrapper: {value: 1}");
  1729. RunValidJsonTest(
  1730. "RepeatedDoubleWrapper", REQUIRED,
  1731. R"({"repeatedDoubleWrapper": [0, 1]})",
  1732. "repeated_double_wrapper: {value: 0}"
  1733. "repeated_double_wrapper: {value: 1}");
  1734. RunValidJsonTest(
  1735. "RepeatedStringWrapper", REQUIRED,
  1736. R"({"repeatedStringWrapper": ["", "AQI="]})",
  1737. R"(
  1738. repeated_string_wrapper: {value: ""}
  1739. repeated_string_wrapper: {value: "AQI="}
  1740. )");
  1741. RunValidJsonTest(
  1742. "RepeatedBytesWrapper", REQUIRED,
  1743. R"({"repeatedBytesWrapper": ["", "AQI="]})",
  1744. R"(
  1745. repeated_bytes_wrapper: {value: ""}
  1746. repeated_bytes_wrapper: {value: "\x01\x02"}
  1747. )");
  1748. RunValidJsonTest(
  1749. "WrapperTypesWithNullValue", REQUIRED,
  1750. R"({
  1751. "optionalBoolWrapper": null,
  1752. "optionalInt32Wrapper": null,
  1753. "optionalUint32Wrapper": null,
  1754. "optionalInt64Wrapper": null,
  1755. "optionalUint64Wrapper": null,
  1756. "optionalFloatWrapper": null,
  1757. "optionalDoubleWrapper": null,
  1758. "optionalStringWrapper": null,
  1759. "optionalBytesWrapper": null,
  1760. "repeatedBoolWrapper": null,
  1761. "repeatedInt32Wrapper": null,
  1762. "repeatedUint32Wrapper": null,
  1763. "repeatedInt64Wrapper": null,
  1764. "repeatedUint64Wrapper": null,
  1765. "repeatedFloatWrapper": null,
  1766. "repeatedDoubleWrapper": null,
  1767. "repeatedStringWrapper": null,
  1768. "repeatedBytesWrapper": null
  1769. })",
  1770. "");
  1771. // Duration
  1772. RunValidJsonTest(
  1773. "DurationMinValue", REQUIRED,
  1774. R"({"optionalDuration": "-315576000000.999999999s"})",
  1775. "optional_duration: {seconds: -315576000000 nanos: -999999999}");
  1776. RunValidJsonTest(
  1777. "DurationMaxValue", REQUIRED,
  1778. R"({"optionalDuration": "315576000000.999999999s"})",
  1779. "optional_duration: {seconds: 315576000000 nanos: 999999999}");
  1780. RunValidJsonTest(
  1781. "DurationRepeatedValue", REQUIRED,
  1782. R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
  1783. "repeated_duration: {seconds: 1 nanos: 500000000}"
  1784. "repeated_duration: {seconds: -1 nanos: -500000000}");
  1785. RunValidJsonTest(
  1786. "DurationNull", REQUIRED,
  1787. R"({"optionalDuration": null})",
  1788. "");
  1789. ExpectParseFailureForJson(
  1790. "DurationMissingS", REQUIRED,
  1791. R"({"optionalDuration": "1"})");
  1792. ExpectParseFailureForJson(
  1793. "DurationJsonInputTooSmall", REQUIRED,
  1794. R"({"optionalDuration": "-315576000001.000000000s"})");
  1795. ExpectParseFailureForJson(
  1796. "DurationJsonInputTooLarge", REQUIRED,
  1797. R"({"optionalDuration": "315576000001.000000000s"})");
  1798. ExpectSerializeFailureForJson(
  1799. "DurationProtoInputTooSmall", REQUIRED,
  1800. "optional_duration: {seconds: -315576000001 nanos: 0}");
  1801. ExpectSerializeFailureForJson(
  1802. "DurationProtoInputTooLarge", REQUIRED,
  1803. "optional_duration: {seconds: 315576000001 nanos: 0}");
  1804. RunValidJsonTestWithValidator(
  1805. "DurationHasZeroFractionalDigit", RECOMMENDED,
  1806. R"({"optionalDuration": "1.000000000s"})",
  1807. [](const Json::Value& value) {
  1808. return value["optionalDuration"].asString() == "1s";
  1809. });
  1810. RunValidJsonTestWithValidator(
  1811. "DurationHas3FractionalDigits", RECOMMENDED,
  1812. R"({"optionalDuration": "1.010000000s"})",
  1813. [](const Json::Value& value) {
  1814. return value["optionalDuration"].asString() == "1.010s";
  1815. });
  1816. RunValidJsonTestWithValidator(
  1817. "DurationHas6FractionalDigits", RECOMMENDED,
  1818. R"({"optionalDuration": "1.000010000s"})",
  1819. [](const Json::Value& value) {
  1820. return value["optionalDuration"].asString() == "1.000010s";
  1821. });
  1822. RunValidJsonTestWithValidator(
  1823. "DurationHas9FractionalDigits", RECOMMENDED,
  1824. R"({"optionalDuration": "1.000000010s"})",
  1825. [](const Json::Value& value) {
  1826. return value["optionalDuration"].asString() == "1.000000010s";
  1827. });
  1828. // Timestamp
  1829. RunValidJsonTest(
  1830. "TimestampMinValue", REQUIRED,
  1831. R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
  1832. "optional_timestamp: {seconds: -62135596800}");
  1833. RunValidJsonTest(
  1834. "TimestampMaxValue", REQUIRED,
  1835. R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
  1836. "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1837. RunValidJsonTest(
  1838. "TimestampRepeatedValue", REQUIRED,
  1839. R"({
  1840. "repeatedTimestamp": [
  1841. "0001-01-01T00:00:00Z",
  1842. "9999-12-31T23:59:59.999999999Z"
  1843. ]
  1844. })",
  1845. "repeated_timestamp: {seconds: -62135596800}"
  1846. "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1847. RunValidJsonTest(
  1848. "TimestampWithPositiveOffset", REQUIRED,
  1849. R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
  1850. "optional_timestamp: {seconds: 0}");
  1851. RunValidJsonTest(
  1852. "TimestampWithNegativeOffset", REQUIRED,
  1853. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  1854. "optional_timestamp: {seconds: 0}");
  1855. RunValidJsonTest(
  1856. "TimestampNull", REQUIRED,
  1857. R"({"optionalTimestamp": null})",
  1858. "");
  1859. ExpectParseFailureForJson(
  1860. "TimestampJsonInputTooSmall", REQUIRED,
  1861. R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  1862. ExpectParseFailureForJson(
  1863. "TimestampJsonInputTooLarge", REQUIRED,
  1864. R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  1865. ExpectParseFailureForJson(
  1866. "TimestampJsonInputMissingZ", REQUIRED,
  1867. R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  1868. ExpectParseFailureForJson(
  1869. "TimestampJsonInputMissingT", REQUIRED,
  1870. R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  1871. ExpectParseFailureForJson(
  1872. "TimestampJsonInputLowercaseZ", REQUIRED,
  1873. R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  1874. ExpectParseFailureForJson(
  1875. "TimestampJsonInputLowercaseT", REQUIRED,
  1876. R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  1877. ExpectSerializeFailureForJson(
  1878. "TimestampProtoInputTooSmall", REQUIRED,
  1879. "optional_timestamp: {seconds: -62135596801}");
  1880. ExpectSerializeFailureForJson(
  1881. "TimestampProtoInputTooLarge", REQUIRED,
  1882. "optional_timestamp: {seconds: 253402300800}");
  1883. RunValidJsonTestWithValidator(
  1884. "TimestampZeroNormalized", RECOMMENDED,
  1885. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  1886. [](const Json::Value& value) {
  1887. return value["optionalTimestamp"].asString() ==
  1888. "1970-01-01T00:00:00Z";
  1889. });
  1890. RunValidJsonTestWithValidator(
  1891. "TimestampHasZeroFractionalDigit", RECOMMENDED,
  1892. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
  1893. [](const Json::Value& value) {
  1894. return value["optionalTimestamp"].asString() ==
  1895. "1970-01-01T00:00:00Z";
  1896. });
  1897. RunValidJsonTestWithValidator(
  1898. "TimestampHas3FractionalDigits", RECOMMENDED,
  1899. R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
  1900. [](const Json::Value& value) {
  1901. return value["optionalTimestamp"].asString() ==
  1902. "1970-01-01T00:00:00.010Z";
  1903. });
  1904. RunValidJsonTestWithValidator(
  1905. "TimestampHas6FractionalDigits", RECOMMENDED,
  1906. R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
  1907. [](const Json::Value& value) {
  1908. return value["optionalTimestamp"].asString() ==
  1909. "1970-01-01T00:00:00.000010Z";
  1910. });
  1911. RunValidJsonTestWithValidator(
  1912. "TimestampHas9FractionalDigits", RECOMMENDED,
  1913. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
  1914. [](const Json::Value& value) {
  1915. return value["optionalTimestamp"].asString() ==
  1916. "1970-01-01T00:00:00.000000010Z";
  1917. });
  1918. // FieldMask
  1919. RunValidJsonTest(
  1920. "FieldMask", REQUIRED,
  1921. R"({"optionalFieldMask": "foo,barBaz"})",
  1922. R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  1923. RunValidJsonTest(
  1924. "EmptyFieldMask", REQUIRED,
  1925. R"({"optionalFieldMask": ""})",
  1926. R"(optional_field_mask: {})");
  1927. ExpectParseFailureForJson(
  1928. "FieldMaskInvalidCharacter", RECOMMENDED,
  1929. R"({"optionalFieldMask": "foo,bar_bar"})");
  1930. ExpectSerializeFailureForJson(
  1931. "FieldMaskPathsDontRoundTrip", RECOMMENDED,
  1932. R"(optional_field_mask: {paths: "fooBar"})");
  1933. ExpectSerializeFailureForJson(
  1934. "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
  1935. R"(optional_field_mask: {paths: "foo_3_bar"})");
  1936. ExpectSerializeFailureForJson(
  1937. "FieldMaskTooManyUnderscore", RECOMMENDED,
  1938. R"(optional_field_mask: {paths: "foo__bar"})");
  1939. // Struct
  1940. RunValidJsonTest(
  1941. "Struct", REQUIRED,
  1942. R"({
  1943. "optionalStruct": {
  1944. "nullValue": null,
  1945. "intValue": 1234,
  1946. "boolValue": true,
  1947. "doubleValue": 1234.5678,
  1948. "stringValue": "Hello world!",
  1949. "listValue": [1234, "5678"],
  1950. "objectValue": {
  1951. "value": 0
  1952. }
  1953. }
  1954. })",
  1955. R"(
  1956. optional_struct: {
  1957. fields: {
  1958. key: "nullValue"
  1959. value: {null_value: NULL_VALUE}
  1960. }
  1961. fields: {
  1962. key: "intValue"
  1963. value: {number_value: 1234}
  1964. }
  1965. fields: {
  1966. key: "boolValue"
  1967. value: {bool_value: true}
  1968. }
  1969. fields: {
  1970. key: "doubleValue"
  1971. value: {number_value: 1234.5678}
  1972. }
  1973. fields: {
  1974. key: "stringValue"
  1975. value: {string_value: "Hello world!"}
  1976. }
  1977. fields: {
  1978. key: "listValue"
  1979. value: {
  1980. list_value: {
  1981. values: {
  1982. number_value: 1234
  1983. }
  1984. values: {
  1985. string_value: "5678"
  1986. }
  1987. }
  1988. }
  1989. }
  1990. fields: {
  1991. key: "objectValue"
  1992. value: {
  1993. struct_value: {
  1994. fields: {
  1995. key: "value"
  1996. value: {
  1997. number_value: 0
  1998. }
  1999. }
  2000. }
  2001. }
  2002. }
  2003. }
  2004. )");
  2005. // Value
  2006. RunValidJsonTest(
  2007. "ValueAcceptInteger", REQUIRED,
  2008. R"({"optionalValue": 1})",
  2009. "optional_value: { number_value: 1}");
  2010. RunValidJsonTest(
  2011. "ValueAcceptFloat", REQUIRED,
  2012. R"({"optionalValue": 1.5})",
  2013. "optional_value: { number_value: 1.5}");
  2014. RunValidJsonTest(
  2015. "ValueAcceptBool", REQUIRED,
  2016. R"({"optionalValue": false})",
  2017. "optional_value: { bool_value: false}");
  2018. RunValidJsonTest(
  2019. "ValueAcceptNull", REQUIRED,
  2020. R"({"optionalValue": null})",
  2021. "optional_value: { null_value: NULL_VALUE}");
  2022. RunValidJsonTest(
  2023. "ValueAcceptString", REQUIRED,
  2024. R"({"optionalValue": "hello"})",
  2025. R"(optional_value: { string_value: "hello"})");
  2026. RunValidJsonTest(
  2027. "ValueAcceptList", REQUIRED,
  2028. R"({"optionalValue": [0, "hello"]})",
  2029. R"(
  2030. optional_value: {
  2031. list_value: {
  2032. values: {
  2033. number_value: 0
  2034. }
  2035. values: {
  2036. string_value: "hello"
  2037. }
  2038. }
  2039. }
  2040. )");
  2041. RunValidJsonTest(
  2042. "ValueAcceptObject", REQUIRED,
  2043. R"({"optionalValue": {"value": 1}})",
  2044. R"(
  2045. optional_value: {
  2046. struct_value: {
  2047. fields: {
  2048. key: "value"
  2049. value: {
  2050. number_value: 1
  2051. }
  2052. }
  2053. }
  2054. }
  2055. )");
  2056. // Any
  2057. RunValidJsonTest(
  2058. "Any", REQUIRED,
  2059. R"({
  2060. "optionalAny": {
  2061. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2062. "optionalInt32": 12345
  2063. }
  2064. })",
  2065. R"(
  2066. optional_any: {
  2067. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2068. optional_int32: 12345
  2069. }
  2070. }
  2071. )");
  2072. RunValidJsonTest(
  2073. "AnyNested", REQUIRED,
  2074. R"({
  2075. "optionalAny": {
  2076. "@type": "type.googleapis.com/google.protobuf.Any",
  2077. "value": {
  2078. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2079. "optionalInt32": 12345
  2080. }
  2081. }
  2082. })",
  2083. R"(
  2084. optional_any: {
  2085. [type.googleapis.com/google.protobuf.Any] {
  2086. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2087. optional_int32: 12345
  2088. }
  2089. }
  2090. }
  2091. )");
  2092. // The special "@type" tag is not required to appear first.
  2093. RunValidJsonTest(
  2094. "AnyUnorderedTypeTag", REQUIRED,
  2095. R"({
  2096. "optionalAny": {
  2097. "optionalInt32": 12345,
  2098. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
  2099. }
  2100. })",
  2101. R"(
  2102. optional_any: {
  2103. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2104. optional_int32: 12345
  2105. }
  2106. }
  2107. )");
  2108. // Well-known types in Any.
  2109. RunValidJsonTest(
  2110. "AnyWithInt32ValueWrapper", REQUIRED,
  2111. R"({
  2112. "optionalAny": {
  2113. "@type": "type.googleapis.com/google.protobuf.Int32Value",
  2114. "value": 12345
  2115. }
  2116. })",
  2117. R"(
  2118. optional_any: {
  2119. [type.googleapis.com/google.protobuf.Int32Value] {
  2120. value: 12345
  2121. }
  2122. }
  2123. )");
  2124. RunValidJsonTest(
  2125. "AnyWithDuration", REQUIRED,
  2126. R"({
  2127. "optionalAny": {
  2128. "@type": "type.googleapis.com/google.protobuf.Duration",
  2129. "value": "1.5s"
  2130. }
  2131. })",
  2132. R"(
  2133. optional_any: {
  2134. [type.googleapis.com/google.protobuf.Duration] {
  2135. seconds: 1
  2136. nanos: 500000000
  2137. }
  2138. }
  2139. )");
  2140. RunValidJsonTest(
  2141. "AnyWithTimestamp", REQUIRED,
  2142. R"({
  2143. "optionalAny": {
  2144. "@type": "type.googleapis.com/google.protobuf.Timestamp",
  2145. "value": "1970-01-01T00:00:00Z"
  2146. }
  2147. })",
  2148. R"(
  2149. optional_any: {
  2150. [type.googleapis.com/google.protobuf.Timestamp] {
  2151. seconds: 0
  2152. nanos: 0
  2153. }
  2154. }
  2155. )");
  2156. RunValidJsonTest(
  2157. "AnyWithFieldMask", REQUIRED,
  2158. R"({
  2159. "optionalAny": {
  2160. "@type": "type.googleapis.com/google.protobuf.FieldMask",
  2161. "value": "foo,barBaz"
  2162. }
  2163. })",
  2164. R"(
  2165. optional_any: {
  2166. [type.googleapis.com/google.protobuf.FieldMask] {
  2167. paths: ["foo", "bar_baz"]
  2168. }
  2169. }
  2170. )");
  2171. RunValidJsonTest(
  2172. "AnyWithStruct", REQUIRED,
  2173. R"({
  2174. "optionalAny": {
  2175. "@type": "type.googleapis.com/google.protobuf.Struct",
  2176. "value": {
  2177. "foo": 1
  2178. }
  2179. }
  2180. })",
  2181. R"(
  2182. optional_any: {
  2183. [type.googleapis.com/google.protobuf.Struct] {
  2184. fields: {
  2185. key: "foo"
  2186. value: {
  2187. number_value: 1
  2188. }
  2189. }
  2190. }
  2191. }
  2192. )");
  2193. RunValidJsonTest(
  2194. "AnyWithValueForJsonObject", REQUIRED,
  2195. R"({
  2196. "optionalAny": {
  2197. "@type": "type.googleapis.com/google.protobuf.Value",
  2198. "value": {
  2199. "foo": 1
  2200. }
  2201. }
  2202. })",
  2203. R"(
  2204. optional_any: {
  2205. [type.googleapis.com/google.protobuf.Value] {
  2206. struct_value: {
  2207. fields: {
  2208. key: "foo"
  2209. value: {
  2210. number_value: 1
  2211. }
  2212. }
  2213. }
  2214. }
  2215. }
  2216. )");
  2217. RunValidJsonTest(
  2218. "AnyWithValueForInteger", REQUIRED,
  2219. R"({
  2220. "optionalAny": {
  2221. "@type": "type.googleapis.com/google.protobuf.Value",
  2222. "value": 1
  2223. }
  2224. })",
  2225. R"(
  2226. optional_any: {
  2227. [type.googleapis.com/google.protobuf.Value] {
  2228. number_value: 1
  2229. }
  2230. }
  2231. )");
  2232. RunValidJsonIgnoreUnknownTest(
  2233. "IgnoreUnknownJsonNumber", REQUIRED,
  2234. R"({
  2235. "unknown": 1
  2236. })",
  2237. "");
  2238. RunValidJsonIgnoreUnknownTest(
  2239. "IgnoreUnknownJsonString", REQUIRED,
  2240. R"({
  2241. "unknown": "a"
  2242. })",
  2243. "");
  2244. RunValidJsonIgnoreUnknownTest(
  2245. "IgnoreUnknownJsonTrue", REQUIRED,
  2246. R"({
  2247. "unknown": true
  2248. })",
  2249. "");
  2250. RunValidJsonIgnoreUnknownTest(
  2251. "IgnoreUnknownJsonFalse", REQUIRED,
  2252. R"({
  2253. "unknown": false
  2254. })",
  2255. "");
  2256. RunValidJsonIgnoreUnknownTest(
  2257. "IgnoreUnknownJsonNull", REQUIRED,
  2258. R"({
  2259. "unknown": null
  2260. })",
  2261. "");
  2262. RunValidJsonIgnoreUnknownTest(
  2263. "IgnoreUnknownJsonObject", REQUIRED,
  2264. R"({
  2265. "unknown": {"a": 1}
  2266. })",
  2267. "");
  2268. }
  2269. } // namespace protobuf
  2270. } // namespace google