cpp_unittest.inc 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282
  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. // Author: kenton@google.com (Kenton Varda)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. //
  34. // To test the code generator, we actually use it to generate code for
  35. // google/protobuf/unittest.proto, then test that. This means that we
  36. // are actually testing the parser and other parts of the system at the same
  37. // time, and that problems in the generator may show up as compile-time errors
  38. // rather than unittest failures, which may be surprising. However, testing
  39. // the output of the C++ generator directly would be very hard. We can't very
  40. // well just check it against golden files since those files would have to be
  41. // updated for any small change; such a test would be very brittle and probably
  42. // not very helpful. What we really want to test is that the code compiles
  43. // correctly and produces the interfaces we expect, which is why this test
  44. // is written this way.
  45. #include <google/protobuf/compiler/cpp/cpp_unittest.h>
  46. #include <memory>
  47. #include <vector>
  48. #include <google/protobuf/unittest_no_arena.pb.h>
  49. #if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER)
  50. // We exclude this large proto from cmake build because it's too large for
  51. // visual studio to compile (report internal errors).
  52. #include <google/protobuf/unittest_enormous_descriptor.pb.h>
  53. #endif
  54. #include <google/protobuf/compiler/cpp/cpp_helpers.h>
  55. #include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h>
  56. #include <google/protobuf/compiler/importer.h>
  57. #include <google/protobuf/unittest_no_generic_services.pb.h>
  58. #include <google/protobuf/io/coded_stream.h>
  59. #include <google/protobuf/io/zero_copy_stream_impl.h>
  60. #include <google/protobuf/descriptor.pb.h>
  61. #include <google/protobuf/arena.h>
  62. #include <google/protobuf/descriptor.h>
  63. #include <google/protobuf/dynamic_message.h>
  64. #include <google/protobuf/stubs/callback.h>
  65. #include <google/protobuf/stubs/common.h>
  66. #include <google/protobuf/stubs/logging.h>
  67. #include <google/protobuf/stubs/substitute.h>
  68. #include <google/protobuf/testing/googletest.h>
  69. #include <gtest/gtest.h>
  70. #include <google/protobuf/stubs/stl_util.h>
  71. namespace google {
  72. namespace protobuf {
  73. namespace compiler {
  74. namespace cpp {
  75. // Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
  76. namespace cpp_unittest {
  77. class MockErrorCollector : public MultiFileErrorCollector {
  78. public:
  79. MockErrorCollector() {}
  80. ~MockErrorCollector() {}
  81. string text_;
  82. // implements ErrorCollector ---------------------------------------
  83. void AddError(const string& filename, int line, int column,
  84. const string& message) {
  85. strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
  86. filename, line, column, message);
  87. }
  88. };
  89. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  90. // Test that generated code has proper descriptors:
  91. // Parse a descriptor directly (using google::protobuf::compiler::Importer) and
  92. // compare it to the one that was produced by generated code.
  93. TEST(GENERATED_DESCRIPTOR_TEST_NAME, IdenticalDescriptors) {
  94. const FileDescriptor* generated_descriptor =
  95. UNITTEST::TestAllTypes::descriptor()->file();
  96. // Set up the Importer.
  97. MockErrorCollector error_collector;
  98. DiskSourceTree source_tree;
  99. source_tree.MapPath("", TestSourceDir());
  100. Importer importer(&source_tree, &error_collector);
  101. // Import (parse) unittest.proto.
  102. const FileDescriptor* parsed_descriptor =
  103. importer.Import(UNITTEST_PROTO_PATH);
  104. EXPECT_EQ("", error_collector.text_);
  105. ASSERT_TRUE(parsed_descriptor != NULL);
  106. // Test that descriptors are generated correctly by converting them to
  107. // FileDescriptorProtos and comparing.
  108. FileDescriptorProto generated_descriptor_proto, parsed_descriptor_proto;
  109. generated_descriptor->CopyTo(&generated_descriptor_proto);
  110. parsed_descriptor->CopyTo(&parsed_descriptor_proto);
  111. EXPECT_EQ(parsed_descriptor_proto.DebugString(),
  112. generated_descriptor_proto.DebugString());
  113. }
  114. #if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER)
  115. // Test that generated code has proper descriptors:
  116. // Touch a descriptor generated from an enormous message to validate special
  117. // handling for descriptors exceeding the C++ standard's recommended minimum
  118. // limit for string literal size
  119. TEST(GENERATED_DESCRIPTOR_TEST_NAME, EnormousDescriptor) {
  120. const Descriptor* generated_descriptor =
  121. TestEnormousDescriptor::descriptor();
  122. EXPECT_TRUE(generated_descriptor != NULL);
  123. }
  124. #endif
  125. #endif // !PROTOBUF_TEST_NO_DESCRIPTORS
  126. // ===================================================================
  127. TEST(GENERATED_MESSAGE_TEST_NAME, Defaults) {
  128. // Check that all default values are set correctly in the initial message.
  129. UNITTEST::TestAllTypes message;
  130. TestUtil::ExpectClear(message);
  131. // Messages should return pointers to default instances until first use.
  132. // (This is not checked by ExpectClear() since it is not actually true after
  133. // the fields have been set and then cleared.)
  134. EXPECT_EQ(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(),
  135. &message.optionalgroup());
  136. EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(),
  137. &message.optional_nested_message());
  138. EXPECT_EQ(&UNITTEST::ForeignMessage::default_instance(),
  139. &message.optional_foreign_message());
  140. EXPECT_EQ(&UNITTEST_IMPORT::ImportMessage::default_instance(),
  141. &message.optional_import_message());
  142. }
  143. #ifndef PROTOBUF_USE_DLLS
  144. TEST(GENERATED_MESSAGE_TEST_NAME, Int32StringConversion) {
  145. EXPECT_EQ("971", Int32ToString(971));
  146. EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min));
  147. EXPECT_EQ("2147483647", Int32ToString(kint32max));
  148. }
  149. TEST(GENERATED_MESSAGE_TEST_NAME, Int64StringConversion) {
  150. EXPECT_EQ("GOOGLE_LONGLONG(971)", Int64ToString(971));
  151. EXPECT_EQ("GOOGLE_LONGLONG(-2147483648)", Int64ToString(kint32min));
  152. EXPECT_EQ("GOOGLE_LONGLONG(~0x7fffffffffffffff)", Int64ToString(kint64min));
  153. EXPECT_EQ("GOOGLE_LONGLONG(9223372036854775807)", Int64ToString(kint64max));
  154. }
  155. #endif // !PROTOBUF_USE_DLLS
  156. TEST(GENERATED_MESSAGE_TEST_NAME, FloatingPointDefaults) {
  157. const UNITTEST::TestExtremeDefaultValues& extreme_default =
  158. UNITTEST::TestExtremeDefaultValues::default_instance();
  159. EXPECT_EQ(0.0f, extreme_default.zero_float());
  160. EXPECT_EQ(1.0f, extreme_default.one_float());
  161. EXPECT_EQ(1.5f, extreme_default.small_float());
  162. EXPECT_EQ(-1.0f, extreme_default.negative_one_float());
  163. EXPECT_EQ(-1.5f, extreme_default.negative_float());
  164. EXPECT_EQ(2.0e8f, extreme_default.large_float());
  165. EXPECT_EQ(-8e-28f, extreme_default.small_negative_float());
  166. EXPECT_EQ(std::numeric_limits<double>::infinity(),
  167. extreme_default.inf_double());
  168. EXPECT_EQ(-std::numeric_limits<double>::infinity(),
  169. extreme_default.neg_inf_double());
  170. EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double());
  171. EXPECT_EQ(std::numeric_limits<float>::infinity(),
  172. extreme_default.inf_float());
  173. EXPECT_EQ(-std::numeric_limits<float>::infinity(),
  174. extreme_default.neg_inf_float());
  175. EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float());
  176. }
  177. TEST(GENERATED_MESSAGE_TEST_NAME, Trigraph) {
  178. const UNITTEST::TestExtremeDefaultValues& extreme_default =
  179. UNITTEST::TestExtremeDefaultValues::default_instance();
  180. EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph());
  181. }
  182. TEST(GENERATED_MESSAGE_TEST_NAME, ExtremeSmallIntegerDefault) {
  183. const UNITTEST::TestExtremeDefaultValues& extreme_default =
  184. UNITTEST::TestExtremeDefaultValues::default_instance();
  185. EXPECT_EQ(~0x7fffffff, kint32min);
  186. EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min);
  187. EXPECT_EQ(kint32min, extreme_default.really_small_int32());
  188. EXPECT_EQ(kint64min, extreme_default.really_small_int64());
  189. }
  190. TEST(GENERATED_MESSAGE_TEST_NAME, Accessors) {
  191. // Set every field to a unique value then go back and check all those
  192. // values.
  193. UNITTEST::TestAllTypes message;
  194. TestUtil::SetAllFields(&message);
  195. TestUtil::ExpectAllFieldsSet(message);
  196. TestUtil::ModifyRepeatedFields(&message);
  197. TestUtil::ExpectRepeatedFieldsModified(message);
  198. }
  199. TEST(GENERATED_MESSAGE_TEST_NAME, MutableStringDefault) {
  200. // mutable_foo() for a string should return a string initialized to its
  201. // default value.
  202. UNITTEST::TestAllTypes message;
  203. EXPECT_EQ("hello", *message.mutable_default_string());
  204. // Note that the first time we call mutable_foo(), we get a newly-allocated
  205. // string, but if we clear it and call it again, we get the same object again.
  206. // We should verify that it has its default value in both cases.
  207. message.set_default_string("blah");
  208. message.Clear();
  209. EXPECT_EQ("hello", *message.mutable_default_string());
  210. }
  211. TEST(GENERATED_MESSAGE_TEST_NAME, StringDefaults) {
  212. UNITTEST::TestExtremeDefaultValues message;
  213. // Check if '\000' can be used in default string value.
  214. EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero());
  215. EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero());
  216. }
  217. TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseString) {
  218. // Check that release_foo() starts out NULL, and gives us a value
  219. // that we can delete after it's been set.
  220. UNITTEST::TestAllTypes message;
  221. EXPECT_EQ(NULL, message.release_default_string());
  222. EXPECT_FALSE(message.has_default_string());
  223. EXPECT_EQ("hello", message.default_string());
  224. message.set_default_string("blah");
  225. EXPECT_TRUE(message.has_default_string());
  226. std::unique_ptr<string> str(message.release_default_string());
  227. EXPECT_FALSE(message.has_default_string());
  228. ASSERT_TRUE(str != NULL);
  229. EXPECT_EQ("blah", *str);
  230. EXPECT_EQ(NULL, message.release_default_string());
  231. EXPECT_FALSE(message.has_default_string());
  232. EXPECT_EQ("hello", message.default_string());
  233. }
  234. TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseMessage) {
  235. // Check that release_foo() starts out NULL, and gives us a value
  236. // that we can delete after it's been set.
  237. UNITTEST::TestAllTypes message;
  238. EXPECT_EQ(NULL, message.release_optional_nested_message());
  239. EXPECT_FALSE(message.has_optional_nested_message());
  240. message.mutable_optional_nested_message()->set_bb(1);
  241. std::unique_ptr<UNITTEST::TestAllTypes::NestedMessage> nest(
  242. message.release_optional_nested_message());
  243. EXPECT_FALSE(message.has_optional_nested_message());
  244. ASSERT_TRUE(nest != NULL);
  245. EXPECT_EQ(1, nest->bb());
  246. EXPECT_EQ(NULL, message.release_optional_nested_message());
  247. EXPECT_FALSE(message.has_optional_nested_message());
  248. }
  249. TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedString) {
  250. // Check that set_allocated_foo() works for strings.
  251. UNITTEST::TestAllTypes message;
  252. EXPECT_FALSE(message.has_optional_string());
  253. const string kHello("hello");
  254. message.set_optional_string(kHello);
  255. EXPECT_TRUE(message.has_optional_string());
  256. message.set_allocated_optional_string(NULL);
  257. EXPECT_FALSE(message.has_optional_string());
  258. EXPECT_EQ("", message.optional_string());
  259. message.set_allocated_optional_string(new string(kHello));
  260. EXPECT_TRUE(message.has_optional_string());
  261. EXPECT_EQ(kHello, message.optional_string());
  262. }
  263. TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedMessage) {
  264. // Check that set_allocated_foo() can be called in all cases.
  265. UNITTEST::TestAllTypes message;
  266. EXPECT_FALSE(message.has_optional_nested_message());
  267. message.mutable_optional_nested_message()->set_bb(1);
  268. EXPECT_TRUE(message.has_optional_nested_message());
  269. message.set_allocated_optional_nested_message(NULL);
  270. EXPECT_FALSE(message.has_optional_nested_message());
  271. EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(),
  272. &message.optional_nested_message());
  273. message.mutable_optional_nested_message()->set_bb(1);
  274. UNITTEST::TestAllTypes::NestedMessage* nest =
  275. message.release_optional_nested_message();
  276. ASSERT_TRUE(nest != NULL);
  277. EXPECT_FALSE(message.has_optional_nested_message());
  278. message.set_allocated_optional_nested_message(nest);
  279. EXPECT_TRUE(message.has_optional_nested_message());
  280. EXPECT_EQ(1, message.optional_nested_message().bb());
  281. }
  282. TEST(GENERATED_MESSAGE_TEST_NAME, Clear) {
  283. // Set every field to a unique value, clear the message, then check that
  284. // it is cleared.
  285. UNITTEST::TestAllTypes message;
  286. TestUtil::SetAllFields(&message);
  287. message.Clear();
  288. TestUtil::ExpectClear(message);
  289. // Unlike with the defaults test, we do NOT expect that requesting embedded
  290. // messages will return a pointer to the default instance. Instead, they
  291. // should return the objects that were created when mutable_blah() was
  292. // called.
  293. EXPECT_NE(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(),
  294. &message.optionalgroup());
  295. EXPECT_NE(&UNITTEST::TestAllTypes::NestedMessage::default_instance(),
  296. &message.optional_nested_message());
  297. EXPECT_NE(&UNITTEST::ForeignMessage::default_instance(),
  298. &message.optional_foreign_message());
  299. EXPECT_NE(&UNITTEST_IMPORT::ImportMessage::default_instance(),
  300. &message.optional_import_message());
  301. }
  302. TEST(GENERATED_MESSAGE_TEST_NAME, EmbeddedNullsInBytesCharStar) {
  303. UNITTEST::TestAllTypes message;
  304. const char* value = "\0lalala\0\0";
  305. message.set_optional_bytes(value, 9);
  306. ASSERT_EQ(9, message.optional_bytes().size());
  307. EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9));
  308. message.add_repeated_bytes(value, 9);
  309. ASSERT_EQ(9, message.repeated_bytes(0).size());
  310. EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9));
  311. }
  312. TEST(GENERATED_MESSAGE_TEST_NAME, ClearOneField) {
  313. // Set every field to a unique value, then clear one value and insure that
  314. // only that one value is cleared.
  315. UNITTEST::TestAllTypes message;
  316. TestUtil::SetAllFields(&message);
  317. int64 original_value = message.optional_int64();
  318. // Clear the field and make sure it shows up as cleared.
  319. message.clear_optional_int64();
  320. EXPECT_FALSE(message.has_optional_int64());
  321. EXPECT_EQ(0, message.optional_int64());
  322. // Other adjacent fields should not be cleared.
  323. EXPECT_TRUE(message.has_optional_int32());
  324. EXPECT_TRUE(message.has_optional_uint32());
  325. // Make sure if we set it again, then all fields are set.
  326. message.set_optional_int64(original_value);
  327. TestUtil::ExpectAllFieldsSet(message);
  328. }
  329. TEST(GENERATED_MESSAGE_TEST_NAME, StringCharStarLength) {
  330. // Verify that we can use a char*,length to set one of the string fields.
  331. UNITTEST::TestAllTypes message;
  332. message.set_optional_string("abcdef", 3);
  333. EXPECT_EQ("abc", message.optional_string());
  334. // Verify that we can use a char*,length to add to a repeated string field.
  335. message.add_repeated_string("abcdef", 3);
  336. EXPECT_EQ(1, message.repeated_string_size());
  337. EXPECT_EQ("abc", message.repeated_string(0));
  338. // Verify that we can use a char*,length to set a repeated string field.
  339. message.set_repeated_string(0, "wxyz", 2);
  340. EXPECT_EQ("wx", message.repeated_string(0));
  341. }
  342. #if LANG_CXX11
  343. TEST(GENERATED_MESSAGE_TEST_NAME, StringMove) {
  344. // Verify that we trigger the move behavior on a scalar setter.
  345. protobuf_unittest_no_arena::TestAllTypes message;
  346. {
  347. string tmp(32, 'a');
  348. const char* old_data = tmp.data();
  349. message.set_optional_string(std::move(tmp));
  350. const char* new_data = message.optional_string().data();
  351. EXPECT_EQ(old_data, new_data);
  352. EXPECT_EQ(string(32, 'a'), message.optional_string());
  353. string tmp2(32, 'b');
  354. old_data = tmp2.data();
  355. message.set_optional_string(std::move(tmp2));
  356. new_data = message.optional_string().data();
  357. EXPECT_EQ(old_data, new_data);
  358. EXPECT_EQ(string(32, 'b'), message.optional_string());
  359. }
  360. // Verify that we trigger the move behavior on a oneof setter.
  361. {
  362. string tmp(32, 'a');
  363. const char* old_data = tmp.data();
  364. message.set_oneof_string(std::move(tmp));
  365. const char* new_data = message.oneof_string().data();
  366. EXPECT_EQ(old_data, new_data);
  367. EXPECT_EQ(string(32, 'a'), message.oneof_string());
  368. string tmp2(32, 'b');
  369. old_data = tmp2.data();
  370. message.set_oneof_string(std::move(tmp2));
  371. new_data = message.oneof_string().data();
  372. EXPECT_EQ(old_data, new_data);
  373. EXPECT_EQ(string(32, 'b'), message.oneof_string());
  374. }
  375. // Verify that we trigger the move behavior on a repeated setter.
  376. {
  377. string tmp(32, 'a');
  378. const char* old_data = tmp.data();
  379. message.add_repeated_string(std::move(tmp));
  380. const char* new_data = message.repeated_string(0).data();
  381. EXPECT_EQ(old_data, new_data);
  382. EXPECT_EQ(string(32, 'a'), message.repeated_string(0));
  383. string tmp2(32, 'b');
  384. old_data = tmp2.data();
  385. message.set_repeated_string(0, std::move(tmp2));
  386. new_data = message.repeated_string(0).data();
  387. EXPECT_EQ(old_data, new_data);
  388. EXPECT_EQ(string(32, 'b'), message.repeated_string(0));
  389. }
  390. }
  391. #endif
  392. TEST(GENERATED_MESSAGE_TEST_NAME, CopyFrom) {
  393. UNITTEST::TestAllTypes message1, message2;
  394. TestUtil::SetAllFields(&message1);
  395. message2.CopyFrom(message1);
  396. TestUtil::ExpectAllFieldsSet(message2);
  397. // Copying from self should be a no-op.
  398. message2.CopyFrom(message2);
  399. TestUtil::ExpectAllFieldsSet(message2);
  400. }
  401. TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithEmpty) {
  402. UNITTEST::TestAllTypes message1, message2;
  403. TestUtil::SetAllFields(&message1);
  404. TestUtil::ExpectAllFieldsSet(message1);
  405. TestUtil::ExpectClear(message2);
  406. message1.Swap(&message2);
  407. TestUtil::ExpectAllFieldsSet(message2);
  408. TestUtil::ExpectClear(message1);
  409. }
  410. TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithSelf) {
  411. UNITTEST::TestAllTypes message;
  412. TestUtil::SetAllFields(&message);
  413. TestUtil::ExpectAllFieldsSet(message);
  414. message.Swap(&message);
  415. TestUtil::ExpectAllFieldsSet(message);
  416. }
  417. TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithOther) {
  418. UNITTEST::TestAllTypes message1, message2;
  419. message1.set_optional_int32(123);
  420. message1.set_optional_string("abc");
  421. message1.mutable_optional_nested_message()->set_bb(1);
  422. message1.set_optional_nested_enum(UNITTEST::TestAllTypes::FOO);
  423. message1.add_repeated_int32(1);
  424. message1.add_repeated_int32(2);
  425. message1.add_repeated_string("a");
  426. message1.add_repeated_string("b");
  427. message1.add_repeated_nested_message()->set_bb(7);
  428. message1.add_repeated_nested_message()->set_bb(8);
  429. message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::FOO);
  430. message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAR);
  431. message2.set_optional_int32(456);
  432. message2.set_optional_string("def");
  433. message2.mutable_optional_nested_message()->set_bb(2);
  434. message2.set_optional_nested_enum(UNITTEST::TestAllTypes::BAR);
  435. message2.add_repeated_int32(3);
  436. message2.add_repeated_string("c");
  437. message2.add_repeated_nested_message()->set_bb(9);
  438. message2.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAZ);
  439. message1.Swap(&message2);
  440. EXPECT_EQ(456, message1.optional_int32());
  441. EXPECT_EQ("def", message1.optional_string());
  442. EXPECT_EQ(2, message1.optional_nested_message().bb());
  443. EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message1.optional_nested_enum());
  444. ASSERT_EQ(1, message1.repeated_int32_size());
  445. EXPECT_EQ(3, message1.repeated_int32(0));
  446. ASSERT_EQ(1, message1.repeated_string_size());
  447. EXPECT_EQ("c", message1.repeated_string(0));
  448. ASSERT_EQ(1, message1.repeated_nested_message_size());
  449. EXPECT_EQ(9, message1.repeated_nested_message(0).bb());
  450. ASSERT_EQ(1, message1.repeated_nested_enum_size());
  451. EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message1.repeated_nested_enum(0));
  452. EXPECT_EQ(123, message2.optional_int32());
  453. EXPECT_EQ("abc", message2.optional_string());
  454. EXPECT_EQ(1, message2.optional_nested_message().bb());
  455. EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.optional_nested_enum());
  456. ASSERT_EQ(2, message2.repeated_int32_size());
  457. EXPECT_EQ(1, message2.repeated_int32(0));
  458. EXPECT_EQ(2, message2.repeated_int32(1));
  459. ASSERT_EQ(2, message2.repeated_string_size());
  460. EXPECT_EQ("a", message2.repeated_string(0));
  461. EXPECT_EQ("b", message2.repeated_string(1));
  462. ASSERT_EQ(2, message2.repeated_nested_message_size());
  463. EXPECT_EQ(7, message2.repeated_nested_message(0).bb());
  464. EXPECT_EQ(8, message2.repeated_nested_message(1).bb());
  465. ASSERT_EQ(2, message2.repeated_nested_enum_size());
  466. EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.repeated_nested_enum(0));
  467. EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message2.repeated_nested_enum(1));
  468. }
  469. TEST(GENERATED_MESSAGE_TEST_NAME, ADLSwap) {
  470. UNITTEST::TestAllTypes message1, message2;
  471. TestUtil::SetAllFields(&message1);
  472. // Note the address of one of the repeated fields, to verify it was swapped
  473. // rather than copied.
  474. const int32* addr = &message1.repeated_int32().Get(0);
  475. using std::swap;
  476. swap(message1, message2);
  477. TestUtil::ExpectAllFieldsSet(message2);
  478. TestUtil::ExpectClear(message1);
  479. EXPECT_EQ(addr, &message2.repeated_int32().Get(0));
  480. }
  481. TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructor) {
  482. // All set.
  483. {
  484. UNITTEST::TestAllTypes message1;
  485. TestUtil::SetAllFields(&message1);
  486. UNITTEST::TestAllTypes message2(message1);
  487. TestUtil::ExpectAllFieldsSet(message2);
  488. }
  489. // None set.
  490. {
  491. UNITTEST::TestAllTypes message1;
  492. UNITTEST::TestAllTypes message2(message1);
  493. EXPECT_FALSE(message1.has_optional_string());
  494. EXPECT_FALSE(message2.has_optional_string());
  495. EXPECT_EQ(message1.optional_string(), message2.optional_string());
  496. EXPECT_FALSE(message1.has_optional_bytes());
  497. EXPECT_FALSE(message2.has_optional_bytes());
  498. EXPECT_EQ(message1.optional_bytes(), message2.optional_bytes());
  499. EXPECT_FALSE(message1.has_optional_nested_message());
  500. EXPECT_FALSE(message2.has_optional_nested_message());
  501. EXPECT_EQ(&message1.optional_nested_message(),
  502. &message2.optional_nested_message());
  503. EXPECT_FALSE(message1.has_optional_foreign_message());
  504. EXPECT_FALSE(message2.has_optional_foreign_message());
  505. EXPECT_EQ(&message1.optional_foreign_message(),
  506. &message2.optional_foreign_message());
  507. EXPECT_FALSE(message1.has_optional_import_message());
  508. EXPECT_FALSE(message2.has_optional_import_message());
  509. EXPECT_EQ(&message1.optional_import_message(),
  510. &message2.optional_import_message());
  511. EXPECT_FALSE(message1.has_optional_public_import_message());
  512. EXPECT_FALSE(message2.has_optional_public_import_message());
  513. EXPECT_EQ(&message1.optional_public_import_message(),
  514. &message2.optional_public_import_message());
  515. EXPECT_FALSE(message1.has_optional_lazy_message());
  516. EXPECT_FALSE(message2.has_optional_lazy_message());
  517. EXPECT_EQ(&message1.optional_lazy_message(),
  518. &message2.optional_lazy_message());
  519. }
  520. }
  521. TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructorWithArenas) {
  522. Arena arena;
  523. UNITTEST::TestAllTypes* message1 =
  524. Arena::CreateMessage<UNITTEST::TestAllTypes>(&arena);
  525. TestUtil::SetAllFields(message1);
  526. UNITTEST::TestAllTypes message2_stack(*message1);
  527. TestUtil::ExpectAllFieldsSet(message2_stack);
  528. std::unique_ptr<UNITTEST::TestAllTypes> message2_heap(
  529. new UNITTEST::TestAllTypes(*message1));
  530. TestUtil::ExpectAllFieldsSet(*message2_heap);
  531. arena.Reset();
  532. // Verify that the copies are still intact.
  533. TestUtil::ExpectAllFieldsSet(message2_stack);
  534. TestUtil::ExpectAllFieldsSet(*message2_heap);
  535. }
  536. TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) {
  537. UNITTEST::TestAllTypes message1;
  538. TestUtil::SetAllFields(&message1);
  539. UNITTEST::TestAllTypes message2;
  540. message2 = message1;
  541. TestUtil::ExpectAllFieldsSet(message2);
  542. // Make sure that self-assignment does something sane.
  543. message2.operator=(message2);
  544. TestUtil::ExpectAllFieldsSet(message2);
  545. }
  546. #if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
  547. !defined(GOOGLE_PROTOBUF_NO_RTTI)
  548. TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) {
  549. // Test the CopyFrom method that takes in the generic const Message&
  550. // parameter.
  551. UNITTEST::TestAllTypes message1, message2;
  552. TestUtil::SetAllFields(&message1);
  553. const Message* source = implicit_cast<const Message*>(&message1);
  554. message2.CopyFrom(*source);
  555. TestUtil::ExpectAllFieldsSet(message2);
  556. }
  557. #endif
  558. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  559. TEST(GENERATED_MESSAGE_TEST_NAME, DynamicMessageCopyFrom) {
  560. // Test copying from a DynamicMessage, which must fall back to using
  561. // reflection.
  562. UNITTEST::TestAllTypes message2;
  563. // Construct a new version of the dynamic message via the factory.
  564. DynamicMessageFactory factory;
  565. std::unique_ptr<Message> message1;
  566. message1.reset(factory.GetPrototype(
  567. UNITTEST::TestAllTypes::descriptor())->New());
  568. TestUtil::ReflectionTester reflection_tester(
  569. UNITTEST::TestAllTypes::descriptor());
  570. reflection_tester.SetAllFieldsViaReflection(message1.get());
  571. message2.CopyFrom(*message1);
  572. TestUtil::ExpectAllFieldsSet(message2);
  573. }
  574. #endif // !PROTOBUF_TEST_NO_DESCRIPTORS
  575. TEST(GENERATED_MESSAGE_TEST_NAME, NonEmptyMergeFrom) {
  576. // Test merging with a non-empty message. Code is a modified form
  577. // of that found in google/protobuf/reflection_ops_unittest.cc.
  578. UNITTEST::TestAllTypes message1, message2;
  579. TestUtil::SetAllFields(&message1);
  580. // This field will test merging into an empty spot.
  581. message2.set_optional_int32(message1.optional_int32());
  582. message1.clear_optional_int32();
  583. // This tests overwriting.
  584. message2.set_optional_string(message1.optional_string());
  585. message1.set_optional_string("something else");
  586. // This tests concatenating.
  587. message2.add_repeated_int32(message1.repeated_int32(1));
  588. int32 i = message1.repeated_int32(0);
  589. message1.clear_repeated_int32();
  590. message1.add_repeated_int32(i);
  591. message1.MergeFrom(message2);
  592. TestUtil::ExpectAllFieldsSet(message1);
  593. }
  594. // Test the generated SerializeWithCachedSizesToArray(),
  595. TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) {
  596. UNITTEST::TestAllTypes message1, message2;
  597. string data;
  598. TestUtil::SetAllFields(&message1);
  599. int size = message1.ByteSizeLong();
  600. data.resize(size);
  601. uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
  602. uint8* end = message1.SerializeWithCachedSizesToArray(start);
  603. EXPECT_EQ(size, end - start);
  604. EXPECT_TRUE(message2.ParseFromString(data));
  605. TestUtil::ExpectAllFieldsSet(message2);
  606. }
  607. TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToArray) {
  608. UNITTEST::TestPackedTypes packed_message1, packed_message2;
  609. string packed_data;
  610. TestUtil::SetPackedFields(&packed_message1);
  611. int packed_size = packed_message1.ByteSizeLong();
  612. packed_data.resize(packed_size);
  613. uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data));
  614. uint8* end = packed_message1.SerializeWithCachedSizesToArray(start);
  615. EXPECT_EQ(packed_size, end - start);
  616. EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
  617. TestUtil::ExpectPackedFieldsSet(packed_message2);
  618. }
  619. // Test the generated SerializeWithCachedSizes() by forcing the buffer to write
  620. // one byte at a time.
  621. TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToStream) {
  622. UNITTEST::TestAllTypes message1, message2;
  623. TestUtil::SetAllFields(&message1);
  624. int size = message1.ByteSizeLong();
  625. string data;
  626. data.resize(size);
  627. {
  628. // Allow the output stream to buffer only one byte at a time.
  629. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  630. io::CodedOutputStream output_stream(&array_stream);
  631. message1.SerializeWithCachedSizes(&output_stream);
  632. EXPECT_FALSE(output_stream.HadError());
  633. EXPECT_EQ(size, output_stream.ByteCount());
  634. }
  635. EXPECT_TRUE(message2.ParseFromString(data));
  636. TestUtil::ExpectAllFieldsSet(message2);
  637. }
  638. TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToStream) {
  639. UNITTEST::TestPackedTypes message1, message2;
  640. TestUtil::SetPackedFields(&message1);
  641. int size = message1.ByteSizeLong();
  642. string data;
  643. data.resize(size);
  644. {
  645. // Allow the output stream to buffer only one byte at a time.
  646. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  647. io::CodedOutputStream output_stream(&array_stream);
  648. message1.SerializeWithCachedSizes(&output_stream);
  649. EXPECT_FALSE(output_stream.HadError());
  650. EXPECT_EQ(size, output_stream.ByteCount());
  651. }
  652. EXPECT_TRUE(message2.ParseFromString(data));
  653. TestUtil::ExpectPackedFieldsSet(message2);
  654. }
  655. TEST(GENERATED_MESSAGE_TEST_NAME, Required) {
  656. // Test that IsInitialized() returns false if required fields are missing.
  657. UNITTEST::TestRequired message;
  658. EXPECT_FALSE(message.IsInitialized());
  659. message.set_a(1);
  660. EXPECT_FALSE(message.IsInitialized());
  661. message.set_b(2);
  662. EXPECT_FALSE(message.IsInitialized());
  663. message.set_c(3);
  664. EXPECT_TRUE(message.IsInitialized());
  665. }
  666. TEST(GENERATED_MESSAGE_TEST_NAME, RequiredForeign) {
  667. // Test that IsInitialized() returns false if required fields in nested
  668. // messages are missing.
  669. UNITTEST::TestRequiredForeign message;
  670. EXPECT_TRUE(message.IsInitialized());
  671. message.mutable_optional_message();
  672. EXPECT_FALSE(message.IsInitialized());
  673. message.mutable_optional_message()->set_a(1);
  674. message.mutable_optional_message()->set_b(2);
  675. message.mutable_optional_message()->set_c(3);
  676. EXPECT_TRUE(message.IsInitialized());
  677. message.add_repeated_message();
  678. EXPECT_FALSE(message.IsInitialized());
  679. message.mutable_repeated_message(0)->set_a(1);
  680. message.mutable_repeated_message(0)->set_b(2);
  681. message.mutable_repeated_message(0)->set_c(3);
  682. EXPECT_TRUE(message.IsInitialized());
  683. }
  684. TEST(GENERATED_MESSAGE_TEST_NAME, ForeignNested) {
  685. // Test that TestAllTypes::NestedMessage can be embedded directly into
  686. // another message.
  687. UNITTEST::TestForeignNested message;
  688. // If this compiles and runs without crashing, it must work. We have
  689. // nothing more to test.
  690. UNITTEST::TestAllTypes::NestedMessage* nested =
  691. message.mutable_foreign_nested();
  692. nested->set_bb(1);
  693. }
  694. TEST(GENERATED_MESSAGE_TEST_NAME, ReallyLargeTagNumber) {
  695. // Test that really large tag numbers don't break anything.
  696. UNITTEST::TestReallyLargeTagNumber message1, message2;
  697. string data;
  698. // For the most part, if this compiles and runs then we're probably good.
  699. // (The most likely cause for failure would be if something were attempting
  700. // to allocate a lookup table of some sort using tag numbers as the index.)
  701. // We'll try serializing just for fun.
  702. message1.set_a(1234);
  703. message1.set_bb(5678);
  704. message1.SerializeToString(&data);
  705. EXPECT_TRUE(message2.ParseFromString(data));
  706. EXPECT_EQ(1234, message2.a());
  707. EXPECT_EQ(5678, message2.bb());
  708. }
  709. TEST(GENERATED_MESSAGE_TEST_NAME, MutualRecursion) {
  710. // Test that mutually-recursive message types work.
  711. UNITTEST::TestMutualRecursionA message;
  712. UNITTEST::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a();
  713. UNITTEST::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a();
  714. // Again, if the above compiles and runs, that's all we really have to
  715. // test, but just for run we'll check that the system didn't somehow come
  716. // up with a pointer loop...
  717. EXPECT_NE(&message, nested);
  718. EXPECT_NE(&message, nested2);
  719. EXPECT_NE(nested, nested2);
  720. }
  721. TEST(GENERATED_MESSAGE_TEST_NAME, CamelCaseFieldNames) {
  722. // This test is mainly checking that the following compiles, which verifies
  723. // that the field names were coerced to lower-case.
  724. //
  725. // Protocol buffers standard style is to use lowercase-with-underscores for
  726. // field names. Some old proto1 .protos unfortunately used camel-case field
  727. // names. In proto1, these names were forced to lower-case. So, we do the
  728. // same thing in proto2.
  729. UNITTEST::TestCamelCaseFieldNames message;
  730. message.set_primitivefield(2);
  731. message.set_stringfield("foo");
  732. message.set_enumfield(UNITTEST::FOREIGN_FOO);
  733. message.mutable_messagefield()->set_c(6);
  734. message.add_repeatedprimitivefield(8);
  735. message.add_repeatedstringfield("qux");
  736. message.add_repeatedenumfield(UNITTEST::FOREIGN_BAR);
  737. message.add_repeatedmessagefield()->set_c(15);
  738. EXPECT_EQ(2, message.primitivefield());
  739. EXPECT_EQ("foo", message.stringfield());
  740. EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.enumfield());
  741. EXPECT_EQ(6, message.messagefield().c());
  742. EXPECT_EQ(8, message.repeatedprimitivefield(0));
  743. EXPECT_EQ("qux", message.repeatedstringfield(0));
  744. EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeatedenumfield(0));
  745. EXPECT_EQ(15, message.repeatedmessagefield(0).c());
  746. }
  747. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  748. TEST(GENERATED_MESSAGE_TEST_NAME, TestOptimizedForSize) {
  749. // We rely on the tests in reflection_ops_unittest and wire_format_unittest
  750. // to really test that reflection-based methods work. Here we are mostly
  751. // just making sure that TestOptimizedForSize actually builds and seems to
  752. // function.
  753. UNITTEST::TestOptimizedForSize message, message2;
  754. message.set_i(1);
  755. message.mutable_msg()->set_c(2);
  756. message2.CopyFrom(message);
  757. EXPECT_EQ(1, message2.i());
  758. EXPECT_EQ(2, message2.msg().c());
  759. }
  760. TEST(GENERATED_MESSAGE_TEST_NAME, TestEmbedOptimizedForSize) {
  761. // Verifies that something optimized for speed can contain something optimized
  762. // for size.
  763. UNITTEST::TestEmbedOptimizedForSize message, message2;
  764. message.mutable_optional_message()->set_i(1);
  765. message.add_repeated_message()->mutable_msg()->set_c(2);
  766. string data;
  767. message.SerializeToString(&data);
  768. ASSERT_TRUE(message2.ParseFromString(data));
  769. EXPECT_EQ(1, message2.optional_message().i());
  770. EXPECT_EQ(2, message2.repeated_message(0).msg().c());
  771. }
  772. TEST(GENERATED_MESSAGE_TEST_NAME, TestSpaceUsed) {
  773. UNITTEST::TestAllTypes message1;
  774. // sizeof provides a lower bound on SpaceUsedLong().
  775. EXPECT_LE(sizeof(UNITTEST::TestAllTypes), message1.SpaceUsedLong());
  776. const size_t empty_message_size = message1.SpaceUsedLong();
  777. // Setting primitive types shouldn't affect the space used.
  778. message1.set_optional_int32(123);
  779. message1.set_optional_int64(12345);
  780. message1.set_optional_uint32(123);
  781. message1.set_optional_uint64(12345);
  782. EXPECT_EQ(empty_message_size, message1.SpaceUsedLong());
  783. // On some STL implementations, setting the string to a small value should
  784. // only increase SpaceUsedLong() by the size of a string object, though this
  785. // is not true everywhere.
  786. message1.set_optional_string("abc");
  787. EXPECT_LE(empty_message_size + message1.optional_string().size(),
  788. message1.SpaceUsedLong());
  789. // Setting a string to a value larger than the string object itself should
  790. // increase SpaceUsedLong(), because it cannot store the value internally.
  791. message1.set_optional_string(string(sizeof(string) + 1, 'x'));
  792. int min_expected_increase = message1.optional_string().capacity();
  793. EXPECT_LE(empty_message_size + min_expected_increase,
  794. message1.SpaceUsedLong());
  795. size_t previous_size = message1.SpaceUsedLong();
  796. // Adding an optional message should increase the size by the size of the
  797. // nested message type. NestedMessage is simple enough (1 int field) that it
  798. // is equal to sizeof(NestedMessage)
  799. message1.mutable_optional_nested_message();
  800. ASSERT_EQ(sizeof(UNITTEST::TestAllTypes::NestedMessage),
  801. message1.optional_nested_message().SpaceUsedLong());
  802. EXPECT_EQ(previous_size +
  803. sizeof(UNITTEST::TestAllTypes::NestedMessage),
  804. message1.SpaceUsedLong());
  805. }
  806. TEST(GENERATED_MESSAGE_TEST_NAME, TestOneofSpaceUsed) {
  807. UNITTEST::TestOneof2 message1;
  808. EXPECT_LE(sizeof(UNITTEST::TestOneof2), message1.SpaceUsedLong());
  809. const size_t empty_message_size = message1.SpaceUsedLong();
  810. // Setting primitive types shouldn't affect the space used.
  811. message1.set_foo_int(123);
  812. message1.set_bar_int(12345);
  813. EXPECT_EQ(empty_message_size, message1.SpaceUsedLong());
  814. // Setting a string in oneof to a small value should only increase
  815. // SpaceUsedLong() by the size of a string object.
  816. message1.set_foo_string("abc");
  817. EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong());
  818. // Setting a string in oneof to a value larger than the string object itself
  819. // should increase SpaceUsedLong(), because it cannot store the value
  820. // internally.
  821. message1.set_foo_string(string(sizeof(string) + 1, 'x'));
  822. int min_expected_increase = message1.foo_string().capacity() +
  823. sizeof(string);
  824. EXPECT_LE(empty_message_size + min_expected_increase,
  825. message1.SpaceUsedLong());
  826. // Setting a message in oneof should delete the other fields and increase the
  827. // size by the size of the nested message type. NestedMessage is simple enough
  828. // that it is equal to sizeof(NestedMessage)
  829. message1.mutable_foo_message();
  830. ASSERT_EQ(sizeof(UNITTEST::TestOneof2::NestedMessage),
  831. message1.foo_message().SpaceUsedLong());
  832. EXPECT_EQ(empty_message_size +
  833. sizeof(UNITTEST::TestOneof2::NestedMessage),
  834. message1.SpaceUsedLong());
  835. }
  836. #endif // !PROTOBUF_TEST_NO_DESCRIPTORS
  837. TEST(GENERATED_MESSAGE_TEST_NAME, FieldConstantValues) {
  838. UNITTEST::TestRequired message;
  839. EXPECT_EQ(UNITTEST::TestAllTypes_NestedMessage::kBbFieldNumber, 1);
  840. EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalInt32FieldNumber, 1);
  841. EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalgroupFieldNumber, 16);
  842. EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedMessageFieldNumber, 18);
  843. EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedEnumFieldNumber, 21);
  844. EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedInt32FieldNumber, 31);
  845. EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedgroupFieldNumber, 46);
  846. EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48);
  847. EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51);
  848. }
  849. TEST(GENERATED_MESSAGE_TEST_NAME, ExtensionConstantValues) {
  850. EXPECT_EQ(UNITTEST::TestRequired::kSingleFieldNumber, 1000);
  851. EXPECT_EQ(UNITTEST::TestRequired::kMultiFieldNumber, 1001);
  852. EXPECT_EQ(UNITTEST::kOptionalInt32ExtensionFieldNumber, 1);
  853. EXPECT_EQ(UNITTEST::kOptionalgroupExtensionFieldNumber, 16);
  854. EXPECT_EQ(UNITTEST::kOptionalNestedMessageExtensionFieldNumber, 18);
  855. EXPECT_EQ(UNITTEST::kOptionalNestedEnumExtensionFieldNumber, 21);
  856. EXPECT_EQ(UNITTEST::kRepeatedInt32ExtensionFieldNumber, 31);
  857. EXPECT_EQ(UNITTEST::kRepeatedgroupExtensionFieldNumber, 46);
  858. EXPECT_EQ(UNITTEST::kRepeatedNestedMessageExtensionFieldNumber, 48);
  859. EXPECT_EQ(UNITTEST::kRepeatedNestedEnumExtensionFieldNumber, 51);
  860. }
  861. TEST(GENERATED_MESSAGE_TEST_NAME, ParseFromTruncated) {
  862. const string long_string = string(128, 'q');
  863. FileDescriptorProto p;
  864. p.add_extension()->set_name(long_string);
  865. const string msg = p.SerializeAsString();
  866. int successful_count = 0;
  867. for (int i = 0; i <= msg.size(); i++) {
  868. if (p.ParseFromArray(msg.c_str(), i)) {
  869. ++successful_count;
  870. }
  871. }
  872. // We don't really care about how often we succeeded.
  873. // As long as we didn't crash, we're happy.
  874. EXPECT_GE(successful_count, 1);
  875. }
  876. // ===================================================================
  877. TEST(GENERATED_ENUM_TEST_NAME, EnumValuesAsSwitchCases) {
  878. // Test that our nested enum values can be used as switch cases. This test
  879. // doesn't actually do anything, the proof that it works is that it
  880. // compiles.
  881. int i =0;
  882. UNITTEST::TestAllTypes::NestedEnum a = UNITTEST::TestAllTypes::BAR;
  883. switch (a) {
  884. case UNITTEST::TestAllTypes::FOO:
  885. i = 1;
  886. break;
  887. case UNITTEST::TestAllTypes::BAR:
  888. i = 2;
  889. break;
  890. case UNITTEST::TestAllTypes::BAZ:
  891. i = 3;
  892. break;
  893. case UNITTEST::TestAllTypes::NEG:
  894. i = -1;
  895. break;
  896. // no default case: We want to make sure the compiler recognizes that
  897. // all cases are covered. (GCC warns if you do not cover all cases of
  898. // an enum in a switch.)
  899. }
  900. // Token check just for fun.
  901. EXPECT_EQ(2, i);
  902. }
  903. TEST(GENERATED_ENUM_TEST_NAME, IsValidValue) {
  904. // Test enum IsValidValue.
  905. EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(1));
  906. EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(2));
  907. EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(3));
  908. EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(0));
  909. EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(4));
  910. // Make sure it also works when there are dups.
  911. EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(1));
  912. EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(2));
  913. EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(3));
  914. EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(0));
  915. EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(4));
  916. }
  917. TEST(GENERATED_ENUM_TEST_NAME, MinAndMax) {
  918. EXPECT_EQ(UNITTEST::TestAllTypes::NEG,
  919. UNITTEST::TestAllTypes::NestedEnum_MIN);
  920. EXPECT_EQ(UNITTEST::TestAllTypes::BAZ,
  921. UNITTEST::TestAllTypes::NestedEnum_MAX);
  922. EXPECT_EQ(4, UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE);
  923. EXPECT_EQ(UNITTEST::FOREIGN_FOO, UNITTEST::ForeignEnum_MIN);
  924. EXPECT_EQ(UNITTEST::FOREIGN_BAZ, UNITTEST::ForeignEnum_MAX);
  925. EXPECT_EQ(7, UNITTEST::ForeignEnum_ARRAYSIZE);
  926. EXPECT_EQ(1, UNITTEST::TestEnumWithDupValue_MIN);
  927. EXPECT_EQ(3, UNITTEST::TestEnumWithDupValue_MAX);
  928. EXPECT_EQ(4, UNITTEST::TestEnumWithDupValue_ARRAYSIZE);
  929. EXPECT_EQ(UNITTEST::SPARSE_E, UNITTEST::TestSparseEnum_MIN);
  930. EXPECT_EQ(UNITTEST::SPARSE_C, UNITTEST::TestSparseEnum_MAX);
  931. EXPECT_EQ(12589235, UNITTEST::TestSparseEnum_ARRAYSIZE);
  932. // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE.
  933. void* null_pointer = 0; // NULL may be integer-type, not pointer-type.
  934. EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MIN);
  935. EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MAX);
  936. EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE);
  937. EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MIN);
  938. EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MAX);
  939. EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_ARRAYSIZE);
  940. // Make sure we can use _MIN and _MAX as switch cases.
  941. switch (UNITTEST::SPARSE_A) {
  942. case UNITTEST::TestSparseEnum_MIN:
  943. case UNITTEST::TestSparseEnum_MAX:
  944. break;
  945. default:
  946. break;
  947. }
  948. }
  949. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  950. TEST(GENERATED_ENUM_TEST_NAME, Name) {
  951. // "Names" in the presence of dup values are a bit arbitrary.
  952. EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO1));
  953. EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO2));
  954. EXPECT_EQ("SPARSE_A", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_A));
  955. EXPECT_EQ("SPARSE_B", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_B));
  956. EXPECT_EQ("SPARSE_C", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_C));
  957. EXPECT_EQ("SPARSE_D", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_D));
  958. EXPECT_EQ("SPARSE_E", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_E));
  959. EXPECT_EQ("SPARSE_F", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_F));
  960. EXPECT_EQ("SPARSE_G", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_G));
  961. }
  962. TEST(GENERATED_ENUM_TEST_NAME, Parse) {
  963. UNITTEST::TestEnumWithDupValue dup_value = UNITTEST::FOO1;
  964. EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO1", &dup_value));
  965. EXPECT_EQ(UNITTEST::FOO1, dup_value);
  966. EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO2", &dup_value));
  967. EXPECT_EQ(UNITTEST::FOO2, dup_value);
  968. EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_Parse("FOO", &dup_value));
  969. }
  970. TEST(GENERATED_ENUM_TEST_NAME, GetEnumDescriptor) {
  971. EXPECT_EQ(UNITTEST::TestAllTypes::NestedEnum_descriptor(),
  972. GetEnumDescriptor<UNITTEST::TestAllTypes::NestedEnum>());
  973. EXPECT_EQ(UNITTEST::ForeignEnum_descriptor(),
  974. GetEnumDescriptor<UNITTEST::ForeignEnum>());
  975. EXPECT_EQ(UNITTEST::TestEnumWithDupValue_descriptor(),
  976. GetEnumDescriptor<UNITTEST::TestEnumWithDupValue>());
  977. EXPECT_EQ(UNITTEST::TestSparseEnum_descriptor(),
  978. GetEnumDescriptor<UNITTEST::TestSparseEnum>());
  979. }
  980. enum NonProtoEnum {
  981. kFoo = 1,
  982. };
  983. TEST(GENERATED_ENUM_TEST_NAME, IsProtoEnumTypeTrait) {
  984. EXPECT_TRUE(is_proto_enum<UNITTEST::TestAllTypes::NestedEnum>::value);
  985. EXPECT_TRUE(is_proto_enum<UNITTEST::ForeignEnum>::value);
  986. EXPECT_TRUE(is_proto_enum<UNITTEST::TestEnumWithDupValue>::value);
  987. EXPECT_TRUE(is_proto_enum<UNITTEST::TestSparseEnum>::value);
  988. EXPECT_FALSE(is_proto_enum<int>::value);
  989. EXPECT_FALSE(is_proto_enum<NonProtoEnum>::value);
  990. }
  991. #endif // PROTOBUF_TEST_NO_DESCRIPTORS
  992. // ===================================================================
  993. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  994. // Support code for testing services.
  995. class GENERATED_SERVICE_TEST_NAME : public testing::Test {
  996. protected:
  997. class MockTestService : public UNITTEST::TestService {
  998. public:
  999. MockTestService()
  1000. : called_(false),
  1001. method_(""),
  1002. controller_(NULL),
  1003. request_(NULL),
  1004. response_(NULL),
  1005. done_(NULL) {}
  1006. ~MockTestService() {}
  1007. void Reset() { called_ = false; }
  1008. // implements TestService ----------------------------------------
  1009. void Foo(RpcController* controller,
  1010. const UNITTEST::FooRequest* request,
  1011. UNITTEST::FooResponse* response,
  1012. Closure* done) {
  1013. ASSERT_FALSE(called_);
  1014. called_ = true;
  1015. method_ = "Foo";
  1016. controller_ = controller;
  1017. request_ = request;
  1018. response_ = response;
  1019. done_ = done;
  1020. }
  1021. void Bar(RpcController* controller,
  1022. const UNITTEST::BarRequest* request,
  1023. UNITTEST::BarResponse* response,
  1024. Closure* done) {
  1025. ASSERT_FALSE(called_);
  1026. called_ = true;
  1027. method_ = "Bar";
  1028. controller_ = controller;
  1029. request_ = request;
  1030. response_ = response;
  1031. done_ = done;
  1032. }
  1033. // ---------------------------------------------------------------
  1034. bool called_;
  1035. string method_;
  1036. RpcController* controller_;
  1037. const Message* request_;
  1038. Message* response_;
  1039. Closure* done_;
  1040. };
  1041. class MockRpcChannel : public RpcChannel {
  1042. public:
  1043. MockRpcChannel()
  1044. : called_(false),
  1045. method_(NULL),
  1046. controller_(NULL),
  1047. request_(NULL),
  1048. response_(NULL),
  1049. done_(NULL),
  1050. destroyed_(NULL) {}
  1051. ~MockRpcChannel() {
  1052. if (destroyed_ != NULL) *destroyed_ = true;
  1053. }
  1054. void Reset() { called_ = false; }
  1055. // implements TestService ----------------------------------------
  1056. void CallMethod(const MethodDescriptor* method,
  1057. RpcController* controller,
  1058. const Message* request,
  1059. Message* response,
  1060. Closure* done) {
  1061. ASSERT_FALSE(called_);
  1062. called_ = true;
  1063. method_ = method;
  1064. controller_ = controller;
  1065. request_ = request;
  1066. response_ = response;
  1067. done_ = done;
  1068. }
  1069. // ---------------------------------------------------------------
  1070. bool called_;
  1071. const MethodDescriptor* method_;
  1072. RpcController* controller_;
  1073. const Message* request_;
  1074. Message* response_;
  1075. Closure* done_;
  1076. bool* destroyed_;
  1077. };
  1078. class MockController : public RpcController {
  1079. public:
  1080. void Reset() {
  1081. ADD_FAILURE() << "Reset() not expected during this test.";
  1082. }
  1083. bool Failed() const {
  1084. ADD_FAILURE() << "Failed() not expected during this test.";
  1085. return false;
  1086. }
  1087. string ErrorText() const {
  1088. ADD_FAILURE() << "ErrorText() not expected during this test.";
  1089. return "";
  1090. }
  1091. void StartCancel() {
  1092. ADD_FAILURE() << "StartCancel() not expected during this test.";
  1093. }
  1094. void SetFailed(const string& reason) {
  1095. ADD_FAILURE() << "SetFailed() not expected during this test.";
  1096. }
  1097. bool IsCanceled() const {
  1098. ADD_FAILURE() << "IsCanceled() not expected during this test.";
  1099. return false;
  1100. }
  1101. void NotifyOnCancel(Closure* callback) {
  1102. ADD_FAILURE() << "NotifyOnCancel() not expected during this test.";
  1103. }
  1104. };
  1105. GENERATED_SERVICE_TEST_NAME()
  1106. : descriptor_(UNITTEST::TestService::descriptor()),
  1107. foo_(descriptor_->FindMethodByName("Foo")),
  1108. bar_(descriptor_->FindMethodByName("Bar")),
  1109. stub_(&mock_channel_),
  1110. done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {}
  1111. virtual void SetUp() {
  1112. ASSERT_TRUE(foo_ != NULL);
  1113. ASSERT_TRUE(bar_ != NULL);
  1114. }
  1115. const ServiceDescriptor* descriptor_;
  1116. const MethodDescriptor* foo_;
  1117. const MethodDescriptor* bar_;
  1118. MockTestService mock_service_;
  1119. MockController mock_controller_;
  1120. MockRpcChannel mock_channel_;
  1121. UNITTEST::TestService::Stub stub_;
  1122. // Just so we don't have to re-define these with every test.
  1123. UNITTEST::FooRequest foo_request_;
  1124. UNITTEST::FooResponse foo_response_;
  1125. UNITTEST::BarRequest bar_request_;
  1126. UNITTEST::BarResponse bar_response_;
  1127. std::unique_ptr<Closure> done_;
  1128. };
  1129. TEST_F(GENERATED_SERVICE_TEST_NAME, GetDescriptor) {
  1130. // Test that GetDescriptor() works.
  1131. EXPECT_EQ(descriptor_, mock_service_.GetDescriptor());
  1132. }
  1133. TEST_F(GENERATED_SERVICE_TEST_NAME, GetChannel) {
  1134. EXPECT_EQ(&mock_channel_, stub_.channel());
  1135. }
  1136. TEST_F(GENERATED_SERVICE_TEST_NAME, OwnsChannel) {
  1137. MockRpcChannel* channel = new MockRpcChannel;
  1138. bool destroyed = false;
  1139. channel->destroyed_ = &destroyed;
  1140. {
  1141. UNITTEST::TestService::Stub owning_stub(channel,
  1142. Service::STUB_OWNS_CHANNEL);
  1143. EXPECT_FALSE(destroyed);
  1144. }
  1145. EXPECT_TRUE(destroyed);
  1146. }
  1147. TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethod) {
  1148. // Test that CallMethod() works.
  1149. // Call Foo() via CallMethod().
  1150. mock_service_.CallMethod(foo_, &mock_controller_,
  1151. &foo_request_, &foo_response_, done_.get());
  1152. ASSERT_TRUE(mock_service_.called_);
  1153. EXPECT_EQ("Foo" , mock_service_.method_ );
  1154. EXPECT_EQ(&mock_controller_, mock_service_.controller_);
  1155. EXPECT_EQ(&foo_request_ , mock_service_.request_ );
  1156. EXPECT_EQ(&foo_response_ , mock_service_.response_ );
  1157. EXPECT_EQ(done_.get() , mock_service_.done_ );
  1158. // Try again, but call Bar() instead.
  1159. mock_service_.Reset();
  1160. mock_service_.CallMethod(bar_, &mock_controller_,
  1161. &bar_request_, &bar_response_, done_.get());
  1162. ASSERT_TRUE(mock_service_.called_);
  1163. EXPECT_EQ("Bar", mock_service_.method_);
  1164. }
  1165. TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethodTypeFailure) {
  1166. // Verify death if we call Foo() with Bar's message types.
  1167. #ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet
  1168. EXPECT_DEBUG_DEATH(
  1169. mock_service_.CallMethod(foo_, &mock_controller_,
  1170. &foo_request_, &bar_response_, done_.get()),
  1171. "dynamic_cast");
  1172. mock_service_.Reset();
  1173. EXPECT_DEBUG_DEATH(
  1174. mock_service_.CallMethod(foo_, &mock_controller_,
  1175. &bar_request_, &foo_response_, done_.get()),
  1176. "dynamic_cast");
  1177. #endif // PROTOBUF_HAS_DEATH_TEST
  1178. }
  1179. TEST_F(GENERATED_SERVICE_TEST_NAME, GetPrototypes) {
  1180. // Test Get{Request,Response}Prototype() methods.
  1181. EXPECT_EQ(&UNITTEST::FooRequest::default_instance(),
  1182. &mock_service_.GetRequestPrototype(foo_));
  1183. EXPECT_EQ(&UNITTEST::BarRequest::default_instance(),
  1184. &mock_service_.GetRequestPrototype(bar_));
  1185. EXPECT_EQ(&UNITTEST::FooResponse::default_instance(),
  1186. &mock_service_.GetResponsePrototype(foo_));
  1187. EXPECT_EQ(&UNITTEST::BarResponse::default_instance(),
  1188. &mock_service_.GetResponsePrototype(bar_));
  1189. }
  1190. TEST_F(GENERATED_SERVICE_TEST_NAME, Stub) {
  1191. // Test that the stub class works.
  1192. // Call Foo() via the stub.
  1193. stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get());
  1194. ASSERT_TRUE(mock_channel_.called_);
  1195. EXPECT_EQ(foo_ , mock_channel_.method_ );
  1196. EXPECT_EQ(&mock_controller_, mock_channel_.controller_);
  1197. EXPECT_EQ(&foo_request_ , mock_channel_.request_ );
  1198. EXPECT_EQ(&foo_response_ , mock_channel_.response_ );
  1199. EXPECT_EQ(done_.get() , mock_channel_.done_ );
  1200. // Call Bar() via the stub.
  1201. mock_channel_.Reset();
  1202. stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get());
  1203. ASSERT_TRUE(mock_channel_.called_);
  1204. EXPECT_EQ(bar_, mock_channel_.method_);
  1205. }
  1206. TEST_F(GENERATED_SERVICE_TEST_NAME, NotImplemented) {
  1207. // Test that failing to implement a method of a service causes it to fail
  1208. // with a "not implemented" error message.
  1209. // A service which doesn't implement any methods.
  1210. class UnimplementedService : public UNITTEST::TestService {
  1211. public:
  1212. UnimplementedService() {}
  1213. };
  1214. UnimplementedService unimplemented_service;
  1215. // And a controller which expects to get a "not implemented" error.
  1216. class ExpectUnimplementedController : public MockController {
  1217. public:
  1218. ExpectUnimplementedController() : called_(false) {}
  1219. void SetFailed(const string& reason) {
  1220. EXPECT_FALSE(called_);
  1221. called_ = true;
  1222. EXPECT_EQ("Method Foo() not implemented.", reason);
  1223. }
  1224. bool called_;
  1225. };
  1226. ExpectUnimplementedController controller;
  1227. // Call Foo.
  1228. unimplemented_service.Foo(&controller, &foo_request_, &foo_response_,
  1229. done_.get());
  1230. EXPECT_TRUE(controller.called_);
  1231. }
  1232. // ===================================================================
  1233. class OneofTest : public testing::Test {
  1234. protected:
  1235. virtual void SetUp() {
  1236. }
  1237. void ExpectEnumCasesWork(const UNITTEST::TestOneof2 &message) {
  1238. switch (message.foo_case()) {
  1239. case UNITTEST::TestOneof2::kFooInt:
  1240. EXPECT_TRUE(message.has_foo_int());
  1241. break;
  1242. case UNITTEST::TestOneof2::kFooString:
  1243. EXPECT_TRUE(message.has_foo_string());
  1244. break;
  1245. case UNITTEST::TestOneof2::kFooCord:
  1246. EXPECT_TRUE(message.has_foo_cord());
  1247. break;
  1248. case UNITTEST::TestOneof2::kFooStringPiece:
  1249. EXPECT_TRUE(message.has_foo_string_piece());
  1250. break;
  1251. case UNITTEST::TestOneof2::kFooBytes:
  1252. EXPECT_TRUE(message.has_foo_bytes());
  1253. break;
  1254. case UNITTEST::TestOneof2::kFooEnum:
  1255. EXPECT_TRUE(message.has_foo_enum());
  1256. break;
  1257. case UNITTEST::TestOneof2::kFooMessage:
  1258. EXPECT_TRUE(message.has_foo_message());
  1259. break;
  1260. case UNITTEST::TestOneof2::kFoogroup:
  1261. EXPECT_TRUE(message.has_foogroup());
  1262. break;
  1263. case UNITTEST::TestOneof2::kFooLazyMessage:
  1264. EXPECT_TRUE(message.has_foo_lazy_message());
  1265. break;
  1266. case UNITTEST::TestOneof2::FOO_NOT_SET:
  1267. break;
  1268. }
  1269. }
  1270. };
  1271. TEST_F(OneofTest, SettingOneFieldClearsOthers) {
  1272. UNITTEST::TestOneof2 message;
  1273. message.set_foo_int(123);
  1274. EXPECT_TRUE(message.has_foo_int());
  1275. TestUtil::ExpectAtMostOneFieldSetInOneof(message);
  1276. message.set_foo_string("foo");
  1277. EXPECT_TRUE(message.has_foo_string());
  1278. TestUtil::ExpectAtMostOneFieldSetInOneof(message);
  1279. message.set_foo_bytes("qux");
  1280. EXPECT_TRUE(message.has_foo_bytes());
  1281. TestUtil::ExpectAtMostOneFieldSetInOneof(message);
  1282. message.set_foo_enum(UNITTEST::TestOneof2::FOO);
  1283. EXPECT_TRUE(message.has_foo_enum());
  1284. TestUtil::ExpectAtMostOneFieldSetInOneof(message);
  1285. message.mutable_foo_message()->set_qux_int(234);
  1286. EXPECT_TRUE(message.has_foo_message());
  1287. TestUtil::ExpectAtMostOneFieldSetInOneof(message);
  1288. message.mutable_foogroup()->set_a(345);
  1289. EXPECT_TRUE(message.has_foogroup());
  1290. TestUtil::ExpectAtMostOneFieldSetInOneof(message);
  1291. // we repeat this because we didn't test if this properly clears other fields
  1292. // at the beginning.
  1293. message.set_foo_int(123);
  1294. EXPECT_TRUE(message.has_foo_int());
  1295. TestUtil::ExpectAtMostOneFieldSetInOneof(message);
  1296. }
  1297. TEST_F(OneofTest, EnumCases) {
  1298. UNITTEST::TestOneof2 message;
  1299. message.set_foo_int(123);
  1300. ExpectEnumCasesWork(message);
  1301. message.set_foo_string("foo");
  1302. ExpectEnumCasesWork(message);
  1303. message.set_foo_bytes("qux");
  1304. ExpectEnumCasesWork(message);
  1305. message.set_foo_enum(UNITTEST::TestOneof2::FOO);
  1306. ExpectEnumCasesWork(message);
  1307. message.mutable_foo_message()->set_qux_int(234);
  1308. ExpectEnumCasesWork(message);
  1309. message.mutable_foogroup()->set_a(345);
  1310. ExpectEnumCasesWork(message);
  1311. }
  1312. TEST_F(OneofTest, PrimitiveType) {
  1313. UNITTEST::TestOneof2 message;
  1314. // Unset field returns default value
  1315. EXPECT_EQ(message.foo_int(), 0);
  1316. message.set_foo_int(123);
  1317. EXPECT_TRUE(message.has_foo_int());
  1318. EXPECT_EQ(message.foo_int(), 123);
  1319. message.clear_foo_int();
  1320. EXPECT_FALSE(message.has_foo_int());
  1321. }
  1322. TEST_F(OneofTest, EnumType) {
  1323. UNITTEST::TestOneof2 message;
  1324. // Unset field returns default value
  1325. EXPECT_EQ(message.foo_enum(), 1);
  1326. message.set_foo_enum(UNITTEST::TestOneof2::FOO);
  1327. EXPECT_TRUE(message.has_foo_enum());
  1328. EXPECT_EQ(message.foo_enum(), UNITTEST::TestOneof2::FOO);
  1329. message.clear_foo_enum();
  1330. EXPECT_FALSE(message.has_foo_enum());
  1331. }
  1332. TEST_F(OneofTest, SetString) {
  1333. // Check that setting a string field in various ways works
  1334. UNITTEST::TestOneof2 message;
  1335. // Unset field returns default value
  1336. EXPECT_EQ(message.foo_string(), "");
  1337. message.set_foo_string("foo");
  1338. EXPECT_TRUE(message.has_foo_string());
  1339. EXPECT_EQ(message.foo_string(), "foo");
  1340. message.clear_foo_string();
  1341. EXPECT_FALSE(message.has_foo_string());
  1342. message.set_foo_string(string("bar"));
  1343. EXPECT_TRUE(message.has_foo_string());
  1344. EXPECT_EQ(message.foo_string(), "bar");
  1345. message.clear_foo_string();
  1346. EXPECT_FALSE(message.has_foo_string());
  1347. message.set_foo_string("qux", 3);
  1348. EXPECT_TRUE(message.has_foo_string());
  1349. EXPECT_EQ(message.foo_string(), "qux");
  1350. message.clear_foo_string();
  1351. EXPECT_FALSE(message.has_foo_string());
  1352. message.mutable_foo_string()->assign("quux");
  1353. EXPECT_TRUE(message.has_foo_string());
  1354. EXPECT_EQ(message.foo_string(), "quux");
  1355. message.clear_foo_string();
  1356. EXPECT_FALSE(message.has_foo_string());
  1357. message.set_foo_string("corge");
  1358. EXPECT_TRUE(message.has_foo_string());
  1359. EXPECT_EQ(message.foo_string(), "corge");
  1360. message.clear_foo_string();
  1361. EXPECT_FALSE(message.has_foo_string());
  1362. }
  1363. TEST_F(OneofTest, ReleaseString) {
  1364. // Check that release_foo() starts out NULL, and gives us a value
  1365. // that we can delete after it's been set.
  1366. UNITTEST::TestOneof2 message;
  1367. EXPECT_EQ(NULL, message.release_foo_string());
  1368. EXPECT_FALSE(message.has_foo_string());
  1369. message.set_foo_string("blah");
  1370. EXPECT_TRUE(message.has_foo_string());
  1371. std::unique_ptr<string> str(message.release_foo_string());
  1372. EXPECT_FALSE(message.has_foo_string());
  1373. ASSERT_TRUE(str != NULL);
  1374. EXPECT_EQ("blah", *str);
  1375. EXPECT_EQ(NULL, message.release_foo_string());
  1376. EXPECT_FALSE(message.has_foo_string());
  1377. }
  1378. TEST_F(OneofTest, SetAllocatedString) {
  1379. // Check that set_allocated_foo() works for strings.
  1380. UNITTEST::TestOneof2 message;
  1381. EXPECT_FALSE(message.has_foo_string());
  1382. const string kHello("hello");
  1383. message.set_foo_string(kHello);
  1384. EXPECT_TRUE(message.has_foo_string());
  1385. message.set_allocated_foo_string(NULL);
  1386. EXPECT_FALSE(message.has_foo_string());
  1387. EXPECT_EQ("", message.foo_string());
  1388. message.set_allocated_foo_string(new string(kHello));
  1389. EXPECT_TRUE(message.has_foo_string());
  1390. EXPECT_EQ(kHello, message.foo_string());
  1391. }
  1392. TEST_F(OneofTest, SetMessage) {
  1393. // Check that setting a message field works
  1394. UNITTEST::TestOneof2 message;
  1395. // Unset field returns default instance
  1396. EXPECT_EQ(&message.foo_message(),
  1397. &UNITTEST::TestOneof2_NestedMessage::default_instance());
  1398. EXPECT_EQ(message.foo_message().qux_int(), 0);
  1399. message.mutable_foo_message()->set_qux_int(234);
  1400. EXPECT_TRUE(message.has_foo_message());
  1401. EXPECT_EQ(message.foo_message().qux_int(), 234);
  1402. message.clear_foo_message();
  1403. EXPECT_FALSE(message.has_foo_message());
  1404. }
  1405. TEST_F(OneofTest, ReleaseMessage) {
  1406. // Check that release_foo() starts out NULL, and gives us a value
  1407. // that we can delete after it's been set.
  1408. UNITTEST::TestOneof2 message;
  1409. EXPECT_EQ(NULL, message.release_foo_message());
  1410. EXPECT_FALSE(message.has_foo_message());
  1411. message.mutable_foo_message()->set_qux_int(1);
  1412. EXPECT_TRUE(message.has_foo_message());
  1413. std::unique_ptr<UNITTEST::TestOneof2_NestedMessage> mes(
  1414. message.release_foo_message());
  1415. EXPECT_FALSE(message.has_foo_message());
  1416. ASSERT_TRUE(mes != NULL);
  1417. EXPECT_EQ(1, mes->qux_int());
  1418. EXPECT_EQ(NULL, message.release_foo_message());
  1419. EXPECT_FALSE(message.has_foo_message());
  1420. }
  1421. TEST_F(OneofTest, SetAllocatedMessage) {
  1422. // Check that set_allocated_foo() works for messages.
  1423. UNITTEST::TestOneof2 message;
  1424. EXPECT_FALSE(message.has_foo_message());
  1425. message.mutable_foo_message()->set_qux_int(1);
  1426. EXPECT_TRUE(message.has_foo_message());
  1427. message.set_allocated_foo_message(NULL);
  1428. EXPECT_FALSE(message.has_foo_message());
  1429. EXPECT_EQ(&message.foo_message(),
  1430. &UNITTEST::TestOneof2_NestedMessage::default_instance());
  1431. message.mutable_foo_message()->set_qux_int(1);
  1432. UNITTEST::TestOneof2_NestedMessage* mes = message.release_foo_message();
  1433. ASSERT_TRUE(mes != NULL);
  1434. EXPECT_FALSE(message.has_foo_message());
  1435. message.set_allocated_foo_message(mes);
  1436. EXPECT_TRUE(message.has_foo_message());
  1437. EXPECT_EQ(1, message.foo_message().qux_int());
  1438. }
  1439. TEST_F(OneofTest, Clear) {
  1440. UNITTEST::TestOneof2 message;
  1441. message.set_foo_int(1);
  1442. EXPECT_TRUE(message.has_foo_int());
  1443. message.clear_foo_int();
  1444. EXPECT_FALSE(message.has_foo_int());
  1445. }
  1446. TEST_F(OneofTest, Defaults) {
  1447. UNITTEST::TestOneof2 message;
  1448. EXPECT_FALSE(message.has_foo_int());
  1449. EXPECT_EQ(message.foo_int(), 0);
  1450. EXPECT_FALSE(message.has_foo_string());
  1451. EXPECT_EQ(message.foo_string(), "");
  1452. EXPECT_FALSE(message.has_foo_bytes());
  1453. EXPECT_EQ(message.foo_bytes(), "");
  1454. EXPECT_FALSE(message.has_foo_enum());
  1455. EXPECT_EQ(message.foo_enum(), 1);
  1456. EXPECT_FALSE(message.has_foo_message());
  1457. EXPECT_EQ(message.foo_message().qux_int(), 0);
  1458. EXPECT_FALSE(message.has_foogroup());
  1459. EXPECT_EQ(message.foogroup().a(), 0);
  1460. EXPECT_FALSE(message.has_bar_int());
  1461. EXPECT_EQ(message.bar_int(), 5);
  1462. EXPECT_FALSE(message.has_bar_string());
  1463. EXPECT_EQ(message.bar_string(), "STRING");
  1464. EXPECT_FALSE(message.has_bar_bytes());
  1465. EXPECT_EQ(message.bar_bytes(), "BYTES");
  1466. EXPECT_FALSE(message.has_bar_enum());
  1467. EXPECT_EQ(message.bar_enum(), 2);
  1468. }
  1469. TEST_F(OneofTest, SwapWithEmpty) {
  1470. UNITTEST::TestOneof2 message1, message2;
  1471. message1.set_foo_string("FOO");
  1472. EXPECT_TRUE(message1.has_foo_string());
  1473. message1.Swap(&message2);
  1474. EXPECT_FALSE(message1.has_foo_string());
  1475. EXPECT_TRUE(message2.has_foo_string());
  1476. EXPECT_EQ(message2.foo_string(), "FOO");
  1477. }
  1478. TEST_F(OneofTest, SwapWithSelf) {
  1479. UNITTEST::TestOneof2 message;
  1480. message.set_foo_string("FOO");
  1481. EXPECT_TRUE(message.has_foo_string());
  1482. message.Swap(&message);
  1483. EXPECT_TRUE(message.has_foo_string());
  1484. EXPECT_EQ(message.foo_string(), "FOO");
  1485. }
  1486. TEST_F(OneofTest, SwapBothHasFields) {
  1487. UNITTEST::TestOneof2 message1, message2;
  1488. message1.set_foo_string("FOO");
  1489. EXPECT_TRUE(message1.has_foo_string());
  1490. message2.mutable_foo_message()->set_qux_int(1);
  1491. EXPECT_TRUE(message2.has_foo_message());
  1492. message1.Swap(&message2);
  1493. EXPECT_FALSE(message1.has_foo_string());
  1494. EXPECT_FALSE(message2.has_foo_message());
  1495. EXPECT_TRUE(message1.has_foo_message());
  1496. EXPECT_EQ(message1.foo_message().qux_int(), 1);
  1497. EXPECT_TRUE(message2.has_foo_string());
  1498. EXPECT_EQ(message2.foo_string(), "FOO");
  1499. }
  1500. TEST_F(OneofTest, CopyConstructor) {
  1501. UNITTEST::TestOneof2 message1;
  1502. message1.set_foo_bytes("FOO");
  1503. UNITTEST::TestOneof2 message2(message1);
  1504. EXPECT_TRUE(message2.has_foo_bytes());
  1505. EXPECT_EQ(message2.foo_bytes(), "FOO");
  1506. }
  1507. TEST_F(OneofTest, CopyFrom) {
  1508. UNITTEST::TestOneof2 message1, message2;
  1509. message1.set_foo_enum(UNITTEST::TestOneof2::BAR);
  1510. EXPECT_TRUE(message1.has_foo_enum());
  1511. message2.CopyFrom(message1);
  1512. EXPECT_TRUE(message2.has_foo_enum());
  1513. EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR);
  1514. // Copying from self should be a no-op.
  1515. message2.CopyFrom(message2);
  1516. EXPECT_TRUE(message2.has_foo_enum());
  1517. EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR);
  1518. }
  1519. TEST_F(OneofTest, CopyAssignmentOperator) {
  1520. UNITTEST::TestOneof2 message1;
  1521. message1.mutable_foo_message()->set_qux_int(123);
  1522. EXPECT_TRUE(message1.has_foo_message());
  1523. UNITTEST::TestOneof2 message2;
  1524. message2 = message1;
  1525. EXPECT_EQ(message2.foo_message().qux_int(), 123);
  1526. // Make sure that self-assignment does something sane.
  1527. message2 = message2;
  1528. EXPECT_EQ(message2.foo_message().qux_int(), 123);
  1529. }
  1530. TEST_F(OneofTest, UpcastCopyFrom) {
  1531. // Test the CopyFrom method that takes in the generic const Message&
  1532. // parameter.
  1533. UNITTEST::TestOneof2 message1, message2;
  1534. message1.mutable_foogroup()->set_a(123);
  1535. EXPECT_TRUE(message1.has_foogroup());
  1536. const Message* source = implicit_cast<const Message*>(&message1);
  1537. message2.CopyFrom(*source);
  1538. EXPECT_TRUE(message2.has_foogroup());
  1539. EXPECT_EQ(message2.foogroup().a(), 123);
  1540. }
  1541. // Test the generated SerializeWithCachedSizesToArray(),
  1542. // This indirectly tests MergePartialFromCodedStream()
  1543. // We have to test each field type separately because we cannot set them at the
  1544. // same time
  1545. TEST_F(OneofTest, SerializationToArray) {
  1546. // Primitive type
  1547. {
  1548. UNITTEST::TestOneof2 message1, message2;
  1549. string data;
  1550. message1.set_foo_int(123);
  1551. int size = message1.ByteSizeLong();
  1552. data.resize(size);
  1553. uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
  1554. uint8* end = message1.SerializeWithCachedSizesToArray(start);
  1555. EXPECT_EQ(size, end - start);
  1556. EXPECT_TRUE(message2.ParseFromString(data));
  1557. EXPECT_EQ(message2.foo_int(), 123);
  1558. }
  1559. // String
  1560. {
  1561. UNITTEST::TestOneof2 message1, message2;
  1562. string data;
  1563. message1.set_foo_string("foo");
  1564. int size = message1.ByteSizeLong();
  1565. data.resize(size);
  1566. uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
  1567. uint8* end = message1.SerializeWithCachedSizesToArray(start);
  1568. EXPECT_EQ(size, end - start);
  1569. EXPECT_TRUE(message2.ParseFromString(data));
  1570. EXPECT_EQ(message2.foo_string(), "foo");
  1571. }
  1572. // Bytes
  1573. {
  1574. UNITTEST::TestOneof2 message1, message2;
  1575. string data;
  1576. message1.set_foo_bytes("qux");
  1577. int size = message1.ByteSizeLong();
  1578. data.resize(size);
  1579. uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
  1580. uint8* end = message1.SerializeWithCachedSizesToArray(start);
  1581. EXPECT_EQ(size, end - start);
  1582. EXPECT_TRUE(message2.ParseFromString(data));
  1583. EXPECT_EQ(message2.foo_bytes(), "qux");
  1584. }
  1585. // Enum
  1586. {
  1587. UNITTEST::TestOneof2 message1, message2;
  1588. string data;
  1589. message1.set_foo_enum(UNITTEST::TestOneof2::FOO);
  1590. int size = message1.ByteSizeLong();
  1591. data.resize(size);
  1592. uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
  1593. uint8* end = message1.SerializeWithCachedSizesToArray(start);
  1594. EXPECT_EQ(size, end - start);
  1595. EXPECT_TRUE(message2.ParseFromString(data));
  1596. EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO);
  1597. }
  1598. // Message
  1599. {
  1600. UNITTEST::TestOneof2 message1, message2;
  1601. string data;
  1602. message1.mutable_foo_message()->set_qux_int(234);
  1603. int size = message1.ByteSizeLong();
  1604. data.resize(size);
  1605. uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
  1606. uint8* end = message1.SerializeWithCachedSizesToArray(start);
  1607. EXPECT_EQ(size, end - start);
  1608. EXPECT_TRUE(message2.ParseFromString(data));
  1609. EXPECT_EQ(message2.foo_message().qux_int(), 234);
  1610. }
  1611. // Group
  1612. {
  1613. UNITTEST::TestOneof2 message1, message2;
  1614. string data;
  1615. message1.mutable_foogroup()->set_a(345);
  1616. int size = message1.ByteSizeLong();
  1617. data.resize(size);
  1618. uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
  1619. uint8* end = message1.SerializeWithCachedSizesToArray(start);
  1620. EXPECT_EQ(size, end - start);
  1621. EXPECT_TRUE(message2.ParseFromString(data));
  1622. EXPECT_EQ(message2.foogroup().a(), 345);
  1623. }
  1624. }
  1625. // Test the generated SerializeWithCachedSizes() by forcing the buffer to write
  1626. // one byte at a time.
  1627. // This indirectly tests MergePartialFromCodedStream()
  1628. // We have to test each field type separately because we cannot set them at the
  1629. // same time
  1630. TEST_F(OneofTest, SerializationToStream) {
  1631. // Primitive type
  1632. {
  1633. UNITTEST::TestOneof2 message1, message2;
  1634. string data;
  1635. message1.set_foo_int(123);
  1636. int size = message1.ByteSizeLong();
  1637. data.resize(size);
  1638. {
  1639. // Allow the output stream to buffer only one byte at a time.
  1640. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  1641. io::CodedOutputStream output_stream(&array_stream);
  1642. message1.SerializeWithCachedSizes(&output_stream);
  1643. EXPECT_FALSE(output_stream.HadError());
  1644. EXPECT_EQ(size, output_stream.ByteCount());
  1645. }
  1646. EXPECT_TRUE(message2.ParseFromString(data));
  1647. EXPECT_EQ(message2.foo_int(), 123);
  1648. }
  1649. // String
  1650. {
  1651. UNITTEST::TestOneof2 message1, message2;
  1652. string data;
  1653. message1.set_foo_string("foo");
  1654. int size = message1.ByteSizeLong();
  1655. data.resize(size);
  1656. {
  1657. // Allow the output stream to buffer only one byte at a time.
  1658. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  1659. io::CodedOutputStream output_stream(&array_stream);
  1660. message1.SerializeWithCachedSizes(&output_stream);
  1661. EXPECT_FALSE(output_stream.HadError());
  1662. EXPECT_EQ(size, output_stream.ByteCount());
  1663. }
  1664. EXPECT_TRUE(message2.ParseFromString(data));
  1665. EXPECT_EQ(message2.foo_string(), "foo");
  1666. }
  1667. // Bytes
  1668. {
  1669. UNITTEST::TestOneof2 message1, message2;
  1670. string data;
  1671. message1.set_foo_bytes("qux");
  1672. int size = message1.ByteSizeLong();
  1673. data.resize(size);
  1674. {
  1675. // Allow the output stream to buffer only one byte at a time.
  1676. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  1677. io::CodedOutputStream output_stream(&array_stream);
  1678. message1.SerializeWithCachedSizes(&output_stream);
  1679. EXPECT_FALSE(output_stream.HadError());
  1680. EXPECT_EQ(size, output_stream.ByteCount());
  1681. }
  1682. EXPECT_TRUE(message2.ParseFromString(data));
  1683. EXPECT_EQ(message2.foo_bytes(), "qux");
  1684. }
  1685. // Enum
  1686. {
  1687. UNITTEST::TestOneof2 message1, message2;
  1688. string data;
  1689. message1.set_foo_enum(UNITTEST::TestOneof2::FOO);
  1690. int size = message1.ByteSizeLong();
  1691. data.resize(size);
  1692. {
  1693. // Allow the output stream to buffer only one byte at a time.
  1694. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  1695. io::CodedOutputStream output_stream(&array_stream);
  1696. message1.SerializeWithCachedSizes(&output_stream);
  1697. EXPECT_FALSE(output_stream.HadError());
  1698. EXPECT_EQ(size, output_stream.ByteCount());
  1699. }
  1700. EXPECT_TRUE(message2.ParseFromString(data));
  1701. EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO);
  1702. }
  1703. // Message
  1704. {
  1705. UNITTEST::TestOneof2 message1, message2;
  1706. string data;
  1707. message1.mutable_foo_message()->set_qux_int(234);
  1708. int size = message1.ByteSizeLong();
  1709. data.resize(size);
  1710. {
  1711. // Allow the output stream to buffer only one byte at a time.
  1712. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  1713. io::CodedOutputStream output_stream(&array_stream);
  1714. message1.SerializeWithCachedSizes(&output_stream);
  1715. EXPECT_FALSE(output_stream.HadError());
  1716. EXPECT_EQ(size, output_stream.ByteCount());
  1717. }
  1718. EXPECT_TRUE(message2.ParseFromString(data));
  1719. EXPECT_EQ(message2.foo_message().qux_int(), 234);
  1720. }
  1721. // Group
  1722. {
  1723. UNITTEST::TestOneof2 message1, message2;
  1724. string data;
  1725. message1.mutable_foogroup()->set_a(345);
  1726. int size = message1.ByteSizeLong();
  1727. data.resize(size);
  1728. {
  1729. // Allow the output stream to buffer only one byte at a time.
  1730. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  1731. io::CodedOutputStream output_stream(&array_stream);
  1732. message1.SerializeWithCachedSizes(&output_stream);
  1733. EXPECT_FALSE(output_stream.HadError());
  1734. EXPECT_EQ(size, output_stream.ByteCount());
  1735. }
  1736. EXPECT_TRUE(message2.ParseFromString(data));
  1737. EXPECT_EQ(message2.foogroup().a(), 345);
  1738. }
  1739. }
  1740. TEST_F(OneofTest, MergeFrom) {
  1741. UNITTEST::TestOneof2 message1, message2;
  1742. message1.set_foo_int(123);
  1743. message2.MergeFrom(message1);
  1744. TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
  1745. EXPECT_TRUE(message2.has_foo_int());
  1746. EXPECT_EQ(message2.foo_int(), 123);
  1747. message1.set_foo_string("foo");
  1748. message2.MergeFrom(message1);
  1749. TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
  1750. EXPECT_TRUE(message2.has_foo_string());
  1751. EXPECT_EQ(message2.foo_string(), "foo");
  1752. message1.set_foo_bytes("qux");
  1753. message2.MergeFrom(message1);
  1754. TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
  1755. EXPECT_TRUE(message2.has_foo_bytes());
  1756. EXPECT_EQ(message2.foo_bytes(), "qux");
  1757. message1.set_foo_enum(UNITTEST::TestOneof2::FOO);
  1758. message2.MergeFrom(message1);
  1759. TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
  1760. EXPECT_TRUE(message2.has_foo_enum());
  1761. EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO);
  1762. message1.mutable_foo_message()->set_qux_int(234);
  1763. message2.MergeFrom(message1);
  1764. TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
  1765. EXPECT_TRUE(message2.has_foo_message());
  1766. EXPECT_EQ(message2.foo_message().qux_int(), 234);
  1767. message1.mutable_foogroup()->set_a(345);
  1768. message2.MergeFrom(message1);
  1769. TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
  1770. EXPECT_TRUE(message2.has_foogroup());
  1771. EXPECT_EQ(message2.foogroup().a(), 345);
  1772. }
  1773. TEST(HELPERS_TEST_NAME, TestSCC) {
  1774. UNITTEST::TestMutualRecursionA a;
  1775. SCCAnalyzer scc_analyzer((Options()));
  1776. const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor());
  1777. std::vector<string> names;
  1778. for (int i = 0; i < scc->descriptors.size(); i++) {
  1779. names.push_back(scc->descriptors[i]->full_name());
  1780. }
  1781. string package = a.GetDescriptor()->file()->package();
  1782. ASSERT_EQ(names.size(), 4);
  1783. std::sort(names.begin(), names.end());
  1784. EXPECT_EQ(names[0], package + ".TestMutualRecursionA");
  1785. EXPECT_EQ(names[1], package + ".TestMutualRecursionA.SubGroup");
  1786. EXPECT_EQ(names[2], package + ".TestMutualRecursionA.SubMessage");
  1787. EXPECT_EQ(names[3], package + ".TestMutualRecursionB");
  1788. MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
  1789. EXPECT_EQ(result.is_recursive, true);
  1790. EXPECT_EQ(result.contains_required, false);
  1791. EXPECT_EQ(result.contains_cord, true); // TestAllTypes
  1792. EXPECT_EQ(result.contains_extension, false); // TestAllTypes
  1793. }
  1794. TEST(HELPERS_TEST_NAME, TestSCCAnalysis) {
  1795. {
  1796. UNITTEST::TestRecursiveMessage msg;
  1797. SCCAnalyzer scc_analyzer((Options()));
  1798. const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
  1799. MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
  1800. EXPECT_EQ(result.is_recursive, true);
  1801. EXPECT_EQ(result.contains_required, false);
  1802. EXPECT_EQ(result.contains_cord, false);
  1803. EXPECT_EQ(result.contains_extension, false);
  1804. }
  1805. {
  1806. UNITTEST::TestAllExtensions msg;
  1807. SCCAnalyzer scc_analyzer((Options()));
  1808. const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
  1809. MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
  1810. EXPECT_EQ(result.is_recursive, false);
  1811. EXPECT_EQ(result.contains_required, false);
  1812. EXPECT_EQ(result.contains_cord, false);
  1813. EXPECT_EQ(result.contains_extension, true);
  1814. }
  1815. {
  1816. UNITTEST::TestRequired msg;
  1817. SCCAnalyzer scc_analyzer((Options()));
  1818. const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
  1819. MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
  1820. EXPECT_EQ(result.is_recursive, false);
  1821. EXPECT_EQ(result.contains_required, true);
  1822. EXPECT_EQ(result.contains_cord, false);
  1823. EXPECT_EQ(result.contains_extension, false);
  1824. }
  1825. }
  1826. } // namespace cpp_unittest
  1827. } // namespace cpp
  1828. } // namespace compiler
  1829. namespace no_generic_services_test {
  1830. // Verify that no class called "TestService" was defined in
  1831. // unittest_no_generic_services.pb.h by defining a different type by the same
  1832. // name. If such a service was generated, this will not compile.
  1833. struct TestService {
  1834. int i;
  1835. };
  1836. }
  1837. namespace compiler {
  1838. namespace cpp {
  1839. namespace cpp_unittest {
  1840. TEST_F(GENERATED_SERVICE_TEST_NAME, NoGenericServices) {
  1841. // Verify that non-services in unittest_no_generic_services.proto were
  1842. // generated.
  1843. no_generic_services_test::TestMessage message;
  1844. message.set_a(1);
  1845. message.SetExtension(no_generic_services_test::test_extension, 123);
  1846. no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
  1847. EXPECT_EQ(e, 1);
  1848. // Verify that a ServiceDescriptor is generated for the service even if the
  1849. // class itself is not.
  1850. const FileDescriptor* file =
  1851. no_generic_services_test::TestMessage::descriptor()->file();
  1852. ASSERT_EQ(1, file->service_count());
  1853. EXPECT_EQ("TestService", file->service(0)->name());
  1854. ASSERT_EQ(1, file->service(0)->method_count());
  1855. EXPECT_EQ("Foo", file->service(0)->method(0)->name());
  1856. }
  1857. #endif // !PROTOBUF_TEST_NO_DESCRIPTORS
  1858. // ===================================================================
  1859. // This test must run last. It verifies that descriptors were or were not
  1860. // initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined.
  1861. // When this is defined, we skip all tests which are expected to trigger
  1862. // descriptor initialization. This verifies that everything else still works
  1863. // if descriptors are not initialized.
  1864. TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) {
  1865. #ifdef PROTOBUF_TEST_NO_DESCRIPTORS
  1866. bool should_have_descriptors = false;
  1867. #else
  1868. bool should_have_descriptors = true;
  1869. #endif
  1870. EXPECT_EQ(should_have_descriptors,
  1871. DescriptorPool::generated_pool()->InternalIsFileLoaded(
  1872. UNITTEST_PROTO_PATH));
  1873. }
  1874. } // namespace cpp_unittest
  1875. } // namespace cpp
  1876. } // namespace compiler
  1877. } // namespace protobuf
  1878. } // namespace google