binary_json_conformance_suite.cc 92 KB

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