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