binary_json_conformance_suite.cc 112 KB

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