conformance_test.cc 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  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 <stdarg.h>
  31. #include <string>
  32. #include <fstream>
  33. #include "conformance.pb.h"
  34. #include "conformance_test.h"
  35. #include <google/protobuf/test_messages_proto3.pb.h>
  36. #include <google/protobuf/stubs/common.h>
  37. #include <google/protobuf/stubs/stringprintf.h>
  38. #include <google/protobuf/text_format.h>
  39. #include <google/protobuf/util/field_comparator.h>
  40. #include <google/protobuf/util/json_util.h>
  41. #include <google/protobuf/util/message_differencer.h>
  42. #include <google/protobuf/util/type_resolver_util.h>
  43. #include <google/protobuf/wire_format_lite.h>
  44. #include "third_party/jsoncpp/json.h"
  45. using conformance::ConformanceRequest;
  46. using conformance::ConformanceResponse;
  47. using conformance::WireFormat;
  48. using google::protobuf::Descriptor;
  49. using google::protobuf::FieldDescriptor;
  50. using google::protobuf::internal::WireFormatLite;
  51. using google::protobuf::TextFormat;
  52. using google::protobuf::util::DefaultFieldComparator;
  53. using google::protobuf::util::JsonToBinaryString;
  54. using google::protobuf::util::MessageDifferencer;
  55. using google::protobuf::util::NewTypeResolverForDescriptorPool;
  56. using google::protobuf::util::Status;
  57. using protobuf_test_messages::proto3::TestAllTypes;
  58. using std::string;
  59. namespace {
  60. static const char kTypeUrlPrefix[] = "type.googleapis.com";
  61. static string GetTypeUrl(const Descriptor* message) {
  62. return string(kTypeUrlPrefix) + "/" + message->full_name();
  63. }
  64. /* Routines for building arbitrary protos *************************************/
  65. // We would use CodedOutputStream except that we want more freedom to build
  66. // arbitrary protos (even invalid ones).
  67. const string empty;
  68. string cat(const string& a, const string& b,
  69. const string& c = empty,
  70. const string& d = empty,
  71. const string& e = empty,
  72. const string& f = empty,
  73. const string& g = empty,
  74. const string& h = empty,
  75. const string& i = empty,
  76. const string& j = empty,
  77. const string& k = empty,
  78. const string& l = empty) {
  79. string ret;
  80. ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() +
  81. g.size() + h.size() + i.size() + j.size() + k.size() + l.size());
  82. ret.append(a);
  83. ret.append(b);
  84. ret.append(c);
  85. ret.append(d);
  86. ret.append(e);
  87. ret.append(f);
  88. ret.append(g);
  89. ret.append(h);
  90. ret.append(i);
  91. ret.append(j);
  92. ret.append(k);
  93. ret.append(l);
  94. return ret;
  95. }
  96. // The maximum number of bytes that it takes to encode a 64-bit varint.
  97. #define VARINT_MAX_LEN 10
  98. size_t vencode64(uint64_t val, char *buf) {
  99. if (val == 0) { buf[0] = 0; return 1; }
  100. size_t i = 0;
  101. while (val) {
  102. uint8_t byte = val & 0x7fU;
  103. val >>= 7;
  104. if (val) byte |= 0x80U;
  105. buf[i++] = byte;
  106. }
  107. return i;
  108. }
  109. string varint(uint64_t x) {
  110. char buf[VARINT_MAX_LEN];
  111. size_t len = vencode64(x, buf);
  112. return string(buf, len);
  113. }
  114. // TODO: proper byte-swapping for big-endian machines.
  115. string fixed32(void *data) { return string(static_cast<char*>(data), 4); }
  116. string fixed64(void *data) { return string(static_cast<char*>(data), 8); }
  117. string delim(const string& buf) { return cat(varint(buf.size()), buf); }
  118. string uint32(uint32_t u32) { return fixed32(&u32); }
  119. string uint64(uint64_t u64) { return fixed64(&u64); }
  120. string flt(float f) { return fixed32(&f); }
  121. string dbl(double d) { return fixed64(&d); }
  122. string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); }
  123. string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); }
  124. string tag(uint32_t fieldnum, char wire_type) {
  125. return varint((fieldnum << 3) | wire_type);
  126. }
  127. string submsg(uint32_t fn, const string& buf) {
  128. return cat( tag(fn, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(buf) );
  129. }
  130. #define UNKNOWN_FIELD 666
  131. uint32_t GetFieldNumberForType(FieldDescriptor::Type type, bool repeated) {
  132. const Descriptor* d = TestAllTypes().GetDescriptor();
  133. for (int i = 0; i < d->field_count(); i++) {
  134. const FieldDescriptor* f = d->field(i);
  135. if (f->type() == type && f->is_repeated() == repeated) {
  136. return f->number();
  137. }
  138. }
  139. GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type;
  140. return 0;
  141. }
  142. string UpperCase(string str) {
  143. for (int i = 0; i < str.size(); i++) {
  144. str[i] = toupper(str[i]);
  145. }
  146. return str;
  147. }
  148. } // anonymous namespace
  149. namespace google {
  150. namespace protobuf {
  151. void ConformanceTestSuite::ReportSuccess(const string& test_name) {
  152. if (expected_to_fail_.erase(test_name) != 0) {
  153. StringAppendF(&output_,
  154. "ERROR: test %s is in the failure list, but test succeeded. "
  155. "Remove it from the failure list.\n",
  156. test_name.c_str());
  157. unexpected_succeeding_tests_.insert(test_name);
  158. }
  159. successes_++;
  160. }
  161. void ConformanceTestSuite::ReportFailure(const string& test_name,
  162. ConformanceLevel level,
  163. const ConformanceRequest& request,
  164. const ConformanceResponse& response,
  165. const char* fmt, ...) {
  166. if (expected_to_fail_.erase(test_name) == 1) {
  167. expected_failures_++;
  168. if (!verbose_)
  169. return;
  170. } else if (level == RECOMMENDED && !enforce_recommended_) {
  171. StringAppendF(&output_, "WARNING, test=%s: ", test_name.c_str());
  172. } else {
  173. StringAppendF(&output_, "ERROR, test=%s: ", test_name.c_str());
  174. unexpected_failing_tests_.insert(test_name);
  175. }
  176. va_list args;
  177. va_start(args, fmt);
  178. StringAppendV(&output_, fmt, args);
  179. va_end(args);
  180. StringAppendF(&output_, " request=%s, response=%s\n",
  181. request.ShortDebugString().c_str(),
  182. response.ShortDebugString().c_str());
  183. }
  184. void ConformanceTestSuite::ReportSkip(const string& test_name,
  185. const ConformanceRequest& request,
  186. const ConformanceResponse& response) {
  187. if (verbose_) {
  188. StringAppendF(&output_, "SKIPPED, test=%s request=%s, response=%s\n",
  189. test_name.c_str(), request.ShortDebugString().c_str(),
  190. response.ShortDebugString().c_str());
  191. }
  192. skipped_.insert(test_name);
  193. }
  194. string ConformanceTestSuite::ConformanceLevelToString(ConformanceLevel level) {
  195. switch (level) {
  196. case REQUIRED: return "Required";
  197. case RECOMMENDED: return "Recommended";
  198. }
  199. GOOGLE_LOG(FATAL) << "Unknown value: " << level;
  200. return "";
  201. }
  202. void ConformanceTestSuite::RunTest(const string& test_name,
  203. const ConformanceRequest& request,
  204. ConformanceResponse* response) {
  205. if (test_names_.insert(test_name).second == false) {
  206. GOOGLE_LOG(FATAL) << "Duplicated test name: " << test_name;
  207. }
  208. string serialized_request;
  209. string serialized_response;
  210. request.SerializeToString(&serialized_request);
  211. runner_->RunTest(test_name, serialized_request, &serialized_response);
  212. if (!response->ParseFromString(serialized_response)) {
  213. response->Clear();
  214. response->set_runtime_error("response proto could not be parsed.");
  215. }
  216. if (verbose_) {
  217. StringAppendF(&output_, "conformance test: name=%s, request=%s, response=%s\n",
  218. test_name.c_str(),
  219. request.ShortDebugString().c_str(),
  220. response->ShortDebugString().c_str());
  221. }
  222. }
  223. void ConformanceTestSuite::RunValidInputTest(
  224. const string& test_name, ConformanceLevel level, const string& input,
  225. WireFormat input_format, const string& equivalent_text_format,
  226. WireFormat requested_output) {
  227. TestAllTypes reference_message;
  228. GOOGLE_CHECK(
  229. TextFormat::ParseFromString(equivalent_text_format, &reference_message))
  230. << "Failed to parse data for test case: " << test_name
  231. << ", data: " << equivalent_text_format;
  232. ConformanceRequest request;
  233. ConformanceResponse response;
  234. switch (input_format) {
  235. case conformance::PROTOBUF:
  236. request.set_protobuf_payload(input);
  237. break;
  238. case conformance::JSON:
  239. request.set_json_payload(input);
  240. break;
  241. default:
  242. GOOGLE_LOG(FATAL) << "Unspecified input format";
  243. }
  244. request.set_requested_output_format(requested_output);
  245. RunTest(test_name, request, &response);
  246. TestAllTypes test_message;
  247. switch (response.result_case()) {
  248. case ConformanceResponse::RESULT_NOT_SET:
  249. ReportFailure(test_name, level, request, response,
  250. "Response didn't have any field in the Response.");
  251. return;
  252. case ConformanceResponse::kParseError:
  253. case ConformanceResponse::kRuntimeError:
  254. case ConformanceResponse::kSerializeError:
  255. ReportFailure(test_name, level, request, response,
  256. "Failed to parse input or produce output.");
  257. return;
  258. case ConformanceResponse::kSkipped:
  259. ReportSkip(test_name, request, response);
  260. return;
  261. case ConformanceResponse::kJsonPayload: {
  262. if (requested_output != conformance::JSON) {
  263. ReportFailure(
  264. test_name, level, request, response,
  265. "Test was asked for protobuf output but provided JSON instead.");
  266. return;
  267. }
  268. string binary_protobuf;
  269. Status status =
  270. JsonToBinaryString(type_resolver_.get(), type_url_,
  271. response.json_payload(), &binary_protobuf);
  272. if (!status.ok()) {
  273. ReportFailure(test_name, level, request, response,
  274. "JSON output we received from test was unparseable.");
  275. return;
  276. }
  277. if (!test_message.ParseFromString(binary_protobuf)) {
  278. ReportFailure(test_name, level, request, response,
  279. "INTERNAL ERROR: internal JSON->protobuf transcode "
  280. "yielded unparseable proto.");
  281. return;
  282. }
  283. break;
  284. }
  285. case ConformanceResponse::kProtobufPayload: {
  286. if (requested_output != conformance::PROTOBUF) {
  287. ReportFailure(
  288. test_name, level, request, response,
  289. "Test was asked for JSON output but provided protobuf instead.");
  290. return;
  291. }
  292. if (!test_message.ParseFromString(response.protobuf_payload())) {
  293. ReportFailure(test_name, level, request, response,
  294. "Protobuf output we received from test was unparseable.");
  295. return;
  296. }
  297. break;
  298. }
  299. default:
  300. GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: "
  301. << response.result_case();
  302. }
  303. MessageDifferencer differencer;
  304. DefaultFieldComparator field_comparator;
  305. field_comparator.set_treat_nan_as_equal(true);
  306. differencer.set_field_comparator(&field_comparator);
  307. string differences;
  308. differencer.ReportDifferencesToString(&differences);
  309. if (differencer.Compare(reference_message, test_message)) {
  310. ReportSuccess(test_name);
  311. } else {
  312. ReportFailure(test_name, level, request, response,
  313. "Output was not equivalent to reference message: %s.",
  314. differences.c_str());
  315. }
  316. }
  317. // Expect that this precise protobuf will cause a parse error.
  318. void ConformanceTestSuite::ExpectParseFailureForProto(
  319. const string& proto, const string& test_name, ConformanceLevel level) {
  320. ConformanceRequest request;
  321. ConformanceResponse response;
  322. request.set_protobuf_payload(proto);
  323. string effective_test_name = ConformanceLevelToString(level) +
  324. ".ProtobufInput." + test_name;
  325. // We don't expect output, but if the program erroneously accepts the protobuf
  326. // we let it send its response as this. We must not leave it unspecified.
  327. request.set_requested_output_format(conformance::PROTOBUF);
  328. RunTest(effective_test_name, request, &response);
  329. if (response.result_case() == ConformanceResponse::kParseError) {
  330. ReportSuccess(effective_test_name);
  331. } else if (response.result_case() == ConformanceResponse::kSkipped) {
  332. ReportSkip(effective_test_name, request, response);
  333. } else {
  334. ReportFailure(effective_test_name, level, request, response,
  335. "Should have failed to parse, but didn't.");
  336. }
  337. }
  338. // Expect that this protobuf will cause a parse error, even if it is followed
  339. // by valid protobuf data. We can try running this twice: once with this
  340. // data verbatim and once with this data followed by some valid data.
  341. //
  342. // TODO(haberman): implement the second of these.
  343. void ConformanceTestSuite::ExpectHardParseFailureForProto(
  344. const string& proto, const string& test_name, ConformanceLevel level) {
  345. return ExpectParseFailureForProto(proto, test_name, level);
  346. }
  347. void ConformanceTestSuite::RunValidJsonTest(
  348. const string& test_name, ConformanceLevel level, const string& input_json,
  349. const string& equivalent_text_format) {
  350. RunValidInputTest(
  351. ConformanceLevelToString(level) + ".JsonInput." + test_name +
  352. ".ProtobufOutput", level, input_json, conformance::JSON,
  353. equivalent_text_format, conformance::PROTOBUF);
  354. RunValidInputTest(
  355. ConformanceLevelToString(level) + ".JsonInput." + test_name +
  356. ".JsonOutput", level, input_json, conformance::JSON,
  357. equivalent_text_format, conformance::JSON);
  358. }
  359. void ConformanceTestSuite::RunValidJsonTestWithProtobufInput(
  360. const string& test_name, ConformanceLevel level, const TestAllTypes& input,
  361. const string& equivalent_text_format) {
  362. RunValidInputTest(
  363. ConformanceLevelToString(level) + ".ProtobufInput." + test_name +
  364. ".JsonOutput", level, input.SerializeAsString(), conformance::PROTOBUF,
  365. equivalent_text_format, conformance::JSON);
  366. }
  367. void ConformanceTestSuite::RunValidProtobufTest(
  368. const string& test_name, ConformanceLevel level, const TestAllTypes& input,
  369. const string& equivalent_text_format) {
  370. RunValidInputTest("ProtobufInput." + test_name + ".ProtobufOutput", level,
  371. input.SerializeAsString(), conformance::PROTOBUF,
  372. equivalent_text_format, conformance::PROTOBUF);
  373. RunValidInputTest("ProtobufInput." + test_name + ".JsonOutput", level,
  374. input.SerializeAsString(), conformance::PROTOBUF,
  375. equivalent_text_format, conformance::JSON);
  376. }
  377. // According to proto3 JSON specification, JSON serializers follow more strict
  378. // rules than parsers (e.g., a serializer must serialize int32 values as JSON
  379. // numbers while the parser is allowed to accept them as JSON strings). This
  380. // method allows strict checking on a proto3 JSON serializer by inspecting
  381. // the JSON output directly.
  382. void ConformanceTestSuite::RunValidJsonTestWithValidator(
  383. const string& test_name, ConformanceLevel level, const string& input_json,
  384. const Validator& validator) {
  385. ConformanceRequest request;
  386. ConformanceResponse response;
  387. request.set_json_payload(input_json);
  388. request.set_requested_output_format(conformance::JSON);
  389. string effective_test_name = ConformanceLevelToString(level) +
  390. ".JsonInput." + test_name + ".Validator";
  391. RunTest(effective_test_name, request, &response);
  392. if (response.result_case() == ConformanceResponse::kSkipped) {
  393. ReportSkip(effective_test_name, request, response);
  394. return;
  395. }
  396. if (response.result_case() != ConformanceResponse::kJsonPayload) {
  397. ReportFailure(effective_test_name, level, request, response,
  398. "Expected JSON payload but got type %d.",
  399. response.result_case());
  400. return;
  401. }
  402. Json::Reader reader;
  403. Json::Value value;
  404. if (!reader.parse(response.json_payload(), value)) {
  405. ReportFailure(effective_test_name, level, request, response,
  406. "JSON payload cannot be parsed as valid JSON: %s",
  407. reader.getFormattedErrorMessages().c_str());
  408. return;
  409. }
  410. if (!validator(value)) {
  411. ReportFailure(effective_test_name, level, request, response,
  412. "JSON payload validation failed.");
  413. return;
  414. }
  415. ReportSuccess(effective_test_name);
  416. }
  417. void ConformanceTestSuite::ExpectParseFailureForJson(
  418. const string& test_name, ConformanceLevel level, const string& input_json) {
  419. ConformanceRequest request;
  420. ConformanceResponse response;
  421. request.set_json_payload(input_json);
  422. string effective_test_name =
  423. ConformanceLevelToString(level) + ".JsonInput." + test_name;
  424. // We don't expect output, but if the program erroneously accepts the protobuf
  425. // we let it send its response as this. We must not leave it unspecified.
  426. request.set_requested_output_format(conformance::JSON);
  427. RunTest(effective_test_name, request, &response);
  428. if (response.result_case() == ConformanceResponse::kParseError) {
  429. ReportSuccess(effective_test_name);
  430. } else if (response.result_case() == ConformanceResponse::kSkipped) {
  431. ReportSkip(effective_test_name, request, response);
  432. } else {
  433. ReportFailure(effective_test_name, level, request, response,
  434. "Should have failed to parse, but didn't.");
  435. }
  436. }
  437. void ConformanceTestSuite::ExpectSerializeFailureForJson(
  438. const string& test_name, ConformanceLevel level, const string& text_format) {
  439. TestAllTypes payload_message;
  440. GOOGLE_CHECK(
  441. TextFormat::ParseFromString(text_format, &payload_message))
  442. << "Failed to parse: " << text_format;
  443. ConformanceRequest request;
  444. ConformanceResponse response;
  445. request.set_protobuf_payload(payload_message.SerializeAsString());
  446. string effective_test_name =
  447. ConformanceLevelToString(level) + "." + test_name + ".JsonOutput";
  448. request.set_requested_output_format(conformance::JSON);
  449. RunTest(effective_test_name, request, &response);
  450. if (response.result_case() == ConformanceResponse::kSerializeError) {
  451. ReportSuccess(effective_test_name);
  452. } else if (response.result_case() == ConformanceResponse::kSkipped) {
  453. ReportSkip(effective_test_name, request, response);
  454. } else {
  455. ReportFailure(effective_test_name, level, request, response,
  456. "Should have failed to serialize, but didn't.");
  457. }
  458. }
  459. void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
  460. // Incomplete values for each wire type.
  461. static const string incompletes[6] = {
  462. string("\x80"), // VARINT
  463. string("abcdefg"), // 64BIT
  464. string("\x80"), // DELIMITED (partial length)
  465. string(), // START_GROUP (no value required)
  466. string(), // END_GROUP (no value required)
  467. string("abc") // 32BIT
  468. };
  469. uint32_t fieldnum = GetFieldNumberForType(type, false);
  470. uint32_t rep_fieldnum = GetFieldNumberForType(type, true);
  471. WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
  472. static_cast<WireFormatLite::FieldType>(type));
  473. const string& incomplete = incompletes[wire_type];
  474. const string type_name =
  475. UpperCase(string(".") + FieldDescriptor::TypeName(type));
  476. ExpectParseFailureForProto(
  477. tag(fieldnum, wire_type),
  478. "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
  479. ExpectParseFailureForProto(
  480. tag(rep_fieldnum, wire_type),
  481. "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
  482. ExpectParseFailureForProto(
  483. tag(UNKNOWN_FIELD, wire_type),
  484. "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
  485. ExpectParseFailureForProto(
  486. cat( tag(fieldnum, wire_type), incomplete ),
  487. "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
  488. ExpectParseFailureForProto(
  489. cat( tag(rep_fieldnum, wire_type), incomplete ),
  490. "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
  491. ExpectParseFailureForProto(
  492. cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
  493. "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
  494. if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
  495. ExpectParseFailureForProto(
  496. cat( tag(fieldnum, wire_type), varint(1) ),
  497. "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
  498. REQUIRED);
  499. ExpectParseFailureForProto(
  500. cat( tag(rep_fieldnum, wire_type), varint(1) ),
  501. "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
  502. REQUIRED);
  503. // EOF in the middle of delimited data for unknown value.
  504. ExpectParseFailureForProto(
  505. cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
  506. "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED);
  507. if (type == FieldDescriptor::TYPE_MESSAGE) {
  508. // Submessage ends in the middle of a value.
  509. string incomplete_submsg =
  510. cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
  511. incompletes[WireFormatLite::WIRETYPE_VARINT] );
  512. ExpectHardParseFailureForProto(
  513. cat( tag(fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  514. varint(incomplete_submsg.size()),
  515. incomplete_submsg ),
  516. "PrematureEofInSubmessageValue" + type_name, REQUIRED);
  517. }
  518. } else if (type != FieldDescriptor::TYPE_GROUP) {
  519. // Non-delimited, non-group: eligible for packing.
  520. // Packed region ends in the middle of a value.
  521. ExpectHardParseFailureForProto(
  522. cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  523. varint(incomplete.size()),
  524. incomplete ),
  525. "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
  526. // EOF in the middle of packed region.
  527. ExpectParseFailureForProto(
  528. cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  529. varint(1) ),
  530. "PrematureEofInPackedField" + type_name, REQUIRED);
  531. }
  532. }
  533. void ConformanceTestSuite::SetFailureList(const string& filename,
  534. const vector<string>& failure_list) {
  535. failure_list_filename_ = filename;
  536. expected_to_fail_.clear();
  537. std::copy(failure_list.begin(), failure_list.end(),
  538. std::inserter(expected_to_fail_, expected_to_fail_.end()));
  539. }
  540. bool ConformanceTestSuite::CheckSetEmpty(const set<string>& set_to_check,
  541. const std::string& write_to_file,
  542. const std::string& msg) {
  543. if (set_to_check.empty()) {
  544. return true;
  545. } else {
  546. StringAppendF(&output_, "\n");
  547. StringAppendF(&output_, "%s\n\n", msg.c_str());
  548. for (set<string>::const_iterator iter = set_to_check.begin();
  549. iter != set_to_check.end(); ++iter) {
  550. StringAppendF(&output_, " %s\n", iter->c_str());
  551. }
  552. StringAppendF(&output_, "\n");
  553. if (!write_to_file.empty()) {
  554. std::ofstream os(write_to_file);
  555. if (os) {
  556. for (set<string>::const_iterator iter = set_to_check.begin();
  557. iter != set_to_check.end(); ++iter) {
  558. os << *iter << "\n";
  559. }
  560. } else {
  561. StringAppendF(&output_, "Failed to open file: %s\n",
  562. write_to_file.c_str());
  563. }
  564. }
  565. return false;
  566. }
  567. }
  568. bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
  569. std::string* output) {
  570. runner_ = runner;
  571. successes_ = 0;
  572. expected_failures_ = 0;
  573. skipped_.clear();
  574. test_names_.clear();
  575. unexpected_failing_tests_.clear();
  576. unexpected_succeeding_tests_.clear();
  577. type_resolver_.reset(NewTypeResolverForDescriptorPool(
  578. kTypeUrlPrefix, DescriptorPool::generated_pool()));
  579. type_url_ = GetTypeUrl(TestAllTypes::descriptor());
  580. output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n";
  581. for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
  582. if (i == FieldDescriptor::TYPE_GROUP) continue;
  583. TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
  584. }
  585. RunValidJsonTest("HelloWorld", REQUIRED,
  586. "{\"optionalString\":\"Hello, World!\"}",
  587. "optional_string: 'Hello, World!'");
  588. // NOTE: The spec for JSON support is still being sorted out, these may not
  589. // all be correct.
  590. // Test field name conventions.
  591. RunValidJsonTest(
  592. "FieldNameInSnakeCase", REQUIRED,
  593. R"({
  594. "fieldname1": 1,
  595. "fieldName2": 2,
  596. "FieldName3": 3,
  597. "fieldName4": 4
  598. })",
  599. R"(
  600. fieldname1: 1
  601. field_name2: 2
  602. _field_name3: 3
  603. field__name4_: 4
  604. )");
  605. RunValidJsonTest(
  606. "FieldNameWithNumbers", REQUIRED,
  607. R"({
  608. "field0name5": 5,
  609. "field0Name6": 6
  610. })",
  611. R"(
  612. field0name5: 5
  613. field_0_name6: 6
  614. )");
  615. RunValidJsonTest(
  616. "FieldNameWithMixedCases", REQUIRED,
  617. R"({
  618. "fieldName7": 7,
  619. "FieldName8": 8,
  620. "fieldName9": 9,
  621. "FieldName10": 10,
  622. "FIELDNAME11": 11,
  623. "FIELDName12": 12
  624. })",
  625. R"(
  626. fieldName7: 7
  627. FieldName8: 8
  628. field_Name9: 9
  629. Field_Name10: 10
  630. FIELD_NAME11: 11
  631. FIELD_name12: 12
  632. )");
  633. RunValidJsonTest(
  634. "FieldNameWithDoubleUnderscores", RECOMMENDED,
  635. R"({
  636. "FieldName13": 13,
  637. "FieldName14": 14,
  638. "fieldName15": 15,
  639. "fieldName16": 16,
  640. "fieldName17": 17,
  641. "FieldName18": 18
  642. })",
  643. R"(
  644. __field_name13: 13
  645. __Field_name14: 14
  646. field__name15: 15
  647. field__Name16: 16
  648. field_name17__: 17
  649. Field_name18__: 18
  650. )");
  651. // Using the original proto field name in JSON is also allowed.
  652. RunValidJsonTest(
  653. "OriginalProtoFieldName", REQUIRED,
  654. R"({
  655. "fieldname1": 1,
  656. "field_name2": 2,
  657. "_field_name3": 3,
  658. "field__name4_": 4,
  659. "field0name5": 5,
  660. "field_0_name6": 6,
  661. "fieldName7": 7,
  662. "FieldName8": 8,
  663. "field_Name9": 9,
  664. "Field_Name10": 10,
  665. "FIELD_NAME11": 11,
  666. "FIELD_name12": 12,
  667. "__field_name13": 13,
  668. "__Field_name14": 14,
  669. "field__name15": 15,
  670. "field__Name16": 16,
  671. "field_name17__": 17,
  672. "Field_name18__": 18
  673. })",
  674. R"(
  675. fieldname1: 1
  676. field_name2: 2
  677. _field_name3: 3
  678. field__name4_: 4
  679. field0name5: 5
  680. field_0_name6: 6
  681. fieldName7: 7
  682. FieldName8: 8
  683. field_Name9: 9
  684. Field_Name10: 10
  685. FIELD_NAME11: 11
  686. FIELD_name12: 12
  687. __field_name13: 13
  688. __Field_name14: 14
  689. field__name15: 15
  690. field__Name16: 16
  691. field_name17__: 17
  692. Field_name18__: 18
  693. )");
  694. // Field names can be escaped.
  695. RunValidJsonTest(
  696. "FieldNameEscaped", REQUIRED,
  697. R"({"fieldn\u0061me1": 1})",
  698. "fieldname1: 1");
  699. // String ends with escape character.
  700. ExpectParseFailureForJson(
  701. "StringEndsWithEscapeChar", RECOMMENDED,
  702. "{\"optionalString\": \"abc\\");
  703. // Field names must be quoted (or it's not valid JSON).
  704. ExpectParseFailureForJson(
  705. "FieldNameNotQuoted", RECOMMENDED,
  706. "{fieldname1: 1}");
  707. // Trailing comma is not allowed (not valid JSON).
  708. ExpectParseFailureForJson(
  709. "TrailingCommaInAnObject", RECOMMENDED,
  710. R"({"fieldname1":1,})");
  711. ExpectParseFailureForJson(
  712. "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
  713. R"({"fieldname1":1 ,})");
  714. ExpectParseFailureForJson(
  715. "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
  716. R"({"fieldname1":1 , })");
  717. ExpectParseFailureForJson(
  718. "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
  719. R"({
  720. "fieldname1":1,
  721. })");
  722. // JSON doesn't support comments.
  723. ExpectParseFailureForJson(
  724. "JsonWithComments", RECOMMENDED,
  725. R"({
  726. // This is a comment.
  727. "fieldname1": 1
  728. })");
  729. // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
  730. RunValidJsonTest(
  731. "OneLineNoSpaces", RECOMMENDED,
  732. "{\"optionalInt32\":1,\"optionalInt64\":2}",
  733. R"(
  734. optional_int32: 1
  735. optional_int64: 2
  736. )");
  737. RunValidJsonTest(
  738. "OneLineWithSpaces", RECOMMENDED,
  739. "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
  740. R"(
  741. optional_int32: 1
  742. optional_int64: 2
  743. )");
  744. RunValidJsonTest(
  745. "MultilineNoSpaces", RECOMMENDED,
  746. "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
  747. R"(
  748. optional_int32: 1
  749. optional_int64: 2
  750. )");
  751. RunValidJsonTest(
  752. "MultilineWithSpaces", RECOMMENDED,
  753. "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n",
  754. R"(
  755. optional_int32: 1
  756. optional_int64: 2
  757. )");
  758. // Missing comma between key/value pairs.
  759. ExpectParseFailureForJson(
  760. "MissingCommaOneLine", RECOMMENDED,
  761. "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
  762. ExpectParseFailureForJson(
  763. "MissingCommaMultiline", RECOMMENDED,
  764. "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}");
  765. // Duplicated field names are not allowed.
  766. ExpectParseFailureForJson(
  767. "FieldNameDuplicate", RECOMMENDED,
  768. R"({
  769. "optionalNestedMessage": {a: 1},
  770. "optionalNestedMessage": {}
  771. })");
  772. ExpectParseFailureForJson(
  773. "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
  774. R"({
  775. "optional_nested_message": {a: 1},
  776. "optionalNestedMessage": {}
  777. })");
  778. ExpectParseFailureForJson(
  779. "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
  780. R"({
  781. "optionalNestedMessage": {a: 1},
  782. "optional_nested_message": {}
  783. })");
  784. // Serializers should use lowerCamelCase by default.
  785. RunValidJsonTestWithValidator(
  786. "FieldNameInLowerCamelCase", REQUIRED,
  787. R"({
  788. "fieldname1": 1,
  789. "fieldName2": 2,
  790. "FieldName3": 3,
  791. "fieldName4": 4
  792. })",
  793. [](const Json::Value& value) {
  794. return value.isMember("fieldname1") &&
  795. value.isMember("fieldName2") &&
  796. value.isMember("FieldName3") &&
  797. value.isMember("fieldName4");
  798. });
  799. RunValidJsonTestWithValidator(
  800. "FieldNameWithNumbers", REQUIRED,
  801. R"({
  802. "field0name5": 5,
  803. "field0Name6": 6
  804. })",
  805. [](const Json::Value& value) {
  806. return value.isMember("field0name5") &&
  807. value.isMember("field0Name6");
  808. });
  809. RunValidJsonTestWithValidator(
  810. "FieldNameWithMixedCases", REQUIRED,
  811. R"({
  812. "fieldName7": 7,
  813. "FieldName8": 8,
  814. "fieldName9": 9,
  815. "FieldName10": 10,
  816. "FIELDNAME11": 11,
  817. "FIELDName12": 12
  818. })",
  819. [](const Json::Value& value) {
  820. return value.isMember("fieldName7") &&
  821. value.isMember("FieldName8") &&
  822. value.isMember("fieldName9") &&
  823. value.isMember("FieldName10") &&
  824. value.isMember("FIELDNAME11") &&
  825. value.isMember("FIELDName12");
  826. });
  827. RunValidJsonTestWithValidator(
  828. "FieldNameWithDoubleUnderscores", RECOMMENDED,
  829. R"({
  830. "FieldName13": 13,
  831. "FieldName14": 14,
  832. "fieldName15": 15,
  833. "fieldName16": 16,
  834. "fieldName17": 17,
  835. "FieldName18": 18
  836. })",
  837. [](const Json::Value& value) {
  838. return value.isMember("FieldName13") &&
  839. value.isMember("FieldName14") &&
  840. value.isMember("fieldName15") &&
  841. value.isMember("fieldName16") &&
  842. value.isMember("fieldName17") &&
  843. value.isMember("FieldName18");
  844. });
  845. // Integer fields.
  846. RunValidJsonTest(
  847. "Int32FieldMaxValue", REQUIRED,
  848. R"({"optionalInt32": 2147483647})",
  849. "optional_int32: 2147483647");
  850. RunValidJsonTest(
  851. "Int32FieldMinValue", REQUIRED,
  852. R"({"optionalInt32": -2147483648})",
  853. "optional_int32: -2147483648");
  854. RunValidJsonTest(
  855. "Uint32FieldMaxValue", REQUIRED,
  856. R"({"optionalUint32": 4294967295})",
  857. "optional_uint32: 4294967295");
  858. RunValidJsonTest(
  859. "Int64FieldMaxValue", REQUIRED,
  860. R"({"optionalInt64": "9223372036854775807"})",
  861. "optional_int64: 9223372036854775807");
  862. RunValidJsonTest(
  863. "Int64FieldMinValue", REQUIRED,
  864. R"({"optionalInt64": "-9223372036854775808"})",
  865. "optional_int64: -9223372036854775808");
  866. RunValidJsonTest(
  867. "Uint64FieldMaxValue", REQUIRED,
  868. R"({"optionalUint64": "18446744073709551615"})",
  869. "optional_uint64: 18446744073709551615");
  870. // While not the largest Int64, this is the largest
  871. // Int64 which can be exactly represented within an
  872. // IEEE-754 64-bit float, which is the expected level
  873. // of interoperability guarantee. Larger values may
  874. // work in some implementations, but should not be
  875. // relied upon.
  876. RunValidJsonTest(
  877. "Int64FieldMaxValueNotQuoted", REQUIRED,
  878. R"({"optionalInt64": 9223372036854774784})",
  879. "optional_int64: 9223372036854774784");
  880. RunValidJsonTest(
  881. "Int64FieldMinValueNotQuoted", REQUIRED,
  882. R"({"optionalInt64": -9223372036854775808})",
  883. "optional_int64: -9223372036854775808");
  884. // Largest interoperable Uint64; see comment above
  885. // for Int64FieldMaxValueNotQuoted.
  886. RunValidJsonTest(
  887. "Uint64FieldMaxValueNotQuoted", REQUIRED,
  888. R"({"optionalUint64": 18446744073709549568})",
  889. "optional_uint64: 18446744073709549568");
  890. // Values can be represented as JSON strings.
  891. RunValidJsonTest(
  892. "Int32FieldStringValue", REQUIRED,
  893. R"({"optionalInt32": "2147483647"})",
  894. "optional_int32: 2147483647");
  895. RunValidJsonTest(
  896. "Int32FieldStringValueEscaped", REQUIRED,
  897. R"({"optionalInt32": "2\u003147483647"})",
  898. "optional_int32: 2147483647");
  899. // Parsers reject out-of-bound integer values.
  900. ExpectParseFailureForJson(
  901. "Int32FieldTooLarge", REQUIRED,
  902. R"({"optionalInt32": 2147483648})");
  903. ExpectParseFailureForJson(
  904. "Int32FieldTooSmall", REQUIRED,
  905. R"({"optionalInt32": -2147483649})");
  906. ExpectParseFailureForJson(
  907. "Uint32FieldTooLarge", REQUIRED,
  908. R"({"optionalUint32": 4294967296})");
  909. ExpectParseFailureForJson(
  910. "Int64FieldTooLarge", REQUIRED,
  911. R"({"optionalInt64": "9223372036854775808"})");
  912. ExpectParseFailureForJson(
  913. "Int64FieldTooSmall", REQUIRED,
  914. R"({"optionalInt64": "-9223372036854775809"})");
  915. ExpectParseFailureForJson(
  916. "Uint64FieldTooLarge", REQUIRED,
  917. R"({"optionalUint64": "18446744073709551616"})");
  918. // Parser reject non-integer numeric values as well.
  919. ExpectParseFailureForJson(
  920. "Int32FieldNotInteger", REQUIRED,
  921. R"({"optionalInt32": 0.5})");
  922. ExpectParseFailureForJson(
  923. "Uint32FieldNotInteger", REQUIRED,
  924. R"({"optionalUint32": 0.5})");
  925. ExpectParseFailureForJson(
  926. "Int64FieldNotInteger", REQUIRED,
  927. R"({"optionalInt64": "0.5"})");
  928. ExpectParseFailureForJson(
  929. "Uint64FieldNotInteger", REQUIRED,
  930. R"({"optionalUint64": "0.5"})");
  931. // Integers but represented as float values are accepted.
  932. RunValidJsonTest(
  933. "Int32FieldFloatTrailingZero", REQUIRED,
  934. R"({"optionalInt32": 100000.000})",
  935. "optional_int32: 100000");
  936. RunValidJsonTest(
  937. "Int32FieldExponentialFormat", REQUIRED,
  938. R"({"optionalInt32": 1e5})",
  939. "optional_int32: 100000");
  940. RunValidJsonTest(
  941. "Int32FieldMaxFloatValue", REQUIRED,
  942. R"({"optionalInt32": 2.147483647e9})",
  943. "optional_int32: 2147483647");
  944. RunValidJsonTest(
  945. "Int32FieldMinFloatValue", REQUIRED,
  946. R"({"optionalInt32": -2.147483648e9})",
  947. "optional_int32: -2147483648");
  948. RunValidJsonTest(
  949. "Uint32FieldMaxFloatValue", REQUIRED,
  950. R"({"optionalUint32": 4.294967295e9})",
  951. "optional_uint32: 4294967295");
  952. // Parser reject non-numeric values.
  953. ExpectParseFailureForJson(
  954. "Int32FieldNotNumber", REQUIRED,
  955. R"({"optionalInt32": "3x3"})");
  956. ExpectParseFailureForJson(
  957. "Uint32FieldNotNumber", REQUIRED,
  958. R"({"optionalUint32": "3x3"})");
  959. ExpectParseFailureForJson(
  960. "Int64FieldNotNumber", REQUIRED,
  961. R"({"optionalInt64": "3x3"})");
  962. ExpectParseFailureForJson(
  963. "Uint64FieldNotNumber", REQUIRED,
  964. R"({"optionalUint64": "3x3"})");
  965. // JSON does not allow "+" on numric values.
  966. ExpectParseFailureForJson(
  967. "Int32FieldPlusSign", REQUIRED,
  968. R"({"optionalInt32": +1})");
  969. // JSON doesn't allow leading 0s.
  970. ExpectParseFailureForJson(
  971. "Int32FieldLeadingZero", REQUIRED,
  972. R"({"optionalInt32": 01})");
  973. ExpectParseFailureForJson(
  974. "Int32FieldNegativeWithLeadingZero", REQUIRED,
  975. R"({"optionalInt32": -01})");
  976. // String values must follow the same syntax rule. Specifically leading
  977. // or traling spaces are not allowed.
  978. ExpectParseFailureForJson(
  979. "Int32FieldLeadingSpace", REQUIRED,
  980. R"({"optionalInt32": " 1"})");
  981. ExpectParseFailureForJson(
  982. "Int32FieldTrailingSpace", REQUIRED,
  983. R"({"optionalInt32": "1 "})");
  984. // 64-bit values are serialized as strings.
  985. RunValidJsonTestWithValidator(
  986. "Int64FieldBeString", RECOMMENDED,
  987. R"({"optionalInt64": 1})",
  988. [](const Json::Value& value) {
  989. return value["optionalInt64"].type() == Json::stringValue &&
  990. value["optionalInt64"].asString() == "1";
  991. });
  992. RunValidJsonTestWithValidator(
  993. "Uint64FieldBeString", RECOMMENDED,
  994. R"({"optionalUint64": 1})",
  995. [](const Json::Value& value) {
  996. return value["optionalUint64"].type() == Json::stringValue &&
  997. value["optionalUint64"].asString() == "1";
  998. });
  999. // Bool fields.
  1000. RunValidJsonTest(
  1001. "BoolFieldTrue", REQUIRED,
  1002. R"({"optionalBool":true})",
  1003. "optional_bool: true");
  1004. RunValidJsonTest(
  1005. "BoolFieldFalse", REQUIRED,
  1006. R"({"optionalBool":false})",
  1007. "optional_bool: false");
  1008. // Other forms are not allowed.
  1009. ExpectParseFailureForJson(
  1010. "BoolFieldIntegerZero", RECOMMENDED,
  1011. R"({"optionalBool":0})");
  1012. ExpectParseFailureForJson(
  1013. "BoolFieldIntegerOne", RECOMMENDED,
  1014. R"({"optionalBool":1})");
  1015. ExpectParseFailureForJson(
  1016. "BoolFieldCamelCaseTrue", RECOMMENDED,
  1017. R"({"optionalBool":True})");
  1018. ExpectParseFailureForJson(
  1019. "BoolFieldCamelCaseFalse", RECOMMENDED,
  1020. R"({"optionalBool":False})");
  1021. ExpectParseFailureForJson(
  1022. "BoolFieldAllCapitalTrue", RECOMMENDED,
  1023. R"({"optionalBool":TRUE})");
  1024. ExpectParseFailureForJson(
  1025. "BoolFieldAllCapitalFalse", RECOMMENDED,
  1026. R"({"optionalBool":FALSE})");
  1027. ExpectParseFailureForJson(
  1028. "BoolFieldDoubleQuotedTrue", RECOMMENDED,
  1029. R"({"optionalBool":"true"})");
  1030. ExpectParseFailureForJson(
  1031. "BoolFieldDoubleQuotedFalse", RECOMMENDED,
  1032. R"({"optionalBool":"false"})");
  1033. // Float fields.
  1034. RunValidJsonTest(
  1035. "FloatFieldMinPositiveValue", REQUIRED,
  1036. R"({"optionalFloat": 1.175494e-38})",
  1037. "optional_float: 1.175494e-38");
  1038. RunValidJsonTest(
  1039. "FloatFieldMaxNegativeValue", REQUIRED,
  1040. R"({"optionalFloat": -1.175494e-38})",
  1041. "optional_float: -1.175494e-38");
  1042. RunValidJsonTest(
  1043. "FloatFieldMaxPositiveValue", REQUIRED,
  1044. R"({"optionalFloat": 3.402823e+38})",
  1045. "optional_float: 3.402823e+38");
  1046. RunValidJsonTest(
  1047. "FloatFieldMinNegativeValue", REQUIRED,
  1048. R"({"optionalFloat": 3.402823e+38})",
  1049. "optional_float: 3.402823e+38");
  1050. // Values can be quoted.
  1051. RunValidJsonTest(
  1052. "FloatFieldQuotedValue", REQUIRED,
  1053. R"({"optionalFloat": "1"})",
  1054. "optional_float: 1");
  1055. // Special values.
  1056. RunValidJsonTest(
  1057. "FloatFieldNan", REQUIRED,
  1058. R"({"optionalFloat": "NaN"})",
  1059. "optional_float: nan");
  1060. RunValidJsonTest(
  1061. "FloatFieldInfinity", REQUIRED,
  1062. R"({"optionalFloat": "Infinity"})",
  1063. "optional_float: inf");
  1064. RunValidJsonTest(
  1065. "FloatFieldNegativeInfinity", REQUIRED,
  1066. R"({"optionalFloat": "-Infinity"})",
  1067. "optional_float: -inf");
  1068. // Non-cannonical Nan will be correctly normalized.
  1069. {
  1070. TestAllTypes message;
  1071. // IEEE floating-point standard 32-bit quiet NaN:
  1072. // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
  1073. message.set_optional_float(
  1074. WireFormatLite::DecodeFloat(0x7FA12345));
  1075. RunValidJsonTestWithProtobufInput(
  1076. "FloatFieldNormalizeQuietNan", REQUIRED, message,
  1077. "optional_float: nan");
  1078. // IEEE floating-point standard 64-bit signaling NaN:
  1079. // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
  1080. message.set_optional_float(
  1081. WireFormatLite::DecodeFloat(0xFFB54321));
  1082. RunValidJsonTestWithProtobufInput(
  1083. "FloatFieldNormalizeSignalingNan", REQUIRED, message,
  1084. "optional_float: nan");
  1085. }
  1086. // Special values must be quoted.
  1087. ExpectParseFailureForJson(
  1088. "FloatFieldNanNotQuoted", RECOMMENDED,
  1089. R"({"optionalFloat": NaN})");
  1090. ExpectParseFailureForJson(
  1091. "FloatFieldInfinityNotQuoted", RECOMMENDED,
  1092. R"({"optionalFloat": Infinity})");
  1093. ExpectParseFailureForJson(
  1094. "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
  1095. R"({"optionalFloat": -Infinity})");
  1096. // Parsers should reject out-of-bound values.
  1097. ExpectParseFailureForJson(
  1098. "FloatFieldTooSmall", REQUIRED,
  1099. R"({"optionalFloat": -3.502823e+38})");
  1100. ExpectParseFailureForJson(
  1101. "FloatFieldTooLarge", REQUIRED,
  1102. R"({"optionalFloat": 3.502823e+38})");
  1103. // Double fields.
  1104. RunValidJsonTest(
  1105. "DoubleFieldMinPositiveValue", REQUIRED,
  1106. R"({"optionalDouble": 2.22507e-308})",
  1107. "optional_double: 2.22507e-308");
  1108. RunValidJsonTest(
  1109. "DoubleFieldMaxNegativeValue", REQUIRED,
  1110. R"({"optionalDouble": -2.22507e-308})",
  1111. "optional_double: -2.22507e-308");
  1112. RunValidJsonTest(
  1113. "DoubleFieldMaxPositiveValue", REQUIRED,
  1114. R"({"optionalDouble": 1.79769e+308})",
  1115. "optional_double: 1.79769e+308");
  1116. RunValidJsonTest(
  1117. "DoubleFieldMinNegativeValue", REQUIRED,
  1118. R"({"optionalDouble": -1.79769e+308})",
  1119. "optional_double: -1.79769e+308");
  1120. // Values can be quoted.
  1121. RunValidJsonTest(
  1122. "DoubleFieldQuotedValue", REQUIRED,
  1123. R"({"optionalDouble": "1"})",
  1124. "optional_double: 1");
  1125. // Speical values.
  1126. RunValidJsonTest(
  1127. "DoubleFieldNan", REQUIRED,
  1128. R"({"optionalDouble": "NaN"})",
  1129. "optional_double: nan");
  1130. RunValidJsonTest(
  1131. "DoubleFieldInfinity", REQUIRED,
  1132. R"({"optionalDouble": "Infinity"})",
  1133. "optional_double: inf");
  1134. RunValidJsonTest(
  1135. "DoubleFieldNegativeInfinity", REQUIRED,
  1136. R"({"optionalDouble": "-Infinity"})",
  1137. "optional_double: -inf");
  1138. // Non-cannonical Nan will be correctly normalized.
  1139. {
  1140. TestAllTypes message;
  1141. message.set_optional_double(
  1142. WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
  1143. RunValidJsonTestWithProtobufInput(
  1144. "DoubleFieldNormalizeQuietNan", REQUIRED, message,
  1145. "optional_double: nan");
  1146. message.set_optional_double(
  1147. WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
  1148. RunValidJsonTestWithProtobufInput(
  1149. "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
  1150. "optional_double: nan");
  1151. }
  1152. // Special values must be quoted.
  1153. ExpectParseFailureForJson(
  1154. "DoubleFieldNanNotQuoted", RECOMMENDED,
  1155. R"({"optionalDouble": NaN})");
  1156. ExpectParseFailureForJson(
  1157. "DoubleFieldInfinityNotQuoted", RECOMMENDED,
  1158. R"({"optionalDouble": Infinity})");
  1159. ExpectParseFailureForJson(
  1160. "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
  1161. R"({"optionalDouble": -Infinity})");
  1162. // Parsers should reject out-of-bound values.
  1163. ExpectParseFailureForJson(
  1164. "DoubleFieldTooSmall", REQUIRED,
  1165. R"({"optionalDouble": -1.89769e+308})");
  1166. ExpectParseFailureForJson(
  1167. "DoubleFieldTooLarge", REQUIRED,
  1168. R"({"optionalDouble": +1.89769e+308})");
  1169. // Enum fields.
  1170. RunValidJsonTest(
  1171. "EnumField", REQUIRED,
  1172. R"({"optionalNestedEnum": "FOO"})",
  1173. "optional_nested_enum: FOO");
  1174. // Enum values must be represented as strings.
  1175. ExpectParseFailureForJson(
  1176. "EnumFieldNotQuoted", REQUIRED,
  1177. R"({"optionalNestedEnum": FOO})");
  1178. // Numeric values are allowed.
  1179. RunValidJsonTest(
  1180. "EnumFieldNumericValueZero", REQUIRED,
  1181. R"({"optionalNestedEnum": 0})",
  1182. "optional_nested_enum: FOO");
  1183. RunValidJsonTest(
  1184. "EnumFieldNumericValueNonZero", REQUIRED,
  1185. R"({"optionalNestedEnum": 1})",
  1186. "optional_nested_enum: BAR");
  1187. // Unknown enum values are represented as numeric values.
  1188. RunValidJsonTestWithValidator(
  1189. "EnumFieldUnknownValue", REQUIRED,
  1190. R"({"optionalNestedEnum": 123})",
  1191. [](const Json::Value& value) {
  1192. return value["optionalNestedEnum"].type() == Json::intValue &&
  1193. value["optionalNestedEnum"].asInt() == 123;
  1194. });
  1195. // String fields.
  1196. RunValidJsonTest(
  1197. "StringField", REQUIRED,
  1198. R"({"optionalString": "Hello world!"})",
  1199. "optional_string: \"Hello world!\"");
  1200. RunValidJsonTest(
  1201. "StringFieldUnicode", REQUIRED,
  1202. // Google in Chinese.
  1203. R"({"optionalString": "谷歌"})",
  1204. R"(optional_string: "谷歌")");
  1205. RunValidJsonTest(
  1206. "StringFieldEscape", REQUIRED,
  1207. R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
  1208. R"(optional_string: "\"\\/\b\f\n\r\t")");
  1209. RunValidJsonTest(
  1210. "StringFieldUnicodeEscape", REQUIRED,
  1211. R"({"optionalString": "\u8C37\u6B4C"})",
  1212. R"(optional_string: "谷歌")");
  1213. RunValidJsonTest(
  1214. "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
  1215. R"({"optionalString": "\u8c37\u6b4c"})",
  1216. R"(optional_string: "谷歌")");
  1217. RunValidJsonTest(
  1218. "StringFieldSurrogatePair", REQUIRED,
  1219. // The character is an emoji: grinning face with smiling eyes. 😁
  1220. R"({"optionalString": "\uD83D\uDE01"})",
  1221. R"(optional_string: "\xF0\x9F\x98\x81")");
  1222. // Unicode escapes must start with "\u" (lowercase u).
  1223. ExpectParseFailureForJson(
  1224. "StringFieldUppercaseEscapeLetter", RECOMMENDED,
  1225. R"({"optionalString": "\U8C37\U6b4C"})");
  1226. ExpectParseFailureForJson(
  1227. "StringFieldInvalidEscape", RECOMMENDED,
  1228. R"({"optionalString": "\uXXXX\u6B4C"})");
  1229. ExpectParseFailureForJson(
  1230. "StringFieldUnterminatedEscape", RECOMMENDED,
  1231. R"({"optionalString": "\u8C3"})");
  1232. ExpectParseFailureForJson(
  1233. "StringFieldUnpairedHighSurrogate", RECOMMENDED,
  1234. R"({"optionalString": "\uD800"})");
  1235. ExpectParseFailureForJson(
  1236. "StringFieldUnpairedLowSurrogate", RECOMMENDED,
  1237. R"({"optionalString": "\uDC00"})");
  1238. ExpectParseFailureForJson(
  1239. "StringFieldSurrogateInWrongOrder", RECOMMENDED,
  1240. R"({"optionalString": "\uDE01\uD83D"})");
  1241. ExpectParseFailureForJson(
  1242. "StringFieldNotAString", REQUIRED,
  1243. R"({"optionalString": 12345})");
  1244. // Bytes fields.
  1245. RunValidJsonTest(
  1246. "BytesField", REQUIRED,
  1247. R"({"optionalBytes": "AQI="})",
  1248. R"(optional_bytes: "\x01\x02")");
  1249. ExpectParseFailureForJson(
  1250. "BytesFieldInvalidBase64Characters", REQUIRED,
  1251. R"({"optionalBytes": "-_=="})");
  1252. // Message fields.
  1253. RunValidJsonTest(
  1254. "MessageField", REQUIRED,
  1255. R"({"optionalNestedMessage": {"a": 1234}})",
  1256. "optional_nested_message: {a: 1234}");
  1257. // Oneof fields.
  1258. ExpectParseFailureForJson(
  1259. "OneofFieldDuplicate", REQUIRED,
  1260. R"({"oneofUint32": 1, "oneofString": "test"})");
  1261. // Ensure zero values for oneof make it out/backs.
  1262. {
  1263. TestAllTypes message;
  1264. message.set_oneof_uint32(0);
  1265. RunValidProtobufTest(
  1266. "OneofZeroUint32", RECOMMENDED, message, "oneof_uint32: 0");
  1267. message.mutable_oneof_nested_message()->set_a(0);
  1268. RunValidProtobufTest(
  1269. "OneofZeroMessage", RECOMMENDED, message, "oneof_nested_message: {}");
  1270. message.set_oneof_string("");
  1271. RunValidProtobufTest(
  1272. "OneofZeroString", RECOMMENDED, message, "oneof_string: \"\"");
  1273. message.set_oneof_bytes("");
  1274. RunValidProtobufTest(
  1275. "OneofZeroBytes", RECOMMENDED, message, "oneof_bytes: \"\"");
  1276. message.set_oneof_bool(false);
  1277. RunValidProtobufTest(
  1278. "OneofZeroBool", RECOMMENDED, message, "oneof_bool: false");
  1279. message.set_oneof_uint64(0);
  1280. RunValidProtobufTest(
  1281. "OneofZeroUint64", RECOMMENDED, message, "oneof_uint64: 0");
  1282. message.set_oneof_float(0.0f);
  1283. RunValidProtobufTest(
  1284. "OneofZeroFloat", RECOMMENDED, message, "oneof_float: 0");
  1285. message.set_oneof_double(0.0);
  1286. RunValidProtobufTest(
  1287. "OneofZeroDouble", RECOMMENDED, message, "oneof_double: 0");
  1288. message.set_oneof_enum(TestAllTypes::FOO);
  1289. RunValidProtobufTest(
  1290. "OneofZeroEnum", RECOMMENDED, message, "oneof_enum: FOO");
  1291. }
  1292. RunValidJsonTest(
  1293. "OneofZeroUint32", RECOMMENDED,
  1294. R"({"oneofUint32": 0})", "oneof_uint32: 0");
  1295. RunValidJsonTest(
  1296. "OneofZeroMessage", RECOMMENDED,
  1297. R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
  1298. RunValidJsonTest(
  1299. "OneofZeroString", RECOMMENDED,
  1300. R"({"oneofString": ""})", "oneof_string: \"\"");
  1301. RunValidJsonTest(
  1302. "OneofZeroBytes", RECOMMENDED,
  1303. R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
  1304. RunValidJsonTest(
  1305. "OneofZeroBool", RECOMMENDED,
  1306. R"({"oneofBool": false})", "oneof_bool: false");
  1307. RunValidJsonTest(
  1308. "OneofZeroUint64", RECOMMENDED,
  1309. R"({"oneofUint64": 0})", "oneof_uint64: 0");
  1310. RunValidJsonTest(
  1311. "OneofZeroFloat", RECOMMENDED,
  1312. R"({"oneofFloat": 0.0})", "oneof_float: 0");
  1313. RunValidJsonTest(
  1314. "OneofZeroDouble", RECOMMENDED,
  1315. R"({"oneofDouble": 0.0})", "oneof_double: 0");
  1316. RunValidJsonTest(
  1317. "OneofZeroEnum", RECOMMENDED,
  1318. R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
  1319. // Repeated fields.
  1320. RunValidJsonTest(
  1321. "PrimitiveRepeatedField", REQUIRED,
  1322. R"({"repeatedInt32": [1, 2, 3, 4]})",
  1323. "repeated_int32: [1, 2, 3, 4]");
  1324. RunValidJsonTest(
  1325. "EnumRepeatedField", REQUIRED,
  1326. R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
  1327. "repeated_nested_enum: [FOO, BAR, BAZ]");
  1328. RunValidJsonTest(
  1329. "StringRepeatedField", REQUIRED,
  1330. R"({"repeatedString": ["Hello", "world"]})",
  1331. R"(repeated_string: ["Hello", "world"])");
  1332. RunValidJsonTest(
  1333. "BytesRepeatedField", REQUIRED,
  1334. R"({"repeatedBytes": ["AAEC", "AQI="]})",
  1335. R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
  1336. RunValidJsonTest(
  1337. "MessageRepeatedField", REQUIRED,
  1338. R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
  1339. "repeated_nested_message: {a: 1234}"
  1340. "repeated_nested_message: {a: 5678}");
  1341. // Repeated field elements are of incorrect type.
  1342. ExpectParseFailureForJson(
  1343. "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
  1344. R"({"repeatedInt32": [1, false, 3, 4]})");
  1345. ExpectParseFailureForJson(
  1346. "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
  1347. R"({"repeatedInt32": [1, 2, "name", 4]})");
  1348. ExpectParseFailureForJson(
  1349. "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
  1350. R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
  1351. ExpectParseFailureForJson(
  1352. "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
  1353. R"({"repeatedString": ["1", 2, "3", "4"]})");
  1354. ExpectParseFailureForJson(
  1355. "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
  1356. R"({"repeatedString": ["1", "2", false, "4"]})");
  1357. ExpectParseFailureForJson(
  1358. "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
  1359. R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
  1360. ExpectParseFailureForJson(
  1361. "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
  1362. R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
  1363. ExpectParseFailureForJson(
  1364. "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
  1365. R"({"repeatedNestedMessage": [{"a": 1}, false]})");
  1366. ExpectParseFailureForJson(
  1367. "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
  1368. R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
  1369. // Trailing comma in the repeated field is not allowed.
  1370. ExpectParseFailureForJson(
  1371. "RepeatedFieldTrailingComma", RECOMMENDED,
  1372. R"({"repeatedInt32": [1, 2, 3, 4,]})");
  1373. ExpectParseFailureForJson(
  1374. "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
  1375. "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
  1376. ExpectParseFailureForJson(
  1377. "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
  1378. "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
  1379. ExpectParseFailureForJson(
  1380. "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
  1381. "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}");
  1382. // Map fields.
  1383. RunValidJsonTest(
  1384. "Int32MapField", REQUIRED,
  1385. R"({"mapInt32Int32": {"1": 2, "3": 4}})",
  1386. "map_int32_int32: {key: 1 value: 2}"
  1387. "map_int32_int32: {key: 3 value: 4}");
  1388. ExpectParseFailureForJson(
  1389. "Int32MapFieldKeyNotQuoted", RECOMMENDED,
  1390. R"({"mapInt32Int32": {1: 2, 3: 4}})");
  1391. RunValidJsonTest(
  1392. "Uint32MapField", REQUIRED,
  1393. R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
  1394. "map_uint32_uint32: {key: 1 value: 2}"
  1395. "map_uint32_uint32: {key: 3 value: 4}");
  1396. ExpectParseFailureForJson(
  1397. "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
  1398. R"({"mapUint32Uint32": {1: 2, 3: 4}})");
  1399. RunValidJsonTest(
  1400. "Int64MapField", REQUIRED,
  1401. R"({"mapInt64Int64": {"1": 2, "3": 4}})",
  1402. "map_int64_int64: {key: 1 value: 2}"
  1403. "map_int64_int64: {key: 3 value: 4}");
  1404. ExpectParseFailureForJson(
  1405. "Int64MapFieldKeyNotQuoted", RECOMMENDED,
  1406. R"({"mapInt64Int64": {1: 2, 3: 4}})");
  1407. RunValidJsonTest(
  1408. "Uint64MapField", REQUIRED,
  1409. R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
  1410. "map_uint64_uint64: {key: 1 value: 2}"
  1411. "map_uint64_uint64: {key: 3 value: 4}");
  1412. ExpectParseFailureForJson(
  1413. "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
  1414. R"({"mapUint64Uint64": {1: 2, 3: 4}})");
  1415. RunValidJsonTest(
  1416. "BoolMapField", REQUIRED,
  1417. R"({"mapBoolBool": {"true": true, "false": false}})",
  1418. "map_bool_bool: {key: true value: true}"
  1419. "map_bool_bool: {key: false value: false}");
  1420. ExpectParseFailureForJson(
  1421. "BoolMapFieldKeyNotQuoted", RECOMMENDED,
  1422. R"({"mapBoolBool": {true: true, false: false}})");
  1423. RunValidJsonTest(
  1424. "MessageMapField", REQUIRED,
  1425. R"({
  1426. "mapStringNestedMessage": {
  1427. "hello": {"a": 1234},
  1428. "world": {"a": 5678}
  1429. }
  1430. })",
  1431. R"(
  1432. map_string_nested_message: {
  1433. key: "hello"
  1434. value: {a: 1234}
  1435. }
  1436. map_string_nested_message: {
  1437. key: "world"
  1438. value: {a: 5678}
  1439. }
  1440. )");
  1441. // Since Map keys are represented as JSON strings, escaping should be allowed.
  1442. RunValidJsonTest(
  1443. "Int32MapEscapedKey", REQUIRED,
  1444. R"({"mapInt32Int32": {"\u0031": 2}})",
  1445. "map_int32_int32: {key: 1 value: 2}");
  1446. RunValidJsonTest(
  1447. "Int64MapEscapedKey", REQUIRED,
  1448. R"({"mapInt64Int64": {"\u0031": 2}})",
  1449. "map_int64_int64: {key: 1 value: 2}");
  1450. RunValidJsonTest(
  1451. "BoolMapEscapedKey", REQUIRED,
  1452. R"({"mapBoolBool": {"tr\u0075e": true}})",
  1453. "map_bool_bool: {key: true value: true}");
  1454. // "null" is accepted for all fields types.
  1455. RunValidJsonTest(
  1456. "AllFieldAcceptNull", REQUIRED,
  1457. R"({
  1458. "optionalInt32": null,
  1459. "optionalInt64": null,
  1460. "optionalUint32": null,
  1461. "optionalUint64": null,
  1462. "optionalBool": null,
  1463. "optionalString": null,
  1464. "optionalBytes": null,
  1465. "optionalNestedEnum": null,
  1466. "optionalNestedMessage": null,
  1467. "repeatedInt32": null,
  1468. "repeatedInt64": null,
  1469. "repeatedUint32": null,
  1470. "repeatedUint64": null,
  1471. "repeatedBool": null,
  1472. "repeatedString": null,
  1473. "repeatedBytes": null,
  1474. "repeatedNestedEnum": null,
  1475. "repeatedNestedMessage": null,
  1476. "mapInt32Int32": null,
  1477. "mapBoolBool": null,
  1478. "mapStringNestedMessage": null
  1479. })",
  1480. "");
  1481. // Repeated field elements cannot be null.
  1482. ExpectParseFailureForJson(
  1483. "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
  1484. R"({"repeatedInt32": [1, null, 2]})");
  1485. ExpectParseFailureForJson(
  1486. "RepeatedFieldMessageElementIsNull", RECOMMENDED,
  1487. R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
  1488. // Map field keys cannot be null.
  1489. ExpectParseFailureForJson(
  1490. "MapFieldKeyIsNull", RECOMMENDED,
  1491. R"({"mapInt32Int32": {null: 1}})");
  1492. // Map field values cannot be null.
  1493. ExpectParseFailureForJson(
  1494. "MapFieldValueIsNull", RECOMMENDED,
  1495. R"({"mapInt32Int32": {"0": null}})");
  1496. // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
  1497. // quotes.
  1498. ExpectParseFailureForJson(
  1499. "StringFieldSingleQuoteKey", RECOMMENDED,
  1500. R"({'optionalString': "Hello world!"})");
  1501. ExpectParseFailureForJson(
  1502. "StringFieldSingleQuoteValue", RECOMMENDED,
  1503. R"({"optionalString": 'Hello world!'})");
  1504. ExpectParseFailureForJson(
  1505. "StringFieldSingleQuoteBoth", RECOMMENDED,
  1506. R"({'optionalString': 'Hello world!'})");
  1507. // Wrapper types.
  1508. RunValidJsonTest(
  1509. "OptionalBoolWrapper", REQUIRED,
  1510. R"({"optionalBoolWrapper": false})",
  1511. "optional_bool_wrapper: {value: false}");
  1512. RunValidJsonTest(
  1513. "OptionalInt32Wrapper", REQUIRED,
  1514. R"({"optionalInt32Wrapper": 0})",
  1515. "optional_int32_wrapper: {value: 0}");
  1516. RunValidJsonTest(
  1517. "OptionalUint32Wrapper", REQUIRED,
  1518. R"({"optionalUint32Wrapper": 0})",
  1519. "optional_uint32_wrapper: {value: 0}");
  1520. RunValidJsonTest(
  1521. "OptionalInt64Wrapper", REQUIRED,
  1522. R"({"optionalInt64Wrapper": 0})",
  1523. "optional_int64_wrapper: {value: 0}");
  1524. RunValidJsonTest(
  1525. "OptionalUint64Wrapper", REQUIRED,
  1526. R"({"optionalUint64Wrapper": 0})",
  1527. "optional_uint64_wrapper: {value: 0}");
  1528. RunValidJsonTest(
  1529. "OptionalFloatWrapper", REQUIRED,
  1530. R"({"optionalFloatWrapper": 0})",
  1531. "optional_float_wrapper: {value: 0}");
  1532. RunValidJsonTest(
  1533. "OptionalDoubleWrapper", REQUIRED,
  1534. R"({"optionalDoubleWrapper": 0})",
  1535. "optional_double_wrapper: {value: 0}");
  1536. RunValidJsonTest(
  1537. "OptionalStringWrapper", REQUIRED,
  1538. R"({"optionalStringWrapper": ""})",
  1539. R"(optional_string_wrapper: {value: ""})");
  1540. RunValidJsonTest(
  1541. "OptionalBytesWrapper", REQUIRED,
  1542. R"({"optionalBytesWrapper": ""})",
  1543. R"(optional_bytes_wrapper: {value: ""})");
  1544. RunValidJsonTest(
  1545. "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
  1546. R"({
  1547. "optionalBoolWrapper": true,
  1548. "optionalInt32Wrapper": 1,
  1549. "optionalUint32Wrapper": 1,
  1550. "optionalInt64Wrapper": "1",
  1551. "optionalUint64Wrapper": "1",
  1552. "optionalFloatWrapper": 1,
  1553. "optionalDoubleWrapper": 1,
  1554. "optionalStringWrapper": "1",
  1555. "optionalBytesWrapper": "AQI="
  1556. })",
  1557. R"(
  1558. optional_bool_wrapper: {value: true}
  1559. optional_int32_wrapper: {value: 1}
  1560. optional_uint32_wrapper: {value: 1}
  1561. optional_int64_wrapper: {value: 1}
  1562. optional_uint64_wrapper: {value: 1}
  1563. optional_float_wrapper: {value: 1}
  1564. optional_double_wrapper: {value: 1}
  1565. optional_string_wrapper: {value: "1"}
  1566. optional_bytes_wrapper: {value: "\x01\x02"}
  1567. )");
  1568. RunValidJsonTest(
  1569. "RepeatedBoolWrapper", REQUIRED,
  1570. R"({"repeatedBoolWrapper": [true, false]})",
  1571. "repeated_bool_wrapper: {value: true}"
  1572. "repeated_bool_wrapper: {value: false}");
  1573. RunValidJsonTest(
  1574. "RepeatedInt32Wrapper", REQUIRED,
  1575. R"({"repeatedInt32Wrapper": [0, 1]})",
  1576. "repeated_int32_wrapper: {value: 0}"
  1577. "repeated_int32_wrapper: {value: 1}");
  1578. RunValidJsonTest(
  1579. "RepeatedUint32Wrapper", REQUIRED,
  1580. R"({"repeatedUint32Wrapper": [0, 1]})",
  1581. "repeated_uint32_wrapper: {value: 0}"
  1582. "repeated_uint32_wrapper: {value: 1}");
  1583. RunValidJsonTest(
  1584. "RepeatedInt64Wrapper", REQUIRED,
  1585. R"({"repeatedInt64Wrapper": [0, 1]})",
  1586. "repeated_int64_wrapper: {value: 0}"
  1587. "repeated_int64_wrapper: {value: 1}");
  1588. RunValidJsonTest(
  1589. "RepeatedUint64Wrapper", REQUIRED,
  1590. R"({"repeatedUint64Wrapper": [0, 1]})",
  1591. "repeated_uint64_wrapper: {value: 0}"
  1592. "repeated_uint64_wrapper: {value: 1}");
  1593. RunValidJsonTest(
  1594. "RepeatedFloatWrapper", REQUIRED,
  1595. R"({"repeatedFloatWrapper": [0, 1]})",
  1596. "repeated_float_wrapper: {value: 0}"
  1597. "repeated_float_wrapper: {value: 1}");
  1598. RunValidJsonTest(
  1599. "RepeatedDoubleWrapper", REQUIRED,
  1600. R"({"repeatedDoubleWrapper": [0, 1]})",
  1601. "repeated_double_wrapper: {value: 0}"
  1602. "repeated_double_wrapper: {value: 1}");
  1603. RunValidJsonTest(
  1604. "RepeatedStringWrapper", REQUIRED,
  1605. R"({"repeatedStringWrapper": ["", "AQI="]})",
  1606. R"(
  1607. repeated_string_wrapper: {value: ""}
  1608. repeated_string_wrapper: {value: "AQI="}
  1609. )");
  1610. RunValidJsonTest(
  1611. "RepeatedBytesWrapper", REQUIRED,
  1612. R"({"repeatedBytesWrapper": ["", "AQI="]})",
  1613. R"(
  1614. repeated_bytes_wrapper: {value: ""}
  1615. repeated_bytes_wrapper: {value: "\x01\x02"}
  1616. )");
  1617. RunValidJsonTest(
  1618. "WrapperTypesWithNullValue", REQUIRED,
  1619. R"({
  1620. "optionalBoolWrapper": null,
  1621. "optionalInt32Wrapper": null,
  1622. "optionalUint32Wrapper": null,
  1623. "optionalInt64Wrapper": null,
  1624. "optionalUint64Wrapper": null,
  1625. "optionalFloatWrapper": null,
  1626. "optionalDoubleWrapper": null,
  1627. "optionalStringWrapper": null,
  1628. "optionalBytesWrapper": null,
  1629. "repeatedBoolWrapper": null,
  1630. "repeatedInt32Wrapper": null,
  1631. "repeatedUint32Wrapper": null,
  1632. "repeatedInt64Wrapper": null,
  1633. "repeatedUint64Wrapper": null,
  1634. "repeatedFloatWrapper": null,
  1635. "repeatedDoubleWrapper": null,
  1636. "repeatedStringWrapper": null,
  1637. "repeatedBytesWrapper": null
  1638. })",
  1639. "");
  1640. // Duration
  1641. RunValidJsonTest(
  1642. "DurationMinValue", REQUIRED,
  1643. R"({"optionalDuration": "-315576000000.999999999s"})",
  1644. "optional_duration: {seconds: -315576000000 nanos: -999999999}");
  1645. RunValidJsonTest(
  1646. "DurationMaxValue", REQUIRED,
  1647. R"({"optionalDuration": "315576000000.999999999s"})",
  1648. "optional_duration: {seconds: 315576000000 nanos: 999999999}");
  1649. RunValidJsonTest(
  1650. "DurationRepeatedValue", REQUIRED,
  1651. R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
  1652. "repeated_duration: {seconds: 1 nanos: 500000000}"
  1653. "repeated_duration: {seconds: -1 nanos: -500000000}");
  1654. ExpectParseFailureForJson(
  1655. "DurationMissingS", REQUIRED,
  1656. R"({"optionalDuration": "1"})");
  1657. ExpectParseFailureForJson(
  1658. "DurationJsonInputTooSmall", REQUIRED,
  1659. R"({"optionalDuration": "-315576000001.000000000s"})");
  1660. ExpectParseFailureForJson(
  1661. "DurationJsonInputTooLarge", REQUIRED,
  1662. R"({"optionalDuration": "315576000001.000000000s"})");
  1663. ExpectSerializeFailureForJson(
  1664. "DurationProtoInputTooSmall", REQUIRED,
  1665. "optional_duration: {seconds: -315576000001 nanos: 0}");
  1666. ExpectSerializeFailureForJson(
  1667. "DurationProtoInputTooLarge", REQUIRED,
  1668. "optional_duration: {seconds: 315576000001 nanos: 0}");
  1669. RunValidJsonTestWithValidator(
  1670. "DurationHasZeroFractionalDigit", RECOMMENDED,
  1671. R"({"optionalDuration": "1.000000000s"})",
  1672. [](const Json::Value& value) {
  1673. return value["optionalDuration"].asString() == "1s";
  1674. });
  1675. RunValidJsonTestWithValidator(
  1676. "DurationHas3FractionalDigits", RECOMMENDED,
  1677. R"({"optionalDuration": "1.010000000s"})",
  1678. [](const Json::Value& value) {
  1679. return value["optionalDuration"].asString() == "1.010s";
  1680. });
  1681. RunValidJsonTestWithValidator(
  1682. "DurationHas6FractionalDigits", RECOMMENDED,
  1683. R"({"optionalDuration": "1.000010000s"})",
  1684. [](const Json::Value& value) {
  1685. return value["optionalDuration"].asString() == "1.000010s";
  1686. });
  1687. RunValidJsonTestWithValidator(
  1688. "DurationHas9FractionalDigits", RECOMMENDED,
  1689. R"({"optionalDuration": "1.000000010s"})",
  1690. [](const Json::Value& value) {
  1691. return value["optionalDuration"].asString() == "1.000000010s";
  1692. });
  1693. // Timestamp
  1694. RunValidJsonTest(
  1695. "TimestampMinValue", REQUIRED,
  1696. R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
  1697. "optional_timestamp: {seconds: -62135596800}");
  1698. RunValidJsonTest(
  1699. "TimestampMaxValue", REQUIRED,
  1700. R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
  1701. "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1702. RunValidJsonTest(
  1703. "TimestampRepeatedValue", REQUIRED,
  1704. R"({
  1705. "repeatedTimestamp": [
  1706. "0001-01-01T00:00:00Z",
  1707. "9999-12-31T23:59:59.999999999Z"
  1708. ]
  1709. })",
  1710. "repeated_timestamp: {seconds: -62135596800}"
  1711. "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
  1712. RunValidJsonTest(
  1713. "TimestampWithPositiveOffset", REQUIRED,
  1714. R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
  1715. "optional_timestamp: {seconds: 0}");
  1716. RunValidJsonTest(
  1717. "TimestampWithNegativeOffset", REQUIRED,
  1718. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  1719. "optional_timestamp: {seconds: 0}");
  1720. ExpectParseFailureForJson(
  1721. "TimestampJsonInputTooSmall", REQUIRED,
  1722. R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  1723. ExpectParseFailureForJson(
  1724. "TimestampJsonInputTooLarge", REQUIRED,
  1725. R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  1726. ExpectParseFailureForJson(
  1727. "TimestampJsonInputMissingZ", REQUIRED,
  1728. R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  1729. ExpectParseFailureForJson(
  1730. "TimestampJsonInputMissingT", REQUIRED,
  1731. R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  1732. ExpectParseFailureForJson(
  1733. "TimestampJsonInputLowercaseZ", REQUIRED,
  1734. R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  1735. ExpectParseFailureForJson(
  1736. "TimestampJsonInputLowercaseT", REQUIRED,
  1737. R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  1738. ExpectSerializeFailureForJson(
  1739. "TimestampProtoInputTooSmall", REQUIRED,
  1740. "optional_timestamp: {seconds: -62135596801}");
  1741. ExpectSerializeFailureForJson(
  1742. "TimestampProtoInputTooLarge", REQUIRED,
  1743. "optional_timestamp: {seconds: 253402300800}");
  1744. RunValidJsonTestWithValidator(
  1745. "TimestampZeroNormalized", RECOMMENDED,
  1746. R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
  1747. [](const Json::Value& value) {
  1748. return value["optionalTimestamp"].asString() ==
  1749. "1970-01-01T00:00:00Z";
  1750. });
  1751. RunValidJsonTestWithValidator(
  1752. "TimestampHasZeroFractionalDigit", RECOMMENDED,
  1753. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
  1754. [](const Json::Value& value) {
  1755. return value["optionalTimestamp"].asString() ==
  1756. "1970-01-01T00:00:00Z";
  1757. });
  1758. RunValidJsonTestWithValidator(
  1759. "TimestampHas3FractionalDigits", RECOMMENDED,
  1760. R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
  1761. [](const Json::Value& value) {
  1762. return value["optionalTimestamp"].asString() ==
  1763. "1970-01-01T00:00:00.010Z";
  1764. });
  1765. RunValidJsonTestWithValidator(
  1766. "TimestampHas6FractionalDigits", RECOMMENDED,
  1767. R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
  1768. [](const Json::Value& value) {
  1769. return value["optionalTimestamp"].asString() ==
  1770. "1970-01-01T00:00:00.000010Z";
  1771. });
  1772. RunValidJsonTestWithValidator(
  1773. "TimestampHas9FractionalDigits", RECOMMENDED,
  1774. R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
  1775. [](const Json::Value& value) {
  1776. return value["optionalTimestamp"].asString() ==
  1777. "1970-01-01T00:00:00.000000010Z";
  1778. });
  1779. // FieldMask
  1780. RunValidJsonTest(
  1781. "FieldMask", REQUIRED,
  1782. R"({"optionalFieldMask": "foo,barBaz"})",
  1783. R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  1784. ExpectParseFailureForJson(
  1785. "FieldMaskInvalidCharacter", RECOMMENDED,
  1786. R"({"optionalFieldMask": "foo,bar_bar"})");
  1787. ExpectSerializeFailureForJson(
  1788. "FieldMaskPathsDontRoundTrip", RECOMMENDED,
  1789. R"(optional_field_mask: {paths: "fooBar"})");
  1790. ExpectSerializeFailureForJson(
  1791. "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
  1792. R"(optional_field_mask: {paths: "foo_3_bar"})");
  1793. ExpectSerializeFailureForJson(
  1794. "FieldMaskTooManyUnderscore", RECOMMENDED,
  1795. R"(optional_field_mask: {paths: "foo__bar"})");
  1796. // Struct
  1797. RunValidJsonTest(
  1798. "Struct", REQUIRED,
  1799. R"({
  1800. "optionalStruct": {
  1801. "nullValue": null,
  1802. "intValue": 1234,
  1803. "boolValue": true,
  1804. "doubleValue": 1234.5678,
  1805. "stringValue": "Hello world!",
  1806. "listValue": [1234, "5678"],
  1807. "objectValue": {
  1808. "value": 0
  1809. }
  1810. }
  1811. })",
  1812. R"(
  1813. optional_struct: {
  1814. fields: {
  1815. key: "nullValue"
  1816. value: {null_value: NULL_VALUE}
  1817. }
  1818. fields: {
  1819. key: "intValue"
  1820. value: {number_value: 1234}
  1821. }
  1822. fields: {
  1823. key: "boolValue"
  1824. value: {bool_value: true}
  1825. }
  1826. fields: {
  1827. key: "doubleValue"
  1828. value: {number_value: 1234.5678}
  1829. }
  1830. fields: {
  1831. key: "stringValue"
  1832. value: {string_value: "Hello world!"}
  1833. }
  1834. fields: {
  1835. key: "listValue"
  1836. value: {
  1837. list_value: {
  1838. values: {
  1839. number_value: 1234
  1840. }
  1841. values: {
  1842. string_value: "5678"
  1843. }
  1844. }
  1845. }
  1846. }
  1847. fields: {
  1848. key: "objectValue"
  1849. value: {
  1850. struct_value: {
  1851. fields: {
  1852. key: "value"
  1853. value: {
  1854. number_value: 0
  1855. }
  1856. }
  1857. }
  1858. }
  1859. }
  1860. }
  1861. )");
  1862. // Value
  1863. RunValidJsonTest(
  1864. "ValueAcceptInteger", REQUIRED,
  1865. R"({"optionalValue": 1})",
  1866. "optional_value: { number_value: 1}");
  1867. RunValidJsonTest(
  1868. "ValueAcceptFloat", REQUIRED,
  1869. R"({"optionalValue": 1.5})",
  1870. "optional_value: { number_value: 1.5}");
  1871. RunValidJsonTest(
  1872. "ValueAcceptBool", REQUIRED,
  1873. R"({"optionalValue": false})",
  1874. "optional_value: { bool_value: false}");
  1875. RunValidJsonTest(
  1876. "ValueAcceptNull", REQUIRED,
  1877. R"({"optionalValue": null})",
  1878. "optional_value: { null_value: NULL_VALUE}");
  1879. RunValidJsonTest(
  1880. "ValueAcceptString", REQUIRED,
  1881. R"({"optionalValue": "hello"})",
  1882. R"(optional_value: { string_value: "hello"})");
  1883. RunValidJsonTest(
  1884. "ValueAcceptList", REQUIRED,
  1885. R"({"optionalValue": [0, "hello"]})",
  1886. R"(
  1887. optional_value: {
  1888. list_value: {
  1889. values: {
  1890. number_value: 0
  1891. }
  1892. values: {
  1893. string_value: "hello"
  1894. }
  1895. }
  1896. }
  1897. )");
  1898. RunValidJsonTest(
  1899. "ValueAcceptObject", REQUIRED,
  1900. R"({"optionalValue": {"value": 1}})",
  1901. R"(
  1902. optional_value: {
  1903. struct_value: {
  1904. fields: {
  1905. key: "value"
  1906. value: {
  1907. number_value: 1
  1908. }
  1909. }
  1910. }
  1911. }
  1912. )");
  1913. // Any
  1914. RunValidJsonTest(
  1915. "Any", REQUIRED,
  1916. R"({
  1917. "optionalAny": {
  1918. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes",
  1919. "optionalInt32": 12345
  1920. }
  1921. })",
  1922. R"(
  1923. optional_any: {
  1924. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes] {
  1925. optional_int32: 12345
  1926. }
  1927. }
  1928. )");
  1929. RunValidJsonTest(
  1930. "AnyNested", REQUIRED,
  1931. R"({
  1932. "optionalAny": {
  1933. "@type": "type.googleapis.com/google.protobuf.Any",
  1934. "value": {
  1935. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes",
  1936. "optionalInt32": 12345
  1937. }
  1938. }
  1939. })",
  1940. R"(
  1941. optional_any: {
  1942. [type.googleapis.com/google.protobuf.Any] {
  1943. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes] {
  1944. optional_int32: 12345
  1945. }
  1946. }
  1947. }
  1948. )");
  1949. // The special "@type" tag is not required to appear first.
  1950. RunValidJsonTest(
  1951. "AnyUnorderedTypeTag", REQUIRED,
  1952. R"({
  1953. "optionalAny": {
  1954. "optionalInt32": 12345,
  1955. "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes"
  1956. }
  1957. })",
  1958. R"(
  1959. optional_any: {
  1960. [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes] {
  1961. optional_int32: 12345
  1962. }
  1963. }
  1964. )");
  1965. // Well-known types in Any.
  1966. RunValidJsonTest(
  1967. "AnyWithInt32ValueWrapper", REQUIRED,
  1968. R"({
  1969. "optionalAny": {
  1970. "@type": "type.googleapis.com/google.protobuf.Int32Value",
  1971. "value": 12345
  1972. }
  1973. })",
  1974. R"(
  1975. optional_any: {
  1976. [type.googleapis.com/google.protobuf.Int32Value] {
  1977. value: 12345
  1978. }
  1979. }
  1980. )");
  1981. RunValidJsonTest(
  1982. "AnyWithDuration", REQUIRED,
  1983. R"({
  1984. "optionalAny": {
  1985. "@type": "type.googleapis.com/google.protobuf.Duration",
  1986. "value": "1.5s"
  1987. }
  1988. })",
  1989. R"(
  1990. optional_any: {
  1991. [type.googleapis.com/google.protobuf.Duration] {
  1992. seconds: 1
  1993. nanos: 500000000
  1994. }
  1995. }
  1996. )");
  1997. RunValidJsonTest(
  1998. "AnyWithTimestamp", REQUIRED,
  1999. R"({
  2000. "optionalAny": {
  2001. "@type": "type.googleapis.com/google.protobuf.Timestamp",
  2002. "value": "1970-01-01T00:00:00Z"
  2003. }
  2004. })",
  2005. R"(
  2006. optional_any: {
  2007. [type.googleapis.com/google.protobuf.Timestamp] {
  2008. seconds: 0
  2009. nanos: 0
  2010. }
  2011. }
  2012. )");
  2013. RunValidJsonTest(
  2014. "AnyWithFieldMask", REQUIRED,
  2015. R"({
  2016. "optionalAny": {
  2017. "@type": "type.googleapis.com/google.protobuf.FieldMask",
  2018. "value": "foo,barBaz"
  2019. }
  2020. })",
  2021. R"(
  2022. optional_any: {
  2023. [type.googleapis.com/google.protobuf.FieldMask] {
  2024. paths: ["foo", "bar_baz"]
  2025. }
  2026. }
  2027. )");
  2028. RunValidJsonTest(
  2029. "AnyWithStruct", REQUIRED,
  2030. R"({
  2031. "optionalAny": {
  2032. "@type": "type.googleapis.com/google.protobuf.Struct",
  2033. "value": {
  2034. "foo": 1
  2035. }
  2036. }
  2037. })",
  2038. R"(
  2039. optional_any: {
  2040. [type.googleapis.com/google.protobuf.Struct] {
  2041. fields: {
  2042. key: "foo"
  2043. value: {
  2044. number_value: 1
  2045. }
  2046. }
  2047. }
  2048. }
  2049. )");
  2050. RunValidJsonTest(
  2051. "AnyWithValueForJsonObject", REQUIRED,
  2052. R"({
  2053. "optionalAny": {
  2054. "@type": "type.googleapis.com/google.protobuf.Value",
  2055. "value": {
  2056. "foo": 1
  2057. }
  2058. }
  2059. })",
  2060. R"(
  2061. optional_any: {
  2062. [type.googleapis.com/google.protobuf.Value] {
  2063. struct_value: {
  2064. fields: {
  2065. key: "foo"
  2066. value: {
  2067. number_value: 1
  2068. }
  2069. }
  2070. }
  2071. }
  2072. }
  2073. )");
  2074. RunValidJsonTest(
  2075. "AnyWithValueForInteger", REQUIRED,
  2076. R"({
  2077. "optionalAny": {
  2078. "@type": "type.googleapis.com/google.protobuf.Value",
  2079. "value": 1
  2080. }
  2081. })",
  2082. R"(
  2083. optional_any: {
  2084. [type.googleapis.com/google.protobuf.Value] {
  2085. number_value: 1
  2086. }
  2087. }
  2088. )");
  2089. bool ok = true;
  2090. if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt",
  2091. "These tests were listed in the failure list, but they "
  2092. "don't exist. Remove them from the failure list by "
  2093. "running:\n"
  2094. " ./update_failure_list.py " + failure_list_filename_ +
  2095. " --remove nonexistent_tests.txt")) {
  2096. ok = false;
  2097. }
  2098. if (!CheckSetEmpty(unexpected_failing_tests_, "failing_tests.txt",
  2099. "These tests failed. If they can't be fixed right now, "
  2100. "you can add them to the failure list so the overall "
  2101. "suite can succeed. Add them to the failure list by "
  2102. "running:\n"
  2103. " ./update_failure_list.py " + failure_list_filename_ +
  2104. " --add failing_tests.txt")) {
  2105. ok = false;
  2106. }
  2107. if (!CheckSetEmpty(unexpected_succeeding_tests_, "succeeding_tests.txt",
  2108. "These tests succeeded, even though they were listed in "
  2109. "the failure list. Remove them from the failure list "
  2110. "by running:\n"
  2111. " ./update_failure_list.py " + failure_list_filename_ +
  2112. " --remove succeeding_tests.txt")) {
  2113. ok = false;
  2114. }
  2115. if (verbose_) {
  2116. CheckSetEmpty(skipped_, "",
  2117. "These tests were skipped (probably because support for some "
  2118. "features is not implemented)");
  2119. }
  2120. StringAppendF(&output_,
  2121. "CONFORMANCE SUITE %s: %d successes, %d skipped, "
  2122. "%d expected failures, %d unexpected failures.\n",
  2123. ok ? "PASSED" : "FAILED", successes_, skipped_.size(),
  2124. expected_failures_, unexpected_failing_tests_.size());
  2125. StringAppendF(&output_, "\n");
  2126. output->assign(output_);
  2127. return ok;
  2128. }
  2129. } // namespace protobuf
  2130. } // namespace google