binary_json_conformance_suite.cc 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467
  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. // Hack to get the list of test failures based on whether
  602. // GOOGLE3_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER is enabled or not.
  603. conformance::FailureSet failure_set;
  604. ConformanceRequest req;
  605. ConformanceResponse res;
  606. req.set_message_type(failure_set.GetTypeName());
  607. req.set_protobuf_payload("");
  608. req.set_requested_output_format(conformance::WireFormat::PROTOBUF);
  609. RunTest("FindFailures", req, &res);
  610. GOOGLE_CHECK(failure_set.MergeFromString(res.protobuf_payload()));
  611. for (const string& failure : failure_set.failure()) {
  612. AddExpectedFailedTest(failure);
  613. }
  614. type_resolver_.reset(NewTypeResolverForDescriptorPool(
  615. kTypeUrlPrefix, DescriptorPool::generated_pool()));
  616. type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor());
  617. for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
  618. if (i == FieldDescriptor::TYPE_GROUP) continue;
  619. TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
  620. }
  621. TestIllegalTags();
  622. int64 kInt64Min = -9223372036854775808ULL;
  623. int64 kInt64Max = 9223372036854775807ULL;
  624. uint64 kUint64Max = 18446744073709551615ULL;
  625. int32 kInt32Max = 2147483647;
  626. int32 kInt32Min = -2147483648;
  627. uint32 kUint32Max = 4294967295UL;
  628. TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, {
  629. {dbl(0.1), "0.1"},
  630. {dbl(1.7976931348623157e+308), "1.7976931348623157e+308"},
  631. {dbl(2.22507385850720138309e-308), "2.22507385850720138309e-308"}
  632. });
  633. TestValidDataForType(FieldDescriptor::TYPE_FLOAT, {
  634. {flt(0.1), "0.1"},
  635. {flt(1.00000075e-36), "1.00000075e-36"},
  636. {flt(3.402823e+38), "3.402823e+38"}, // 3.40282347e+38
  637. {flt(1.17549435e-38f), "1.17549435e-38"}
  638. });
  639. TestValidDataForType(FieldDescriptor::TYPE_INT64, {
  640. {varint(12345), "12345"},
  641. {varint(kInt64Max), std::to_string(kInt64Max)},
  642. {varint(kInt64Min), std::to_string(kInt64Min)}
  643. });
  644. TestValidDataForType(FieldDescriptor::TYPE_UINT64, {
  645. {varint(12345), "12345"},
  646. {varint(kUint64Max), std::to_string(kUint64Max)},
  647. {varint(0), "0"}
  648. });
  649. TestValidDataForType(FieldDescriptor::TYPE_INT32, {
  650. {varint(12345), "12345"},
  651. {longvarint(12345, 2), "12345"},
  652. {longvarint(12345, 7), "12345"},
  653. {varint(kInt32Max), std::to_string(kInt32Max)},
  654. {varint(kInt32Min), std::to_string(kInt32Min)},
  655. {varint(1LL << 33), std::to_string(static_cast<int32>(1LL << 33))},
  656. {varint((1LL << 33) - 1),
  657. std::to_string(static_cast<int32>((1LL << 33) - 1))},
  658. });
  659. TestValidDataForType(FieldDescriptor::TYPE_UINT32, {
  660. {varint(12345), "12345"},
  661. {longvarint(12345, 2), "12345"},
  662. {longvarint(12345, 7), "12345"},
  663. {varint(kUint32Max), std::to_string(kUint32Max)}, // UINT32_MAX
  664. {varint(0), "0"},
  665. {varint(1LL << 33), std::to_string(static_cast<uint32>(1LL << 33))},
  666. {varint((1LL << 33) - 1),
  667. std::to_string(static_cast<uint32>((1LL << 33) - 1))},
  668. });
  669. TestValidDataForType(FieldDescriptor::TYPE_FIXED64, {
  670. {u64(12345), "12345"},
  671. {u64(kUint64Max), std::to_string(kUint64Max)},
  672. {u64(0), "0"}
  673. });
  674. TestValidDataForType(FieldDescriptor::TYPE_FIXED32, {
  675. {u32(12345), "12345"},
  676. {u32(kUint32Max), std::to_string(kUint32Max)}, // UINT32_MAX
  677. {u32(0), "0"}
  678. });
  679. TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, {
  680. {u64(12345), "12345"},
  681. {u64(kInt64Max), std::to_string(kInt64Max)},
  682. {u64(kInt64Min), std::to_string(kInt64Min)}
  683. });
  684. TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, {
  685. {u32(12345), "12345"},
  686. {u32(kInt32Max), std::to_string(kInt32Max)},
  687. {u32(kInt32Min), std::to_string(kInt32Min)}
  688. });
  689. TestValidDataForType(FieldDescriptor::TYPE_BOOL, {
  690. {varint(1), "true"},
  691. {varint(0), "false"},
  692. {varint(12345678), "true"}
  693. });
  694. TestValidDataForType(FieldDescriptor::TYPE_SINT32, {
  695. {zz32(12345), "12345"},
  696. {zz32(kInt32Max), std::to_string(kInt32Max)},
  697. {zz32(kInt32Min), std::to_string(kInt32Min)}
  698. });
  699. TestValidDataForType(FieldDescriptor::TYPE_SINT64, {
  700. {zz64(12345), "12345"},
  701. {zz64(kInt64Max), std::to_string(kInt64Max)},
  702. {zz64(kInt64Min), std::to_string(kInt64Min)}
  703. });
  704. TestValidDataForType(FieldDescriptor::TYPE_STRING, {
  705. {delim("Hello world!"), "\"Hello world!\""},
  706. {delim("\'\"\?\\\a\b\f\n\r\t\v"),
  707. "\"\x27\\\"\x3F\\\\\x07\x08\x0C\\n\x0D\x09\x0B\""}, // escape
  708. {delim("谷歌"), "\"谷歌\""}, // Google in Chinese
  709. {delim("\u8C37\u6B4C"), "\"谷歌\""}, // unicode escape
  710. {delim("\u8c37\u6b4c"), "\"谷歌\""}, // lowercase unicode
  711. {delim("\xF0\x9F\x98\x81"), "\"\xF0\x9F\x98\x81\""}, // emoji: 😁
  712. {delim(""), "\"\""},
  713. });
  714. // TODO(haberman):
  715. // TestValidDataForType(FieldDescriptor::TYPE_GROUP
  716. // TestValidDataForType(FieldDescriptor::TYPE_MESSAGE
  717. // TestValidDataForType(FieldDescriptor::TYPE_BYTES
  718. // TestValidDataForType(FieldDescriptor::TYPE_ENUM
  719. RunValidJsonTest("HelloWorld", REQUIRED,
  720. "{\"optionalString\":\"Hello, World!\"}",
  721. "optional_string: 'Hello, World!'");
  722. // NOTE: The spec for JSON support is still being sorted out, these may not
  723. // all be correct.
  724. // Test field name conventions.
  725. RunValidJsonTest(
  726. "FieldNameInSnakeCase", REQUIRED,
  727. R"({
  728. "fieldname1": 1,
  729. "fieldName2": 2,
  730. "FieldName3": 3,
  731. "fieldName4": 4
  732. })",
  733. R"(
  734. fieldname1: 1
  735. field_name2: 2
  736. _field_name3: 3
  737. field__name4_: 4
  738. )");
  739. RunValidJsonTest(
  740. "FieldNameWithNumbers", REQUIRED,
  741. R"({
  742. "field0name5": 5,
  743. "field0Name6": 6
  744. })",
  745. R"(
  746. field0name5: 5
  747. field_0_name6: 6
  748. )");
  749. RunValidJsonTest(
  750. "FieldNameWithMixedCases", REQUIRED,
  751. R"({
  752. "fieldName7": 7,
  753. "FieldName8": 8,
  754. "fieldName9": 9,
  755. "FieldName10": 10,
  756. "FIELDNAME11": 11,
  757. "FIELDName12": 12
  758. })",
  759. R"(
  760. fieldName7: 7
  761. FieldName8: 8
  762. field_Name9: 9
  763. Field_Name10: 10
  764. FIELD_NAME11: 11
  765. FIELD_name12: 12
  766. )");
  767. RunValidJsonTest(
  768. "FieldNameWithDoubleUnderscores", RECOMMENDED,
  769. R"({
  770. "FieldName13": 13,
  771. "FieldName14": 14,
  772. "fieldName15": 15,
  773. "fieldName16": 16,
  774. "fieldName17": 17,
  775. "FieldName18": 18
  776. })",
  777. R"(
  778. __field_name13: 13
  779. __Field_name14: 14
  780. field__name15: 15
  781. field__Name16: 16
  782. field_name17__: 17
  783. Field_name18__: 18
  784. )");
  785. // Using the original proto field name in JSON is also allowed.
  786. RunValidJsonTest(
  787. "OriginalProtoFieldName", REQUIRED,
  788. R"({
  789. "fieldname1": 1,
  790. "field_name2": 2,
  791. "_field_name3": 3,
  792. "field__name4_": 4,
  793. "field0name5": 5,
  794. "field_0_name6": 6,
  795. "fieldName7": 7,
  796. "FieldName8": 8,
  797. "field_Name9": 9,
  798. "Field_Name10": 10,
  799. "FIELD_NAME11": 11,
  800. "FIELD_name12": 12,
  801. "__field_name13": 13,
  802. "__Field_name14": 14,
  803. "field__name15": 15,
  804. "field__Name16": 16,
  805. "field_name17__": 17,
  806. "Field_name18__": 18
  807. })",
  808. R"(
  809. fieldname1: 1
  810. field_name2: 2
  811. _field_name3: 3
  812. field__name4_: 4
  813. field0name5: 5
  814. field_0_name6: 6
  815. fieldName7: 7
  816. FieldName8: 8
  817. field_Name9: 9
  818. Field_Name10: 10
  819. FIELD_NAME11: 11
  820. FIELD_name12: 12
  821. __field_name13: 13
  822. __Field_name14: 14
  823. field__name15: 15
  824. field__Name16: 16
  825. field_name17__: 17
  826. Field_name18__: 18
  827. )");
  828. // Field names can be escaped.
  829. RunValidJsonTest(
  830. "FieldNameEscaped", REQUIRED,
  831. R"({"fieldn\u0061me1": 1})",
  832. "fieldname1: 1");
  833. // String ends with escape character.
  834. ExpectParseFailureForJson(
  835. "StringEndsWithEscapeChar", RECOMMENDED,
  836. "{\"optionalString\": \"abc\\");
  837. // Field names must be quoted (or it's not valid JSON).
  838. ExpectParseFailureForJson(
  839. "FieldNameNotQuoted", RECOMMENDED,
  840. "{fieldname1: 1}");
  841. // Trailing comma is not allowed (not valid JSON).
  842. ExpectParseFailureForJson(
  843. "TrailingCommaInAnObject", RECOMMENDED,
  844. R"({"fieldname1":1,})");
  845. ExpectParseFailureForJson(
  846. "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
  847. R"({"fieldname1":1 ,})");
  848. ExpectParseFailureForJson(
  849. "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
  850. R"({"fieldname1":1 , })");
  851. ExpectParseFailureForJson(
  852. "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
  853. R"({
  854. "fieldname1":1,
  855. })");
  856. // JSON doesn't support comments.
  857. ExpectParseFailureForJson(
  858. "JsonWithComments", RECOMMENDED,
  859. R"({
  860. // This is a comment.
  861. "fieldname1": 1
  862. })");
  863. // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
  864. RunValidJsonTest(
  865. "OneLineNoSpaces", RECOMMENDED,
  866. "{\"optionalInt32\":1,\"optionalInt64\":2}",
  867. R"(
  868. optional_int32: 1
  869. optional_int64: 2
  870. )");
  871. RunValidJsonTest(
  872. "OneLineWithSpaces", RECOMMENDED,
  873. "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
  874. R"(
  875. optional_int32: 1
  876. optional_int64: 2
  877. )");
  878. RunValidJsonTest(
  879. "MultilineNoSpaces", RECOMMENDED,
  880. "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
  881. R"(
  882. optional_int32: 1
  883. optional_int64: 2
  884. )");
  885. RunValidJsonTest(
  886. "MultilineWithSpaces", RECOMMENDED,
  887. "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n",
  888. R"(
  889. optional_int32: 1
  890. optional_int64: 2
  891. )");
  892. // Missing comma between key/value pairs.
  893. ExpectParseFailureForJson(
  894. "MissingCommaOneLine", RECOMMENDED,
  895. "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
  896. ExpectParseFailureForJson(
  897. "MissingCommaMultiline", RECOMMENDED,
  898. "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}");
  899. // Duplicated field names are not allowed.
  900. ExpectParseFailureForJson(
  901. "FieldNameDuplicate", RECOMMENDED,
  902. R"({
  903. "optionalNestedMessage": {a: 1},
  904. "optionalNestedMessage": {}
  905. })");
  906. ExpectParseFailureForJson(
  907. "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
  908. R"({
  909. "optional_nested_message": {a: 1},
  910. "optionalNestedMessage": {}
  911. })");
  912. ExpectParseFailureForJson(
  913. "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
  914. R"({
  915. "optionalNestedMessage": {a: 1},
  916. "optional_nested_message": {}
  917. })");
  918. // Serializers should use lowerCamelCase by default.
  919. RunValidJsonTestWithValidator(
  920. "FieldNameInLowerCamelCase", REQUIRED,
  921. R"({
  922. "fieldname1": 1,
  923. "fieldName2": 2,
  924. "FieldName3": 3,
  925. "fieldName4": 4
  926. })",
  927. [](const Json::Value& value) {
  928. return value.isMember("fieldname1") &&
  929. value.isMember("fieldName2") &&
  930. value.isMember("FieldName3") &&
  931. value.isMember("fieldName4");
  932. });
  933. RunValidJsonTestWithValidator(
  934. "FieldNameWithNumbers", REQUIRED,
  935. R"({
  936. "field0name5": 5,
  937. "field0Name6": 6
  938. })",
  939. [](const Json::Value& value) {
  940. return value.isMember("field0name5") &&
  941. value.isMember("field0Name6");
  942. });
  943. RunValidJsonTestWithValidator(
  944. "FieldNameWithMixedCases", REQUIRED,
  945. R"({
  946. "fieldName7": 7,
  947. "FieldName8": 8,
  948. "fieldName9": 9,
  949. "FieldName10": 10,
  950. "FIELDNAME11": 11,
  951. "FIELDName12": 12
  952. })",
  953. [](const Json::Value& value) {
  954. return value.isMember("fieldName7") &&
  955. value.isMember("FieldName8") &&
  956. value.isMember("fieldName9") &&
  957. value.isMember("FieldName10") &&
  958. value.isMember("FIELDNAME11") &&
  959. value.isMember("FIELDName12");
  960. });
  961. RunValidJsonTestWithValidator(
  962. "FieldNameWithDoubleUnderscores", RECOMMENDED,
  963. R"({
  964. "FieldName13": 13,
  965. "FieldName14": 14,
  966. "fieldName15": 15,
  967. "fieldName16": 16,
  968. "fieldName17": 17,
  969. "FieldName18": 18
  970. })",
  971. [](const Json::Value& value) {
  972. return value.isMember("FieldName13") &&
  973. value.isMember("FieldName14") &&
  974. value.isMember("fieldName15") &&
  975. value.isMember("fieldName16") &&
  976. value.isMember("fieldName17") &&
  977. value.isMember("FieldName18");
  978. });
  979. // Integer fields.
  980. RunValidJsonTest(
  981. "Int32FieldMaxValue", REQUIRED,
  982. R"({"optionalInt32": 2147483647})",
  983. "optional_int32: 2147483647");
  984. RunValidJsonTest(
  985. "Int32FieldMinValue", REQUIRED,
  986. R"({"optionalInt32": -2147483648})",
  987. "optional_int32: -2147483648");
  988. RunValidJsonTest(
  989. "Uint32FieldMaxValue", REQUIRED,
  990. R"({"optionalUint32": 4294967295})",
  991. "optional_uint32: 4294967295");
  992. RunValidJsonTest(
  993. "Int64FieldMaxValue", REQUIRED,
  994. R"({"optionalInt64": "9223372036854775807"})",
  995. "optional_int64: 9223372036854775807");
  996. RunValidJsonTest(
  997. "Int64FieldMinValue", REQUIRED,
  998. R"({"optionalInt64": "-9223372036854775808"})",
  999. "optional_int64: -9223372036854775808");
  1000. RunValidJsonTest(
  1001. "Uint64FieldMaxValue", REQUIRED,
  1002. R"({"optionalUint64": "18446744073709551615"})",
  1003. "optional_uint64: 18446744073709551615");
  1004. // While not the largest Int64, this is the largest
  1005. // Int64 which can be exactly represented within an
  1006. // IEEE-754 64-bit float, which is the expected level
  1007. // of interoperability guarantee. Larger values may
  1008. // work in some implementations, but should not be
  1009. // relied upon.
  1010. RunValidJsonTest(
  1011. "Int64FieldMaxValueNotQuoted", REQUIRED,
  1012. R"({"optionalInt64": 9223372036854774784})",
  1013. "optional_int64: 9223372036854774784");
  1014. RunValidJsonTest(
  1015. "Int64FieldMinValueNotQuoted", REQUIRED,
  1016. R"({"optionalInt64": -9223372036854775808})",
  1017. "optional_int64: -9223372036854775808");
  1018. // Largest interoperable Uint64; see comment above
  1019. // for Int64FieldMaxValueNotQuoted.
  1020. RunValidJsonTest(
  1021. "Uint64FieldMaxValueNotQuoted", REQUIRED,
  1022. R"({"optionalUint64": 18446744073709549568})",
  1023. "optional_uint64: 18446744073709549568");
  1024. // Values can be represented as JSON strings.
  1025. RunValidJsonTest(
  1026. "Int32FieldStringValue", REQUIRED,
  1027. R"({"optionalInt32": "2147483647"})",
  1028. "optional_int32: 2147483647");
  1029. RunValidJsonTest(
  1030. "Int32FieldStringValueEscaped", REQUIRED,
  1031. R"({"optionalInt32": "2\u003147483647"})",
  1032. "optional_int32: 2147483647");
  1033. // Parsers reject out-of-bound integer values.
  1034. ExpectParseFailureForJson(
  1035. "Int32FieldTooLarge", REQUIRED,
  1036. R"({"optionalInt32": 2147483648})");
  1037. ExpectParseFailureForJson(
  1038. "Int32FieldTooSmall", REQUIRED,
  1039. R"({"optionalInt32": -2147483649})");
  1040. ExpectParseFailureForJson(
  1041. "Uint32FieldTooLarge", REQUIRED,
  1042. R"({"optionalUint32": 4294967296})");
  1043. ExpectParseFailureForJson(
  1044. "Int64FieldTooLarge", REQUIRED,
  1045. R"({"optionalInt64": "9223372036854775808"})");
  1046. ExpectParseFailureForJson(
  1047. "Int64FieldTooSmall", REQUIRED,
  1048. R"({"optionalInt64": "-9223372036854775809"})");
  1049. ExpectParseFailureForJson(
  1050. "Uint64FieldTooLarge", REQUIRED,
  1051. R"({"optionalUint64": "18446744073709551616"})");
  1052. // Parser reject non-integer numeric values as well.
  1053. ExpectParseFailureForJson(
  1054. "Int32FieldNotInteger", REQUIRED,
  1055. R"({"optionalInt32": 0.5})");
  1056. ExpectParseFailureForJson(
  1057. "Uint32FieldNotInteger", REQUIRED,
  1058. R"({"optionalUint32": 0.5})");
  1059. ExpectParseFailureForJson(
  1060. "Int64FieldNotInteger", REQUIRED,
  1061. R"({"optionalInt64": "0.5"})");
  1062. ExpectParseFailureForJson(
  1063. "Uint64FieldNotInteger", REQUIRED,
  1064. R"({"optionalUint64": "0.5"})");
  1065. // Integers but represented as float values are accepted.
  1066. RunValidJsonTest(
  1067. "Int32FieldFloatTrailingZero", REQUIRED,
  1068. R"({"optionalInt32": 100000.000})",
  1069. "optional_int32: 100000");
  1070. RunValidJsonTest(
  1071. "Int32FieldExponentialFormat", REQUIRED,
  1072. R"({"optionalInt32": 1e5})",
  1073. "optional_int32: 100000");
  1074. RunValidJsonTest(
  1075. "Int32FieldMaxFloatValue", REQUIRED,
  1076. R"({"optionalInt32": 2.147483647e9})",
  1077. "optional_int32: 2147483647");
  1078. RunValidJsonTest(
  1079. "Int32FieldMinFloatValue", REQUIRED,
  1080. R"({"optionalInt32": -2.147483648e9})",
  1081. "optional_int32: -2147483648");
  1082. RunValidJsonTest(
  1083. "Uint32FieldMaxFloatValue", REQUIRED,
  1084. R"({"optionalUint32": 4.294967295e9})",
  1085. "optional_uint32: 4294967295");
  1086. // Parser reject non-numeric values.
  1087. ExpectParseFailureForJson(
  1088. "Int32FieldNotNumber", REQUIRED,
  1089. R"({"optionalInt32": "3x3"})");
  1090. ExpectParseFailureForJson(
  1091. "Uint32FieldNotNumber", REQUIRED,
  1092. R"({"optionalUint32": "3x3"})");
  1093. ExpectParseFailureForJson(
  1094. "Int64FieldNotNumber", REQUIRED,
  1095. R"({"optionalInt64": "3x3"})");
  1096. ExpectParseFailureForJson(
  1097. "Uint64FieldNotNumber", REQUIRED,
  1098. R"({"optionalUint64": "3x3"})");
  1099. // JSON does not allow "+" on numric values.
  1100. ExpectParseFailureForJson(
  1101. "Int32FieldPlusSign", REQUIRED,
  1102. R"({"optionalInt32": +1})");
  1103. // JSON doesn't allow leading 0s.
  1104. ExpectParseFailureForJson(
  1105. "Int32FieldLeadingZero", REQUIRED,
  1106. R"({"optionalInt32": 01})");
  1107. ExpectParseFailureForJson(
  1108. "Int32FieldNegativeWithLeadingZero", REQUIRED,
  1109. R"({"optionalInt32": -01})");
  1110. // String values must follow the same syntax rule. Specifically leading
  1111. // or trailing spaces are not allowed.
  1112. ExpectParseFailureForJson(
  1113. "Int32FieldLeadingSpace", REQUIRED,
  1114. R"({"optionalInt32": " 1"})");
  1115. ExpectParseFailureForJson(
  1116. "Int32FieldTrailingSpace", REQUIRED,
  1117. R"({"optionalInt32": "1 "})");
  1118. // 64-bit values are serialized as strings.
  1119. RunValidJsonTestWithValidator(
  1120. "Int64FieldBeString", RECOMMENDED,
  1121. R"({"optionalInt64": 1})",
  1122. [](const Json::Value& value) {
  1123. return value["optionalInt64"].type() == Json::stringValue &&
  1124. value["optionalInt64"].asString() == "1";
  1125. });
  1126. RunValidJsonTestWithValidator(
  1127. "Uint64FieldBeString", RECOMMENDED,
  1128. R"({"optionalUint64": 1})",
  1129. [](const Json::Value& value) {
  1130. return value["optionalUint64"].type() == Json::stringValue &&
  1131. value["optionalUint64"].asString() == "1";
  1132. });
  1133. // Bool fields.
  1134. RunValidJsonTest(
  1135. "BoolFieldTrue", REQUIRED,
  1136. R"({"optionalBool":true})",
  1137. "optional_bool: true");
  1138. RunValidJsonTest(
  1139. "BoolFieldFalse", REQUIRED,
  1140. R"({"optionalBool":false})",
  1141. "optional_bool: false");
  1142. // Other forms are not allowed.
  1143. ExpectParseFailureForJson(
  1144. "BoolFieldIntegerZero", RECOMMENDED,
  1145. R"({"optionalBool":0})");
  1146. ExpectParseFailureForJson(
  1147. "BoolFieldIntegerOne", RECOMMENDED,
  1148. R"({"optionalBool":1})");
  1149. ExpectParseFailureForJson(
  1150. "BoolFieldCamelCaseTrue", RECOMMENDED,
  1151. R"({"optionalBool":True})");
  1152. ExpectParseFailureForJson(
  1153. "BoolFieldCamelCaseFalse", RECOMMENDED,
  1154. R"({"optionalBool":False})");
  1155. ExpectParseFailureForJson(
  1156. "BoolFieldAllCapitalTrue", RECOMMENDED,
  1157. R"({"optionalBool":TRUE})");
  1158. ExpectParseFailureForJson(
  1159. "BoolFieldAllCapitalFalse", RECOMMENDED,
  1160. R"({"optionalBool":FALSE})");
  1161. ExpectParseFailureForJson(
  1162. "BoolFieldDoubleQuotedTrue", RECOMMENDED,
  1163. R"({"optionalBool":"true"})");
  1164. ExpectParseFailureForJson(
  1165. "BoolFieldDoubleQuotedFalse", RECOMMENDED,
  1166. R"({"optionalBool":"false"})");
  1167. // Float fields.
  1168. RunValidJsonTest(
  1169. "FloatFieldMinPositiveValue", REQUIRED,
  1170. R"({"optionalFloat": 1.175494e-38})",
  1171. "optional_float: 1.175494e-38");
  1172. RunValidJsonTest(
  1173. "FloatFieldMaxNegativeValue", REQUIRED,
  1174. R"({"optionalFloat": -1.175494e-38})",
  1175. "optional_float: -1.175494e-38");
  1176. RunValidJsonTest(
  1177. "FloatFieldMaxPositiveValue", REQUIRED,
  1178. R"({"optionalFloat": 3.402823e+38})",
  1179. "optional_float: 3.402823e+38");
  1180. RunValidJsonTest(
  1181. "FloatFieldMinNegativeValue", REQUIRED,
  1182. R"({"optionalFloat": 3.402823e+38})",
  1183. "optional_float: 3.402823e+38");
  1184. // Values can be quoted.
  1185. RunValidJsonTest(
  1186. "FloatFieldQuotedValue", REQUIRED,
  1187. R"({"optionalFloat": "1"})",
  1188. "optional_float: 1");
  1189. // Special values.
  1190. RunValidJsonTest(
  1191. "FloatFieldNan", REQUIRED,
  1192. R"({"optionalFloat": "NaN"})",
  1193. "optional_float: nan");
  1194. RunValidJsonTest(
  1195. "FloatFieldInfinity", REQUIRED,
  1196. R"({"optionalFloat": "Infinity"})",
  1197. "optional_float: inf");
  1198. RunValidJsonTest(
  1199. "FloatFieldNegativeInfinity", REQUIRED,
  1200. R"({"optionalFloat": "-Infinity"})",
  1201. "optional_float: -inf");
  1202. // Non-cannonical Nan will be correctly normalized.
  1203. {
  1204. TestAllTypesProto3 message;
  1205. // IEEE floating-point standard 32-bit quiet NaN:
  1206. // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
  1207. message.set_optional_float(
  1208. WireFormatLite::DecodeFloat(0x7FA12345));
  1209. RunValidJsonTestWithProtobufInput(
  1210. "FloatFieldNormalizeQuietNan", REQUIRED, message,
  1211. "optional_float: nan");
  1212. // IEEE floating-point standard 64-bit signaling NaN:
  1213. // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
  1214. message.set_optional_float(
  1215. WireFormatLite::DecodeFloat(0xFFB54321));
  1216. RunValidJsonTestWithProtobufInput(
  1217. "FloatFieldNormalizeSignalingNan", REQUIRED, message,
  1218. "optional_float: nan");
  1219. }
  1220. // Special values must be quoted.
  1221. ExpectParseFailureForJson(
  1222. "FloatFieldNanNotQuoted", RECOMMENDED,
  1223. R"({"optionalFloat": NaN})");
  1224. ExpectParseFailureForJson(
  1225. "FloatFieldInfinityNotQuoted", RECOMMENDED,
  1226. R"({"optionalFloat": Infinity})");
  1227. ExpectParseFailureForJson(
  1228. "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
  1229. R"({"optionalFloat": -Infinity})");
  1230. // Parsers should reject out-of-bound values.
  1231. ExpectParseFailureForJson(
  1232. "FloatFieldTooSmall", REQUIRED,
  1233. R"({"optionalFloat": -3.502823e+38})");
  1234. ExpectParseFailureForJson(
  1235. "FloatFieldTooLarge", REQUIRED,
  1236. R"({"optionalFloat": 3.502823e+38})");
  1237. // Double fields.
  1238. RunValidJsonTest(
  1239. "DoubleFieldMinPositiveValue", REQUIRED,
  1240. R"({"optionalDouble": 2.22507e-308})",
  1241. "optional_double: 2.22507e-308");
  1242. RunValidJsonTest(
  1243. "DoubleFieldMaxNegativeValue", REQUIRED,
  1244. R"({"optionalDouble": -2.22507e-308})",
  1245. "optional_double: -2.22507e-308");
  1246. RunValidJsonTest(
  1247. "DoubleFieldMaxPositiveValue", REQUIRED,
  1248. R"({"optionalDouble": 1.79769e+308})",
  1249. "optional_double: 1.79769e+308");
  1250. RunValidJsonTest(
  1251. "DoubleFieldMinNegativeValue", REQUIRED,
  1252. R"({"optionalDouble": -1.79769e+308})",
  1253. "optional_double: -1.79769e+308");
  1254. // Values can be quoted.
  1255. RunValidJsonTest(
  1256. "DoubleFieldQuotedValue", REQUIRED,
  1257. R"({"optionalDouble": "1"})",
  1258. "optional_double: 1");
  1259. // Speical values.
  1260. RunValidJsonTest(
  1261. "DoubleFieldNan", REQUIRED,
  1262. R"({"optionalDouble": "NaN"})",
  1263. "optional_double: nan");
  1264. RunValidJsonTest(
  1265. "DoubleFieldInfinity", REQUIRED,
  1266. R"({"optionalDouble": "Infinity"})",
  1267. "optional_double: inf");
  1268. RunValidJsonTest(
  1269. "DoubleFieldNegativeInfinity", REQUIRED,
  1270. R"({"optionalDouble": "-Infinity"})",
  1271. "optional_double: -inf");
  1272. // Non-cannonical Nan will be correctly normalized.
  1273. {
  1274. TestAllTypesProto3 message;
  1275. message.set_optional_double(
  1276. WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
  1277. RunValidJsonTestWithProtobufInput(
  1278. "DoubleFieldNormalizeQuietNan", REQUIRED, message,
  1279. "optional_double: nan");
  1280. message.set_optional_double(
  1281. WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
  1282. RunValidJsonTestWithProtobufInput(
  1283. "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
  1284. "optional_double: nan");
  1285. }
  1286. // Special values must be quoted.
  1287. ExpectParseFailureForJson(
  1288. "DoubleFieldNanNotQuoted", RECOMMENDED,
  1289. R"({"optionalDouble": NaN})");
  1290. ExpectParseFailureForJson(
  1291. "DoubleFieldInfinityNotQuoted", RECOMMENDED,
  1292. R"({"optionalDouble": Infinity})");
  1293. ExpectParseFailureForJson(
  1294. "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
  1295. R"({"optionalDouble": -Infinity})");
  1296. // Parsers should reject out-of-bound values.
  1297. ExpectParseFailureForJson(
  1298. "DoubleFieldTooSmall", REQUIRED,
  1299. R"({"optionalDouble": -1.89769e+308})");
  1300. ExpectParseFailureForJson(
  1301. "DoubleFieldTooLarge", REQUIRED,
  1302. R"({"optionalDouble": +1.89769e+308})");
  1303. // Enum fields.
  1304. RunValidJsonTest(
  1305. "EnumField", REQUIRED,
  1306. R"({"optionalNestedEnum": "FOO"})",
  1307. "optional_nested_enum: FOO");
  1308. // Enum fields with alias
  1309. RunValidJsonTest(
  1310. "EnumFieldWithAlias", REQUIRED,
  1311. R"({"optionalAliasedEnum": "ALIAS_BAZ"})",
  1312. "optional_aliased_enum: ALIAS_BAZ");
  1313. RunValidJsonTest(
  1314. "EnumFieldWithAliasUseAlias", REQUIRED,
  1315. R"({"optionalAliasedEnum": "QUX"})",
  1316. "optional_aliased_enum: ALIAS_BAZ");
  1317. RunValidJsonTest(
  1318. "EnumFieldWithAliasLowerCase", REQUIRED,
  1319. R"({"optionalAliasedEnum": "qux"})",
  1320. "optional_aliased_enum: ALIAS_BAZ");
  1321. RunValidJsonTest(
  1322. "EnumFieldWithAliasDifferentCase", REQUIRED,
  1323. R"({"optionalAliasedEnum": "bAz"})",
  1324. "optional_aliased_enum: ALIAS_BAZ");
  1325. // Enum values must be represented as strings.
  1326. ExpectParseFailureForJson(
  1327. "EnumFieldNotQuoted", REQUIRED,
  1328. R"({"optionalNestedEnum": FOO})");
  1329. // Numeric values are allowed.
  1330. RunValidJsonTest(
  1331. "EnumFieldNumericValueZero", REQUIRED,
  1332. R"({"optionalNestedEnum": 0})",
  1333. "optional_nested_enum: FOO");
  1334. RunValidJsonTest(
  1335. "EnumFieldNumericValueNonZero", REQUIRED,
  1336. R"({"optionalNestedEnum": 1})",
  1337. "optional_nested_enum: BAR");
  1338. // Unknown enum values are represented as numeric values.
  1339. RunValidJsonTestWithValidator(
  1340. "EnumFieldUnknownValue", REQUIRED,
  1341. R"({"optionalNestedEnum": 123})",
  1342. [](const Json::Value& value) {
  1343. return value["optionalNestedEnum"].type() == Json::intValue &&
  1344. value["optionalNestedEnum"].asInt() == 123;
  1345. });
  1346. // String fields.
  1347. RunValidJsonTest(
  1348. "StringField", REQUIRED,
  1349. R"({"optionalString": "Hello world!"})",
  1350. "optional_string: \"Hello world!\"");
  1351. RunValidJsonTest(
  1352. "StringFieldUnicode", REQUIRED,
  1353. // Google in Chinese.
  1354. R"({"optionalString": "谷歌"})",
  1355. R"(optional_string: "谷歌")");
  1356. RunValidJsonTest(
  1357. "StringFieldEscape", REQUIRED,
  1358. R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
  1359. R"(optional_string: "\"\\/\b\f\n\r\t")");
  1360. RunValidJsonTest(
  1361. "StringFieldUnicodeEscape", REQUIRED,
  1362. R"({"optionalString": "\u8C37\u6B4C"})",
  1363. R"(optional_string: "谷歌")");
  1364. RunValidJsonTest(
  1365. "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
  1366. R"({"optionalString": "\u8c37\u6b4c"})",
  1367. R"(optional_string: "谷歌")");
  1368. RunValidJsonTest(
  1369. "StringFieldSurrogatePair", REQUIRED,
  1370. // The character is an emoji: grinning face with smiling eyes. 😁
  1371. R"({"optionalString": "\uD83D\uDE01"})",
  1372. R"(optional_string: "\xF0\x9F\x98\x81")");
  1373. // Unicode escapes must start with "\u" (lowercase u).
  1374. ExpectParseFailureForJson(
  1375. "StringFieldUppercaseEscapeLetter", RECOMMENDED,
  1376. R"({"optionalString": "\U8C37\U6b4C"})");
  1377. ExpectParseFailureForJson(
  1378. "StringFieldInvalidEscape", RECOMMENDED,
  1379. R"({"optionalString": "\uXXXX\u6B4C"})");
  1380. ExpectParseFailureForJson(
  1381. "StringFieldUnterminatedEscape", RECOMMENDED,
  1382. R"({"optionalString": "\u8C3"})");
  1383. ExpectParseFailureForJson(
  1384. "StringFieldUnpairedHighSurrogate", RECOMMENDED,
  1385. R"({"optionalString": "\uD800"})");
  1386. ExpectParseFailureForJson(
  1387. "StringFieldUnpairedLowSurrogate", RECOMMENDED,
  1388. R"({"optionalString": "\uDC00"})");
  1389. ExpectParseFailureForJson(
  1390. "StringFieldSurrogateInWrongOrder", RECOMMENDED,
  1391. R"({"optionalString": "\uDE01\uD83D"})");
  1392. ExpectParseFailureForJson(
  1393. "StringFieldNotAString", REQUIRED,
  1394. R"({"optionalString": 12345})");
  1395. // Bytes fields.
  1396. RunValidJsonTest(
  1397. "BytesField", REQUIRED,
  1398. R"({"optionalBytes": "AQI="})",
  1399. R"(optional_bytes: "\x01\x02")");
  1400. RunValidJsonTest(
  1401. "BytesFieldBase64Url", RECOMMENDED,
  1402. R"({"optionalBytes": "-_"})",
  1403. R"(optional_bytes: "\xfb")");
  1404. // Message fields.
  1405. RunValidJsonTest(
  1406. "MessageField", REQUIRED,
  1407. R"({"optionalNestedMessage": {"a": 1234}})",
  1408. "optional_nested_message: {a: 1234}");
  1409. // Oneof fields.
  1410. ExpectParseFailureForJson(
  1411. "OneofFieldDuplicate", REQUIRED,
  1412. R"({"oneofUint32": 1, "oneofString": "test"})");
  1413. // Ensure zero values for oneof make it out/backs.
  1414. TestAllTypesProto3 messageProto3;
  1415. TestAllTypesProto2 messageProto2;
  1416. TestOneofMessage(messageProto3, true);
  1417. TestOneofMessage(messageProto2, false);
  1418. RunValidJsonTest(
  1419. "OneofZeroUint32", RECOMMENDED,
  1420. R"({"oneofUint32": 0})", "oneof_uint32: 0");
  1421. RunValidJsonTest(
  1422. "OneofZeroMessage", RECOMMENDED,
  1423. R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
  1424. RunValidJsonTest(
  1425. "OneofZeroString", RECOMMENDED,
  1426. R"({"oneofString": ""})", "oneof_string: \"\"");
  1427. RunValidJsonTest(
  1428. "OneofZeroBytes", RECOMMENDED,
  1429. R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
  1430. RunValidJsonTest(
  1431. "OneofZeroBool", RECOMMENDED,
  1432. R"({"oneofBool": false})", "oneof_bool: false");
  1433. RunValidJsonTest(
  1434. "OneofZeroUint64", RECOMMENDED,
  1435. R"({"oneofUint64": 0})", "oneof_uint64: 0");
  1436. RunValidJsonTest(
  1437. "OneofZeroFloat", RECOMMENDED,
  1438. R"({"oneofFloat": 0.0})", "oneof_float: 0");
  1439. RunValidJsonTest(
  1440. "OneofZeroDouble", RECOMMENDED,
  1441. R"({"oneofDouble": 0.0})", "oneof_double: 0");
  1442. RunValidJsonTest(
  1443. "OneofZeroEnum", RECOMMENDED,
  1444. R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
  1445. // Repeated fields.
  1446. RunValidJsonTest(
  1447. "PrimitiveRepeatedField", REQUIRED,
  1448. R"({"repeatedInt32": [1, 2, 3, 4]})",
  1449. "repeated_int32: [1, 2, 3, 4]");
  1450. RunValidJsonTest(
  1451. "EnumRepeatedField", REQUIRED,
  1452. R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
  1453. "repeated_nested_enum: [FOO, BAR, BAZ]");
  1454. RunValidJsonTest(
  1455. "StringRepeatedField", REQUIRED,
  1456. R"({"repeatedString": ["Hello", "world"]})",
  1457. R"(repeated_string: ["Hello", "world"])");
  1458. RunValidJsonTest(
  1459. "BytesRepeatedField", REQUIRED,
  1460. R"({"repeatedBytes": ["AAEC", "AQI="]})",
  1461. R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
  1462. RunValidJsonTest(
  1463. "MessageRepeatedField", REQUIRED,
  1464. R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
  1465. "repeated_nested_message: {a: 1234}"
  1466. "repeated_nested_message: {a: 5678}");
  1467. // Repeated field elements are of incorrect type.
  1468. ExpectParseFailureForJson(
  1469. "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
  1470. R"({"repeatedInt32": [1, false, 3, 4]})");
  1471. ExpectParseFailureForJson(
  1472. "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
  1473. R"({"repeatedInt32": [1, 2, "name", 4]})");
  1474. ExpectParseFailureForJson(
  1475. "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
  1476. R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
  1477. ExpectParseFailureForJson(
  1478. "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
  1479. R"({"repeatedString": ["1", 2, "3", "4"]})");
  1480. ExpectParseFailureForJson(
  1481. "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
  1482. R"({"repeatedString": ["1", "2", false, "4"]})");
  1483. ExpectParseFailureForJson(
  1484. "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
  1485. R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
  1486. ExpectParseFailureForJson(
  1487. "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
  1488. R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
  1489. ExpectParseFailureForJson(
  1490. "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
  1491. R"({"repeatedNestedMessage": [{"a": 1}, false]})");
  1492. ExpectParseFailureForJson(
  1493. "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
  1494. R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
  1495. // Trailing comma in the repeated field is not allowed.
  1496. ExpectParseFailureForJson(
  1497. "RepeatedFieldTrailingComma", RECOMMENDED,
  1498. R"({"repeatedInt32": [1, 2, 3, 4,]})");
  1499. ExpectParseFailureForJson(
  1500. "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
  1501. "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
  1502. ExpectParseFailureForJson(
  1503. "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
  1504. "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
  1505. ExpectParseFailureForJson(
  1506. "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
  1507. "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}");
  1508. // Map fields.
  1509. RunValidJsonTest(
  1510. "Int32MapField", REQUIRED,
  1511. R"({"mapInt32Int32": {"1": 2, "3": 4}})",
  1512. "map_int32_int32: {key: 1 value: 2}"
  1513. "map_int32_int32: {key: 3 value: 4}");
  1514. ExpectParseFailureForJson(
  1515. "Int32MapFieldKeyNotQuoted", RECOMMENDED,
  1516. R"({"mapInt32Int32": {1: 2, 3: 4}})");
  1517. RunValidJsonTest(
  1518. "Uint32MapField", REQUIRED,
  1519. R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
  1520. "map_uint32_uint32: {key: 1 value: 2}"
  1521. "map_uint32_uint32: {key: 3 value: 4}");
  1522. ExpectParseFailureForJson(
  1523. "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
  1524. R"({"mapUint32Uint32": {1: 2, 3: 4}})");
  1525. RunValidJsonTest(
  1526. "Int64MapField", REQUIRED,
  1527. R"({"mapInt64Int64": {"1": 2, "3": 4}})",
  1528. "map_int64_int64: {key: 1 value: 2}"
  1529. "map_int64_int64: {key: 3 value: 4}");
  1530. ExpectParseFailureForJson(
  1531. "Int64MapFieldKeyNotQuoted", RECOMMENDED,
  1532. R"({"mapInt64Int64": {1: 2, 3: 4}})");
  1533. RunValidJsonTest(
  1534. "Uint64MapField", REQUIRED,
  1535. R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
  1536. "map_uint64_uint64: {key: 1 value: 2}"
  1537. "map_uint64_uint64: {key: 3 value: 4}");
  1538. ExpectParseFailureForJson(
  1539. "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
  1540. R"({"mapUint64Uint64": {1: 2, 3: 4}})");
  1541. RunValidJsonTest(
  1542. "BoolMapField", REQUIRED,
  1543. R"({"mapBoolBool": {"true": true, "false": false}})",
  1544. "map_bool_bool: {key: true value: true}"
  1545. "map_bool_bool: {key: false value: false}");
  1546. ExpectParseFailureForJson(
  1547. "BoolMapFieldKeyNotQuoted", RECOMMENDED,
  1548. R"({"mapBoolBool": {true: true, false: false}})");
  1549. RunValidJsonTest(
  1550. "MessageMapField", REQUIRED,
  1551. R"({
  1552. "mapStringNestedMessage": {
  1553. "hello": {"a": 1234},
  1554. "world": {"a": 5678}
  1555. }
  1556. })",
  1557. R"(
  1558. map_string_nested_message: {
  1559. key: "hello"
  1560. value: {a: 1234}
  1561. }
  1562. map_string_nested_message: {
  1563. key: "world"
  1564. value: {a: 5678}
  1565. }
  1566. )");
  1567. // Since Map keys are represented as JSON strings, escaping should be allowed.
  1568. RunValidJsonTest(
  1569. "Int32MapEscapedKey", REQUIRED,
  1570. R"({"mapInt32Int32": {"\u0031": 2}})",
  1571. "map_int32_int32: {key: 1 value: 2}");
  1572. RunValidJsonTest(
  1573. "Int64MapEscapedKey", REQUIRED,
  1574. R"({"mapInt64Int64": {"\u0031": 2}})",
  1575. "map_int64_int64: {key: 1 value: 2}");
  1576. RunValidJsonTest(
  1577. "BoolMapEscapedKey", REQUIRED,
  1578. R"({"mapBoolBool": {"tr\u0075e": true}})",
  1579. "map_bool_bool: {key: true value: true}");
  1580. // "null" is accepted for all fields types.
  1581. RunValidJsonTest(
  1582. "AllFieldAcceptNull", REQUIRED,
  1583. R"({
  1584. "optionalInt32": null,
  1585. "optionalInt64": null,
  1586. "optionalUint32": null,
  1587. "optionalUint64": null,
  1588. "optionalSint32": null,
  1589. "optionalSint64": null,
  1590. "optionalFixed32": null,
  1591. "optionalFixed64": null,
  1592. "optionalSfixed32": null,
  1593. "optionalSfixed64": null,
  1594. "optionalFloat": null,
  1595. "optionalDouble": null,
  1596. "optionalBool": null,
  1597. "optionalString": null,
  1598. "optionalBytes": null,
  1599. "optionalNestedEnum": null,
  1600. "optionalNestedMessage": null,
  1601. "repeatedInt32": null,
  1602. "repeatedInt64": null,
  1603. "repeatedUint32": null,
  1604. "repeatedUint64": null,
  1605. "repeatedSint32": null,
  1606. "repeatedSint64": null,
  1607. "repeatedFixed32": null,
  1608. "repeatedFixed64": null,
  1609. "repeatedSfixed32": null,
  1610. "repeatedSfixed64": null,
  1611. "repeatedFloat": null,
  1612. "repeatedDouble": null,
  1613. "repeatedBool": null,
  1614. "repeatedString": null,
  1615. "repeatedBytes": null,
  1616. "repeatedNestedEnum": null,
  1617. "repeatedNestedMessage": null,
  1618. "mapInt32Int32": null,
  1619. "mapBoolBool": null,
  1620. "mapStringNestedMessage": null
  1621. })",
  1622. "");
  1623. // Repeated field elements cannot be null.
  1624. ExpectParseFailureForJson(
  1625. "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
  1626. R"({"repeatedInt32": [1, null, 2]})");
  1627. ExpectParseFailureForJson(
  1628. "RepeatedFieldMessageElementIsNull", RECOMMENDED,
  1629. R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
  1630. // Map field keys cannot be null.
  1631. ExpectParseFailureForJson(
  1632. "MapFieldKeyIsNull", RECOMMENDED,
  1633. R"({"mapInt32Int32": {null: 1}})");
  1634. // Map field values cannot be null.
  1635. ExpectParseFailureForJson(
  1636. "MapFieldValueIsNull", RECOMMENDED,
  1637. R"({"mapInt32Int32": {"0": null}})");
  1638. // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
  1639. // quotes.
  1640. ExpectParseFailureForJson(
  1641. "StringFieldSingleQuoteKey", RECOMMENDED,
  1642. R"({'optionalString': "Hello world!"})");
  1643. ExpectParseFailureForJson(
  1644. "StringFieldSingleQuoteValue", RECOMMENDED,
  1645. R"({"optionalString": 'Hello world!'})");
  1646. ExpectParseFailureForJson(
  1647. "StringFieldSingleQuoteBoth", RECOMMENDED,
  1648. R"({'optionalString': 'Hello world!'})");
  1649. // Unknown fields.
  1650. {
  1651. TestAllTypesProto3 messageProto3;
  1652. TestAllTypesProto2 messageProto2;
  1653. //TODO(yilunchong): update this behavior when unknown field's behavior
  1654. // changed in open source. Also delete
  1655. // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput
  1656. // from failure list of python_cpp python java
  1657. TestUnknownMessage(messageProto3, true);
  1658. TestUnknownMessage(messageProto2, false);
  1659. }
  1660. // Wrapper types.
  1661. RunValidJsonTest(
  1662. "OptionalBoolWrapper", REQUIRED,
  1663. R"({"optionalBoolWrapper": false})",
  1664. "optional_bool_wrapper: {value: false}");
  1665. RunValidJsonTest(
  1666. "OptionalInt32Wrapper", REQUIRED,
  1667. R"({"optionalInt32Wrapper": 0})",
  1668. "optional_int32_wrapper: {value: 0}");
  1669. RunValidJsonTest(
  1670. "OptionalUint32Wrapper", REQUIRED,
  1671. R"({"optionalUint32Wrapper": 0})",
  1672. "optional_uint32_wrapper: {value: 0}");
  1673. RunValidJsonTest(
  1674. "OptionalInt64Wrapper", REQUIRED,
  1675. R"({"optionalInt64Wrapper": 0})",
  1676. "optional_int64_wrapper: {value: 0}");
  1677. RunValidJsonTest(
  1678. "OptionalUint64Wrapper", REQUIRED,
  1679. R"({"optionalUint64Wrapper": 0})",
  1680. "optional_uint64_wrapper: {value: 0}");
  1681. RunValidJsonTest(
  1682. "OptionalFloatWrapper", REQUIRED,
  1683. R"({"optionalFloatWrapper": 0})",
  1684. "optional_float_wrapper: {value: 0}");
  1685. RunValidJsonTest(
  1686. "OptionalDoubleWrapper", REQUIRED,
  1687. R"({"optionalDoubleWrapper": 0})",
  1688. "optional_double_wrapper: {value: 0}");
  1689. RunValidJsonTest(
  1690. "OptionalStringWrapper", REQUIRED,
  1691. R"({"optionalStringWrapper": ""})",
  1692. R"(optional_string_wrapper: {value: ""})");
  1693. RunValidJsonTest(
  1694. "OptionalBytesWrapper", REQUIRED,
  1695. R"({"optionalBytesWrapper": ""})",
  1696. R"(optional_bytes_wrapper: {value: ""})");
  1697. RunValidJsonTest(
  1698. "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
  1699. R"({
  1700. "optionalBoolWrapper": true,
  1701. "optionalInt32Wrapper": 1,
  1702. "optionalUint32Wrapper": 1,
  1703. "optionalInt64Wrapper": "1",
  1704. "optionalUint64Wrapper": "1",
  1705. "optionalFloatWrapper": 1,
  1706. "optionalDoubleWrapper": 1,
  1707. "optionalStringWrapper": "1",
  1708. "optionalBytesWrapper": "AQI="
  1709. })",
  1710. R"(
  1711. optional_bool_wrapper: {value: true}
  1712. optional_int32_wrapper: {value: 1}
  1713. optional_uint32_wrapper: {value: 1}
  1714. optional_int64_wrapper: {value: 1}
  1715. optional_uint64_wrapper: {value: 1}
  1716. optional_float_wrapper: {value: 1}
  1717. optional_double_wrapper: {value: 1}
  1718. optional_string_wrapper: {value: "1"}
  1719. optional_bytes_wrapper: {value: "\x01\x02"}
  1720. )");
  1721. RunValidJsonTest(
  1722. "RepeatedBoolWrapper", REQUIRED,
  1723. R"({"repeatedBoolWrapper": [true, false]})",
  1724. "repeated_bool_wrapper: {value: true}"
  1725. "repeated_bool_wrapper: {value: false}");
  1726. RunValidJsonTest(
  1727. "RepeatedInt32Wrapper", REQUIRED,
  1728. R"({"repeatedInt32Wrapper": [0, 1]})",
  1729. "repeated_int32_wrapper: {value: 0}"
  1730. "repeated_int32_wrapper: {value: 1}");
  1731. RunValidJsonTest(
  1732. "RepeatedUint32Wrapper", REQUIRED,
  1733. R"({"repeatedUint32Wrapper": [0, 1]})",
  1734. "repeated_uint32_wrapper: {value: 0}"
  1735. "repeated_uint32_wrapper: {value: 1}");
  1736. RunValidJsonTest(
  1737. "RepeatedInt64Wrapper", REQUIRED,
  1738. R"({"repeatedInt64Wrapper": [0, 1]})",
  1739. "repeated_int64_wrapper: {value: 0}"
  1740. "repeated_int64_wrapper: {value: 1}");
  1741. RunValidJsonTest(
  1742. "RepeatedUint64Wrapper", REQUIRED,
  1743. R"({"repeatedUint64Wrapper": [0, 1]})",
  1744. "repeated_uint64_wrapper: {value: 0}"
  1745. "repeated_uint64_wrapper: {value: 1}");
  1746. RunValidJsonTest(
  1747. "RepeatedFloatWrapper", REQUIRED,
  1748. R"({"repeatedFloatWrapper": [0, 1]})",
  1749. "repeated_float_wrapper: {value: 0}"
  1750. "repeated_float_wrapper: {value: 1}");
  1751. RunValidJsonTest(
  1752. "RepeatedDoubleWrapper", REQUIRED,
  1753. R"({"repeatedDoubleWrapper": [0, 1]})",
  1754. "repeated_double_wrapper: {value: 0}"
  1755. "repeated_double_wrapper: {value: 1}");
  1756. RunValidJsonTest(
  1757. "RepeatedStringWrapper", REQUIRED,
  1758. R"({"repeatedStringWrapper": ["", "AQI="]})",
  1759. R"(
  1760. repeated_string_wrapper: {value: ""}
  1761. repeated_string_wrapper: {value: "AQI="}
  1762. )");
  1763. RunValidJsonTest(
  1764. "RepeatedBytesWrapper", REQUIRED,
  1765. R"({"repeatedBytesWrapper": ["", "AQI="]})",
  1766. R"(
  1767. repeated_bytes_wrapper: {value: ""}
  1768. repeated_bytes_wrapper: {value: "\x01\x02"}
  1769. )");
  1770. RunValidJsonTest(
  1771. "WrapperTypesWithNullValue", REQUIRED,
  1772. R"({
  1773. "optionalBoolWrapper": null,
  1774. "optionalInt32Wrapper": null,
  1775. "optionalUint32Wrapper": null,
  1776. "optionalInt64Wrapper": null,
  1777. "optionalUint64Wrapper": null,
  1778. "optionalFloatWrapper": null,
  1779. "optionalDoubleWrapper": null,
  1780. "optionalStringWrapper": null,
  1781. "optionalBytesWrapper": null,
  1782. "repeatedBoolWrapper": null,
  1783. "repeatedInt32Wrapper": null,
  1784. "repeatedUint32Wrapper": null,
  1785. "repeatedInt64Wrapper": null,
  1786. "repeatedUint64Wrapper": null,
  1787. "repeatedFloatWrapper": null,
  1788. "repeatedDoubleWrapper": null,
  1789. "repeatedStringWrapper": null,
  1790. "repeatedBytesWrapper": null
  1791. })",
  1792. "");
  1793. // Duration
  1794. RunValidJsonTest(
  1795. "DurationMinValue", REQUIRED,
  1796. R"({"optionalDuration": "-315576000000.999999999s"})",
  1797. "optional_duration: {seconds: -315576000000 nanos: -999999999}");
  1798. RunValidJsonTest(
  1799. "DurationMaxValue", REQUIRED,
  1800. R"({"optionalDuration": "315576000000.999999999s"})",
  1801. "optional_duration: {seconds: 315576000000 nanos: 999999999}");
  1802. RunValidJsonTest(
  1803. "DurationRepeatedValue", REQUIRED,
  1804. R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
  1805. "repeated_duration: {seconds: 1 nanos: 500000000}"
  1806. "repeated_duration: {seconds: -1 nanos: -500000000}");
  1807. RunValidJsonTest(
  1808. "DurationNull", REQUIRED,
  1809. R"({"optionalDuration": null})",
  1810. "");
  1811. ExpectParseFailureForJson(
  1812. "DurationMissingS", REQUIRED,
  1813. R"({"optionalDuration": "1"})");
  1814. ExpectParseFailureForJson(
  1815. "DurationJsonInputTooSmall", REQUIRED,
  1816. R"({"optionalDuration": "-315576000001.000000000s"})");
  1817. ExpectParseFailureForJson(
  1818. "DurationJsonInputTooLarge", REQUIRED,
  1819. R"({"optionalDuration": "315576000001.000000000s"})");
  1820. ExpectSerializeFailureForJson(
  1821. "DurationProtoInputTooSmall", REQUIRED,
  1822. "optional_duration: {seconds: -315576000001 nanos: 0}");
  1823. ExpectSerializeFailureForJson(
  1824. "DurationProtoInputTooLarge", REQUIRED,
  1825. "optional_duration: {seconds: 315576000001 nanos: 0}");
  1826. RunValidJsonTestWithValidator(
  1827. "DurationHasZeroFractionalDigit", RECOMMENDED,
  1828. R"({"optionalDuration": "1.000000000s"})",
  1829. [](const Json::Value& value) {
  1830. return value["optionalDuration"].asString() == "1s";
  1831. });
  1832. RunValidJsonTestWithValidator(
  1833. "DurationHas3FractionalDigits", RECOMMENDED,
  1834. R"({"optionalDuration": "1.010000000s"})",
  1835. [](const Json::Value& value) {
  1836. return value["optionalDuration"].asString() == "1.010s";
  1837. });
  1838. RunValidJsonTestWithValidator(
  1839. "DurationHas6FractionalDigits", RECOMMENDED,
  1840. R"({"optionalDuration": "1.000010000s"})",
  1841. [](const Json::Value& value) {
  1842. return value["optionalDuration"].asString() == "1.000010s";
  1843. });
  1844. RunValidJsonTestWithValidator(
  1845. "DurationHas9FractionalDigits", RECOMMENDED,
  1846. R"({"optionalDuration": "1.000000010s"})",
  1847. [](const Json::Value& value) {
  1848. return value["optionalDuration"].asString() == "1.000000010s";
  1849. });
  1850. // Timestamp
  1851. RunValidJsonTest(
  1852. "TimestampMinValue", REQUIRED,
  1853. R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
  1854. "optional_timestamp: {seconds: -62135596800}");
  1855. RunValidJsonTest(
  1856. "TimestampMaxValue", REQUIRED,
  1857. R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
  1858. "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1859. RunValidJsonTest(
  1860. "TimestampRepeatedValue", REQUIRED,
  1861. R"({
  1862. "repeatedTimestamp": [
  1863. "0001-01-01T00:00:00Z",
  1864. "9999-12-31T23:59:59.999999999Z"
  1865. ]
  1866. })",
  1867. "repeated_timestamp: {seconds: -62135596800}"
  1868. "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1869. RunValidJsonTest("TimestampWithPositiveOffset", REQUIRED,
  1870. R"({"optionalTimestamp": "1970-01-01T08:00:01+08:00"})",
  1871. "optional_timestamp: {seconds: 1}");
  1872. RunValidJsonTest("TimestampWithNegativeOffset", REQUIRED,
  1873. R"({"optionalTimestamp": "1969-12-31T16:00:01-08:00"})",
  1874. "optional_timestamp: {seconds: 1}");
  1875. RunValidJsonTest(
  1876. "TimestampNull", REQUIRED,
  1877. R"({"optionalTimestamp": null})",
  1878. "");
  1879. ExpectParseFailureForJson(
  1880. "TimestampJsonInputTooSmall", REQUIRED,
  1881. R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  1882. ExpectParseFailureForJson(
  1883. "TimestampJsonInputTooLarge", REQUIRED,
  1884. R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  1885. ExpectParseFailureForJson(
  1886. "TimestampJsonInputMissingZ", REQUIRED,
  1887. R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  1888. ExpectParseFailureForJson(
  1889. "TimestampJsonInputMissingT", REQUIRED,
  1890. R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  1891. ExpectParseFailureForJson(
  1892. "TimestampJsonInputLowercaseZ", REQUIRED,
  1893. R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  1894. ExpectParseFailureForJson(
  1895. "TimestampJsonInputLowercaseT", REQUIRED,
  1896. R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  1897. ExpectSerializeFailureForJson(
  1898. "TimestampProtoInputTooSmall", REQUIRED,
  1899. "optional_timestamp: {seconds: -62135596801}");
  1900. ExpectSerializeFailureForJson(
  1901. "TimestampProtoInputTooLarge", REQUIRED,
  1902. "optional_timestamp: {seconds: 253402300800}");
  1903. RunValidJsonTestWithValidator(
  1904. "TimestampZeroNormalized", RECOMMENDED,
  1905. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  1906. [](const Json::Value& value) {
  1907. return value["optionalTimestamp"].asString() ==
  1908. "1970-01-01T00:00:00Z";
  1909. });
  1910. RunValidJsonTestWithValidator(
  1911. "TimestampHasZeroFractionalDigit", RECOMMENDED,
  1912. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
  1913. [](const Json::Value& value) {
  1914. return value["optionalTimestamp"].asString() ==
  1915. "1970-01-01T00:00:00Z";
  1916. });
  1917. RunValidJsonTestWithValidator(
  1918. "TimestampHas3FractionalDigits", RECOMMENDED,
  1919. R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
  1920. [](const Json::Value& value) {
  1921. return value["optionalTimestamp"].asString() ==
  1922. "1970-01-01T00:00:00.010Z";
  1923. });
  1924. RunValidJsonTestWithValidator(
  1925. "TimestampHas6FractionalDigits", RECOMMENDED,
  1926. R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
  1927. [](const Json::Value& value) {
  1928. return value["optionalTimestamp"].asString() ==
  1929. "1970-01-01T00:00:00.000010Z";
  1930. });
  1931. RunValidJsonTestWithValidator(
  1932. "TimestampHas9FractionalDigits", RECOMMENDED,
  1933. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
  1934. [](const Json::Value& value) {
  1935. return value["optionalTimestamp"].asString() ==
  1936. "1970-01-01T00:00:00.000000010Z";
  1937. });
  1938. // FieldMask
  1939. RunValidJsonTest(
  1940. "FieldMask", REQUIRED,
  1941. R"({"optionalFieldMask": "foo,barBaz"})",
  1942. R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  1943. RunValidJsonTest(
  1944. "EmptyFieldMask", REQUIRED,
  1945. R"({"optionalFieldMask": ""})",
  1946. R"(optional_field_mask: {})");
  1947. ExpectParseFailureForJson(
  1948. "FieldMaskInvalidCharacter", RECOMMENDED,
  1949. R"({"optionalFieldMask": "foo,bar_bar"})");
  1950. ExpectSerializeFailureForJson(
  1951. "FieldMaskPathsDontRoundTrip", RECOMMENDED,
  1952. R"(optional_field_mask: {paths: "fooBar"})");
  1953. ExpectSerializeFailureForJson(
  1954. "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
  1955. R"(optional_field_mask: {paths: "foo_3_bar"})");
  1956. ExpectSerializeFailureForJson(
  1957. "FieldMaskTooManyUnderscore", RECOMMENDED,
  1958. R"(optional_field_mask: {paths: "foo__bar"})");
  1959. // Struct
  1960. RunValidJsonTest(
  1961. "Struct", REQUIRED,
  1962. R"({
  1963. "optionalStruct": {
  1964. "nullValue": null,
  1965. "intValue": 1234,
  1966. "boolValue": true,
  1967. "doubleValue": 1234.5678,
  1968. "stringValue": "Hello world!",
  1969. "listValue": [1234, "5678"],
  1970. "objectValue": {
  1971. "value": 0
  1972. }
  1973. }
  1974. })",
  1975. R"(
  1976. optional_struct: {
  1977. fields: {
  1978. key: "nullValue"
  1979. value: {null_value: NULL_VALUE}
  1980. }
  1981. fields: {
  1982. key: "intValue"
  1983. value: {number_value: 1234}
  1984. }
  1985. fields: {
  1986. key: "boolValue"
  1987. value: {bool_value: true}
  1988. }
  1989. fields: {
  1990. key: "doubleValue"
  1991. value: {number_value: 1234.5678}
  1992. }
  1993. fields: {
  1994. key: "stringValue"
  1995. value: {string_value: "Hello world!"}
  1996. }
  1997. fields: {
  1998. key: "listValue"
  1999. value: {
  2000. list_value: {
  2001. values: {
  2002. number_value: 1234
  2003. }
  2004. values: {
  2005. string_value: "5678"
  2006. }
  2007. }
  2008. }
  2009. }
  2010. fields: {
  2011. key: "objectValue"
  2012. value: {
  2013. struct_value: {
  2014. fields: {
  2015. key: "value"
  2016. value: {
  2017. number_value: 0
  2018. }
  2019. }
  2020. }
  2021. }
  2022. }
  2023. }
  2024. )");
  2025. RunValidJsonTest(
  2026. "StructWithEmptyListValue", REQUIRED,
  2027. R"({
  2028. "optionalStruct": {
  2029. "listValue": []
  2030. }
  2031. })",
  2032. R"(
  2033. optional_struct: {
  2034. fields: {
  2035. key: "listValue"
  2036. value: {
  2037. list_value: {
  2038. }
  2039. }
  2040. }
  2041. }
  2042. )");
  2043. // Value
  2044. RunValidJsonTest(
  2045. "ValueAcceptInteger", REQUIRED,
  2046. R"({"optionalValue": 1})",
  2047. "optional_value: { number_value: 1}");
  2048. RunValidJsonTest(
  2049. "ValueAcceptFloat", REQUIRED,
  2050. R"({"optionalValue": 1.5})",
  2051. "optional_value: { number_value: 1.5}");
  2052. RunValidJsonTest(
  2053. "ValueAcceptBool", REQUIRED,
  2054. R"({"optionalValue": false})",
  2055. "optional_value: { bool_value: false}");
  2056. RunValidJsonTest(
  2057. "ValueAcceptNull", REQUIRED,
  2058. R"({"optionalValue": null})",
  2059. "optional_value: { null_value: NULL_VALUE}");
  2060. RunValidJsonTest(
  2061. "ValueAcceptString", REQUIRED,
  2062. R"({"optionalValue": "hello"})",
  2063. R"(optional_value: { string_value: "hello"})");
  2064. RunValidJsonTest(
  2065. "ValueAcceptList", REQUIRED,
  2066. R"({"optionalValue": [0, "hello"]})",
  2067. R"(
  2068. optional_value: {
  2069. list_value: {
  2070. values: {
  2071. number_value: 0
  2072. }
  2073. values: {
  2074. string_value: "hello"
  2075. }
  2076. }
  2077. }
  2078. )");
  2079. RunValidJsonTest(
  2080. "ValueAcceptObject", REQUIRED,
  2081. R"({"optionalValue": {"value": 1}})",
  2082. R"(
  2083. optional_value: {
  2084. struct_value: {
  2085. fields: {
  2086. key: "value"
  2087. value: {
  2088. number_value: 1
  2089. }
  2090. }
  2091. }
  2092. }
  2093. )");
  2094. RunValidJsonTest(
  2095. "RepeatedValue", REQUIRED,
  2096. R"({
  2097. "repeatedValue": [["a"]]
  2098. })",
  2099. R"(
  2100. repeated_value: [
  2101. {
  2102. list_value: {
  2103. values: [
  2104. { string_value: "a"}
  2105. ]
  2106. }
  2107. }
  2108. ]
  2109. )");
  2110. RunValidJsonTest(
  2111. "RepeatedListValue", REQUIRED,
  2112. R"({
  2113. "repeatedListValue": [["a"]]
  2114. })",
  2115. R"(
  2116. repeated_list_value: [
  2117. {
  2118. values: [
  2119. { string_value: "a"}
  2120. ]
  2121. }
  2122. ]
  2123. )");
  2124. // Any
  2125. RunValidJsonTest(
  2126. "Any", REQUIRED,
  2127. R"({
  2128. "optionalAny": {
  2129. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2130. "optionalInt32": 12345
  2131. }
  2132. })",
  2133. R"(
  2134. optional_any: {
  2135. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2136. optional_int32: 12345
  2137. }
  2138. }
  2139. )");
  2140. RunValidJsonTest(
  2141. "AnyNested", REQUIRED,
  2142. R"({
  2143. "optionalAny": {
  2144. "@type": "type.googleapis.com/google.protobuf.Any",
  2145. "value": {
  2146. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
  2147. "optionalInt32": 12345
  2148. }
  2149. }
  2150. })",
  2151. R"(
  2152. optional_any: {
  2153. [type.googleapis.com/google.protobuf.Any] {
  2154. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2155. optional_int32: 12345
  2156. }
  2157. }
  2158. }
  2159. )");
  2160. // The special "@type" tag is not required to appear first.
  2161. RunValidJsonTest(
  2162. "AnyUnorderedTypeTag", REQUIRED,
  2163. R"({
  2164. "optionalAny": {
  2165. "optionalInt32": 12345,
  2166. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
  2167. }
  2168. })",
  2169. R"(
  2170. optional_any: {
  2171. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
  2172. optional_int32: 12345
  2173. }
  2174. }
  2175. )");
  2176. // Well-known types in Any.
  2177. RunValidJsonTest(
  2178. "AnyWithInt32ValueWrapper", REQUIRED,
  2179. R"({
  2180. "optionalAny": {
  2181. "@type": "type.googleapis.com/google.protobuf.Int32Value",
  2182. "value": 12345
  2183. }
  2184. })",
  2185. R"(
  2186. optional_any: {
  2187. [type.googleapis.com/google.protobuf.Int32Value] {
  2188. value: 12345
  2189. }
  2190. }
  2191. )");
  2192. RunValidJsonTest(
  2193. "AnyWithDuration", REQUIRED,
  2194. R"({
  2195. "optionalAny": {
  2196. "@type": "type.googleapis.com/google.protobuf.Duration",
  2197. "value": "1.5s"
  2198. }
  2199. })",
  2200. R"(
  2201. optional_any: {
  2202. [type.googleapis.com/google.protobuf.Duration] {
  2203. seconds: 1
  2204. nanos: 500000000
  2205. }
  2206. }
  2207. )");
  2208. RunValidJsonTest(
  2209. "AnyWithTimestamp", REQUIRED,
  2210. R"({
  2211. "optionalAny": {
  2212. "@type": "type.googleapis.com/google.protobuf.Timestamp",
  2213. "value": "1970-01-01T00:00:00Z"
  2214. }
  2215. })",
  2216. R"(
  2217. optional_any: {
  2218. [type.googleapis.com/google.protobuf.Timestamp] {
  2219. seconds: 0
  2220. nanos: 0
  2221. }
  2222. }
  2223. )");
  2224. RunValidJsonTest(
  2225. "AnyWithFieldMask", REQUIRED,
  2226. R"({
  2227. "optionalAny": {
  2228. "@type": "type.googleapis.com/google.protobuf.FieldMask",
  2229. "value": "foo,barBaz"
  2230. }
  2231. })",
  2232. R"(
  2233. optional_any: {
  2234. [type.googleapis.com/google.protobuf.FieldMask] {
  2235. paths: ["foo", "bar_baz"]
  2236. }
  2237. }
  2238. )");
  2239. RunValidJsonTest(
  2240. "AnyWithStruct", REQUIRED,
  2241. R"({
  2242. "optionalAny": {
  2243. "@type": "type.googleapis.com/google.protobuf.Struct",
  2244. "value": {
  2245. "foo": 1
  2246. }
  2247. }
  2248. })",
  2249. R"(
  2250. optional_any: {
  2251. [type.googleapis.com/google.protobuf.Struct] {
  2252. fields: {
  2253. key: "foo"
  2254. value: {
  2255. number_value: 1
  2256. }
  2257. }
  2258. }
  2259. }
  2260. )");
  2261. RunValidJsonTest(
  2262. "AnyWithValueForJsonObject", REQUIRED,
  2263. R"({
  2264. "optionalAny": {
  2265. "@type": "type.googleapis.com/google.protobuf.Value",
  2266. "value": {
  2267. "foo": 1
  2268. }
  2269. }
  2270. })",
  2271. R"(
  2272. optional_any: {
  2273. [type.googleapis.com/google.protobuf.Value] {
  2274. struct_value: {
  2275. fields: {
  2276. key: "foo"
  2277. value: {
  2278. number_value: 1
  2279. }
  2280. }
  2281. }
  2282. }
  2283. }
  2284. )");
  2285. RunValidJsonTest(
  2286. "AnyWithValueForInteger", REQUIRED,
  2287. R"({
  2288. "optionalAny": {
  2289. "@type": "type.googleapis.com/google.protobuf.Value",
  2290. "value": 1
  2291. }
  2292. })",
  2293. R"(
  2294. optional_any: {
  2295. [type.googleapis.com/google.protobuf.Value] {
  2296. number_value: 1
  2297. }
  2298. }
  2299. )");
  2300. RunValidJsonIgnoreUnknownTest(
  2301. "IgnoreUnknownJsonNumber", REQUIRED,
  2302. R"({
  2303. "unknown": 1
  2304. })",
  2305. "");
  2306. RunValidJsonIgnoreUnknownTest(
  2307. "IgnoreUnknownJsonString", REQUIRED,
  2308. R"({
  2309. "unknown": "a"
  2310. })",
  2311. "");
  2312. RunValidJsonIgnoreUnknownTest(
  2313. "IgnoreUnknownJsonTrue", REQUIRED,
  2314. R"({
  2315. "unknown": true
  2316. })",
  2317. "");
  2318. RunValidJsonIgnoreUnknownTest(
  2319. "IgnoreUnknownJsonFalse", REQUIRED,
  2320. R"({
  2321. "unknown": false
  2322. })",
  2323. "");
  2324. RunValidJsonIgnoreUnknownTest(
  2325. "IgnoreUnknownJsonNull", REQUIRED,
  2326. R"({
  2327. "unknown": null
  2328. })",
  2329. "");
  2330. RunValidJsonIgnoreUnknownTest(
  2331. "IgnoreUnknownJsonObject", REQUIRED,
  2332. R"({
  2333. "unknown": {"a": 1}
  2334. })",
  2335. "");
  2336. ExpectParseFailureForJson("RejectTopLevelNull", REQUIRED, "null");
  2337. }
  2338. } // namespace protobuf
  2339. } // namespace google