binary_json_conformance_suite.cc 82 KB

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