binary_json_conformance_suite.cc 93 KB

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