/thirdparty/breakpad/third_party/protobuf/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.cc

http://github.com/tomahawk-player/tomahawk · C++ · 1281 lines · 865 code · 227 blank · 189 comment · 11 complexity · 46bdbe52fde47b211c6ebd5f6b5e254c MD5 · raw file

  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // http://code.google.com/p/protobuf/
  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 <vector>
  46. #include <google/protobuf/unittest.pb.h>
  47. #include <google/protobuf/unittest_optimize_for.pb.h>
  48. #include <google/protobuf/unittest_embed_optimize_for.pb.h>
  49. #include <google/protobuf/unittest_no_generic_services.pb.h>
  50. #include <google/protobuf/test_util.h>
  51. #include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h>
  52. #include <google/protobuf/compiler/importer.h>
  53. #include <google/protobuf/io/coded_stream.h>
  54. #include <google/protobuf/io/zero_copy_stream_impl.h>
  55. #include <google/protobuf/descriptor.h>
  56. #include <google/protobuf/descriptor.pb.h>
  57. #include <google/protobuf/dynamic_message.h>
  58. #include <google/protobuf/stubs/common.h>
  59. #include <google/protobuf/stubs/strutil.h>
  60. #include <google/protobuf/stubs/substitute.h>
  61. #include <google/protobuf/testing/googletest.h>
  62. #include <gtest/gtest.h>
  63. #include <google/protobuf/stubs/stl_util-inl.h>
  64. namespace google {
  65. namespace protobuf {
  66. namespace compiler {
  67. namespace cpp {
  68. // Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
  69. namespace cpp_unittest {
  70. class MockErrorCollector : public MultiFileErrorCollector {
  71. public:
  72. MockErrorCollector() {}
  73. ~MockErrorCollector() {}
  74. string text_;
  75. // implements ErrorCollector ---------------------------------------
  76. void AddError(const string& filename, int line, int column,
  77. const string& message) {
  78. strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
  79. filename, line, column, message);
  80. }
  81. };
  82. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  83. // Test that generated code has proper descriptors:
  84. // Parse a descriptor directly (using google::protobuf::compiler::Importer) and
  85. // compare it to the one that was produced by generated code.
  86. TEST(GeneratedDescriptorTest, IdenticalDescriptors) {
  87. const FileDescriptor* generated_descriptor =
  88. unittest::TestAllTypes::descriptor()->file();
  89. // Set up the Importer.
  90. MockErrorCollector error_collector;
  91. DiskSourceTree source_tree;
  92. source_tree.MapPath("", TestSourceDir());
  93. Importer importer(&source_tree, &error_collector);
  94. // Import (parse) unittest.proto.
  95. const FileDescriptor* parsed_descriptor =
  96. importer.Import("google/protobuf/unittest.proto");
  97. EXPECT_EQ("", error_collector.text_);
  98. ASSERT_TRUE(parsed_descriptor != NULL);
  99. // Test that descriptors are generated correctly by converting them to
  100. // FileDescriptorProtos and comparing.
  101. FileDescriptorProto generated_decsriptor_proto, parsed_descriptor_proto;
  102. generated_descriptor->CopyTo(&generated_decsriptor_proto);
  103. parsed_descriptor->CopyTo(&parsed_descriptor_proto);
  104. EXPECT_EQ(parsed_descriptor_proto.DebugString(),
  105. generated_decsriptor_proto.DebugString());
  106. }
  107. #endif // !PROTOBUF_TEST_NO_DESCRIPTORS
  108. // ===================================================================
  109. TEST(GeneratedMessageTest, Defaults) {
  110. // Check that all default values are set correctly in the initial message.
  111. unittest::TestAllTypes message;
  112. TestUtil::ExpectClear(message);
  113. // Messages should return pointers to default instances until first use.
  114. // (This is not checked by ExpectClear() since it is not actually true after
  115. // the fields have been set and then cleared.)
  116. EXPECT_EQ(&unittest::TestAllTypes::OptionalGroup::default_instance(),
  117. &message.optionalgroup());
  118. EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
  119. &message.optional_nested_message());
  120. EXPECT_EQ(&unittest::ForeignMessage::default_instance(),
  121. &message.optional_foreign_message());
  122. EXPECT_EQ(&unittest_import::ImportMessage::default_instance(),
  123. &message.optional_import_message());
  124. }
  125. TEST(GeneratedMessageTest, FloatingPointDefaults) {
  126. const unittest::TestExtremeDefaultValues& extreme_default =
  127. unittest::TestExtremeDefaultValues::default_instance();
  128. EXPECT_EQ(0.0f, extreme_default.zero_float());
  129. EXPECT_EQ(1.0f, extreme_default.one_float());
  130. EXPECT_EQ(1.5f, extreme_default.small_float());
  131. EXPECT_EQ(-1.0f, extreme_default.negative_one_float());
  132. EXPECT_EQ(-1.5f, extreme_default.negative_float());
  133. EXPECT_EQ(2.0e8f, extreme_default.large_float());
  134. EXPECT_EQ(-8e-28f, extreme_default.small_negative_float());
  135. EXPECT_EQ(numeric_limits<double>::infinity(),
  136. extreme_default.inf_double());
  137. EXPECT_EQ(-numeric_limits<double>::infinity(),
  138. extreme_default.neg_inf_double());
  139. EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double());
  140. EXPECT_EQ(numeric_limits<float>::infinity(),
  141. extreme_default.inf_float());
  142. EXPECT_EQ(-numeric_limits<float>::infinity(),
  143. extreme_default.neg_inf_float());
  144. EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float());
  145. }
  146. TEST(GeneratedMessageTest, Trigraph) {
  147. const unittest::TestExtremeDefaultValues& extreme_default =
  148. unittest::TestExtremeDefaultValues::default_instance();
  149. EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph());
  150. }
  151. TEST(GeneratedMessageTest, Accessors) {
  152. // Set every field to a unique value then go back and check all those
  153. // values.
  154. unittest::TestAllTypes message;
  155. TestUtil::SetAllFields(&message);
  156. TestUtil::ExpectAllFieldsSet(message);
  157. TestUtil::ModifyRepeatedFields(&message);
  158. TestUtil::ExpectRepeatedFieldsModified(message);
  159. }
  160. TEST(GeneratedMessageTest, MutableStringDefault) {
  161. // mutable_foo() for a string should return a string initialized to its
  162. // default value.
  163. unittest::TestAllTypes message;
  164. EXPECT_EQ("hello", *message.mutable_default_string());
  165. // Note that the first time we call mutable_foo(), we get a newly-allocated
  166. // string, but if we clear it and call it again, we get the same object again.
  167. // We should verify that it has its default value in both cases.
  168. message.set_default_string("blah");
  169. message.Clear();
  170. EXPECT_EQ("hello", *message.mutable_default_string());
  171. }
  172. TEST(GeneratedMessageTest, ReleaseString) {
  173. // Check that release_foo() starts out NULL, and gives us a value
  174. // that we can delete after it's been set.
  175. unittest::TestAllTypes message;
  176. EXPECT_EQ(NULL, message.release_default_string());
  177. EXPECT_FALSE(message.has_default_string());
  178. EXPECT_EQ("hello", message.default_string());
  179. message.set_default_string("blah");
  180. EXPECT_TRUE(message.has_default_string());
  181. string* str = message.release_default_string();
  182. EXPECT_FALSE(message.has_default_string());
  183. ASSERT_TRUE(str != NULL);
  184. EXPECT_EQ("blah", *str);
  185. delete str;
  186. EXPECT_EQ(NULL, message.release_default_string());
  187. EXPECT_FALSE(message.has_default_string());
  188. EXPECT_EQ("hello", message.default_string());
  189. }
  190. TEST(GeneratedMessageTest, ReleaseMessage) {
  191. // Check that release_foo() starts out NULL, and gives us a value
  192. // that we can delete after it's been set.
  193. unittest::TestAllTypes message;
  194. EXPECT_EQ(NULL, message.release_optional_nested_message());
  195. EXPECT_FALSE(message.has_optional_nested_message());
  196. message.mutable_optional_nested_message()->set_bb(1);
  197. unittest::TestAllTypes::NestedMessage* nest =
  198. message.release_optional_nested_message();
  199. EXPECT_FALSE(message.has_optional_nested_message());
  200. ASSERT_TRUE(nest != NULL);
  201. EXPECT_EQ(1, nest->bb());
  202. delete nest;
  203. EXPECT_EQ(NULL, message.release_optional_nested_message());
  204. EXPECT_FALSE(message.has_optional_nested_message());
  205. }
  206. TEST(GeneratedMessageTest, Clear) {
  207. // Set every field to a unique value, clear the message, then check that
  208. // it is cleared.
  209. unittest::TestAllTypes message;
  210. TestUtil::SetAllFields(&message);
  211. message.Clear();
  212. TestUtil::ExpectClear(message);
  213. // Unlike with the defaults test, we do NOT expect that requesting embedded
  214. // messages will return a pointer to the default instance. Instead, they
  215. // should return the objects that were created when mutable_blah() was
  216. // called.
  217. EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(),
  218. &message.optionalgroup());
  219. EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(),
  220. &message.optional_nested_message());
  221. EXPECT_NE(&unittest::ForeignMessage::default_instance(),
  222. &message.optional_foreign_message());
  223. EXPECT_NE(&unittest_import::ImportMessage::default_instance(),
  224. &message.optional_import_message());
  225. }
  226. TEST(GeneratedMessageTest, EmbeddedNullsInBytesCharStar) {
  227. unittest::TestAllTypes message;
  228. const char* value = "\0lalala\0\0";
  229. message.set_optional_bytes(value, 9);
  230. ASSERT_EQ(9, message.optional_bytes().size());
  231. EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9));
  232. message.add_repeated_bytes(value, 9);
  233. ASSERT_EQ(9, message.repeated_bytes(0).size());
  234. EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9));
  235. }
  236. TEST(GeneratedMessageTest, ClearOneField) {
  237. // Set every field to a unique value, then clear one value and insure that
  238. // only that one value is cleared.
  239. unittest::TestAllTypes message;
  240. TestUtil::SetAllFields(&message);
  241. int64 original_value = message.optional_int64();
  242. // Clear the field and make sure it shows up as cleared.
  243. message.clear_optional_int64();
  244. EXPECT_FALSE(message.has_optional_int64());
  245. EXPECT_EQ(0, message.optional_int64());
  246. // Other adjacent fields should not be cleared.
  247. EXPECT_TRUE(message.has_optional_int32());
  248. EXPECT_TRUE(message.has_optional_uint32());
  249. // Make sure if we set it again, then all fields are set.
  250. message.set_optional_int64(original_value);
  251. TestUtil::ExpectAllFieldsSet(message);
  252. }
  253. TEST(GeneratedMessageTest, StringCharStarLength) {
  254. // Verify that we can use a char*,length to set one of the string fields.
  255. unittest::TestAllTypes message;
  256. message.set_optional_string("abcdef", 3);
  257. EXPECT_EQ("abc", message.optional_string());
  258. // Verify that we can use a char*,length to add to a repeated string field.
  259. message.add_repeated_string("abcdef", 3);
  260. EXPECT_EQ(1, message.repeated_string_size());
  261. EXPECT_EQ("abc", message.repeated_string(0));
  262. // Verify that we can use a char*,length to set a repeated string field.
  263. message.set_repeated_string(0, "wxyz", 2);
  264. EXPECT_EQ("wx", message.repeated_string(0));
  265. }
  266. TEST(GeneratedMessageTest, CopyFrom) {
  267. unittest::TestAllTypes message1, message2;
  268. TestUtil::SetAllFields(&message1);
  269. message2.CopyFrom(message1);
  270. TestUtil::ExpectAllFieldsSet(message2);
  271. // Copying from self should be a no-op.
  272. message2.CopyFrom(message2);
  273. TestUtil::ExpectAllFieldsSet(message2);
  274. }
  275. TEST(GeneratedMessageTest, SwapWithEmpty) {
  276. unittest::TestAllTypes message1, message2;
  277. TestUtil::SetAllFields(&message1);
  278. TestUtil::ExpectAllFieldsSet(message1);
  279. TestUtil::ExpectClear(message2);
  280. message1.Swap(&message2);
  281. TestUtil::ExpectAllFieldsSet(message2);
  282. TestUtil::ExpectClear(message1);
  283. }
  284. TEST(GeneratedMessageTest, SwapWithSelf) {
  285. unittest::TestAllTypes message;
  286. TestUtil::SetAllFields(&message);
  287. TestUtil::ExpectAllFieldsSet(message);
  288. message.Swap(&message);
  289. TestUtil::ExpectAllFieldsSet(message);
  290. }
  291. TEST(GeneratedMessageTest, SwapWithOther) {
  292. unittest::TestAllTypes message1, message2;
  293. message1.set_optional_int32(123);
  294. message1.set_optional_string("abc");
  295. message1.mutable_optional_nested_message()->set_bb(1);
  296. message1.set_optional_nested_enum(unittest::TestAllTypes::FOO);
  297. message1.add_repeated_int32(1);
  298. message1.add_repeated_int32(2);
  299. message1.add_repeated_string("a");
  300. message1.add_repeated_string("b");
  301. message1.add_repeated_nested_message()->set_bb(7);
  302. message1.add_repeated_nested_message()->set_bb(8);
  303. message1.add_repeated_nested_enum(unittest::TestAllTypes::FOO);
  304. message1.add_repeated_nested_enum(unittest::TestAllTypes::BAR);
  305. message2.set_optional_int32(456);
  306. message2.set_optional_string("def");
  307. message2.mutable_optional_nested_message()->set_bb(2);
  308. message2.set_optional_nested_enum(unittest::TestAllTypes::BAR);
  309. message2.add_repeated_int32(3);
  310. message2.add_repeated_string("c");
  311. message2.add_repeated_nested_message()->set_bb(9);
  312. message2.add_repeated_nested_enum(unittest::TestAllTypes::BAZ);
  313. message1.Swap(&message2);
  314. EXPECT_EQ(456, message1.optional_int32());
  315. EXPECT_EQ("def", message1.optional_string());
  316. EXPECT_EQ(2, message1.optional_nested_message().bb());
  317. EXPECT_EQ(unittest::TestAllTypes::BAR, message1.optional_nested_enum());
  318. ASSERT_EQ(1, message1.repeated_int32_size());
  319. EXPECT_EQ(3, message1.repeated_int32(0));
  320. ASSERT_EQ(1, message1.repeated_string_size());
  321. EXPECT_EQ("c", message1.repeated_string(0));
  322. ASSERT_EQ(1, message1.repeated_nested_message_size());
  323. EXPECT_EQ(9, message1.repeated_nested_message(0).bb());
  324. ASSERT_EQ(1, message1.repeated_nested_enum_size());
  325. EXPECT_EQ(unittest::TestAllTypes::BAZ, message1.repeated_nested_enum(0));
  326. EXPECT_EQ(123, message2.optional_int32());
  327. EXPECT_EQ("abc", message2.optional_string());
  328. EXPECT_EQ(1, message2.optional_nested_message().bb());
  329. EXPECT_EQ(unittest::TestAllTypes::FOO, message2.optional_nested_enum());
  330. ASSERT_EQ(2, message2.repeated_int32_size());
  331. EXPECT_EQ(1, message2.repeated_int32(0));
  332. EXPECT_EQ(2, message2.repeated_int32(1));
  333. ASSERT_EQ(2, message2.repeated_string_size());
  334. EXPECT_EQ("a", message2.repeated_string(0));
  335. EXPECT_EQ("b", message2.repeated_string(1));
  336. ASSERT_EQ(2, message2.repeated_nested_message_size());
  337. EXPECT_EQ(7, message2.repeated_nested_message(0).bb());
  338. EXPECT_EQ(8, message2.repeated_nested_message(1).bb());
  339. ASSERT_EQ(2, message2.repeated_nested_enum_size());
  340. EXPECT_EQ(unittest::TestAllTypes::FOO, message2.repeated_nested_enum(0));
  341. EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1));
  342. }
  343. TEST(GeneratedMessageTest, CopyConstructor) {
  344. unittest::TestAllTypes message1;
  345. TestUtil::SetAllFields(&message1);
  346. unittest::TestAllTypes message2(message1);
  347. TestUtil::ExpectAllFieldsSet(message2);
  348. }
  349. TEST(GeneratedMessageTest, CopyAssignmentOperator) {
  350. unittest::TestAllTypes message1;
  351. TestUtil::SetAllFields(&message1);
  352. unittest::TestAllTypes message2;
  353. message2 = message1;
  354. TestUtil::ExpectAllFieldsSet(message2);
  355. // Make sure that self-assignment does something sane.
  356. message2.operator=(message2);
  357. TestUtil::ExpectAllFieldsSet(message2);
  358. }
  359. TEST(GeneratedMessageTest, UpcastCopyFrom) {
  360. // Test the CopyFrom method that takes in the generic const Message&
  361. // parameter.
  362. unittest::TestAllTypes message1, message2;
  363. TestUtil::SetAllFields(&message1);
  364. const Message* source = implicit_cast<const Message*>(&message1);
  365. message2.CopyFrom(*source);
  366. TestUtil::ExpectAllFieldsSet(message2);
  367. }
  368. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  369. TEST(GeneratedMessageTest, DynamicMessageCopyFrom) {
  370. // Test copying from a DynamicMessage, which must fall back to using
  371. // reflection.
  372. unittest::TestAllTypes message2;
  373. // Construct a new version of the dynamic message via the factory.
  374. DynamicMessageFactory factory;
  375. scoped_ptr<Message> message1;
  376. message1.reset(factory.GetPrototype(
  377. unittest::TestAllTypes::descriptor())->New());
  378. TestUtil::ReflectionTester reflection_tester(
  379. unittest::TestAllTypes::descriptor());
  380. reflection_tester.SetAllFieldsViaReflection(message1.get());
  381. message2.CopyFrom(*message1);
  382. TestUtil::ExpectAllFieldsSet(message2);
  383. }
  384. #endif // !PROTOBUF_TEST_NO_DESCRIPTORS
  385. TEST(GeneratedMessageTest, NonEmptyMergeFrom) {
  386. // Test merging with a non-empty message. Code is a modified form
  387. // of that found in google/protobuf/reflection_ops_unittest.cc.
  388. unittest::TestAllTypes message1, message2;
  389. TestUtil::SetAllFields(&message1);
  390. // This field will test merging into an empty spot.
  391. message2.set_optional_int32(message1.optional_int32());
  392. message1.clear_optional_int32();
  393. // This tests overwriting.
  394. message2.set_optional_string(message1.optional_string());
  395. message1.set_optional_string("something else");
  396. // This tests concatenating.
  397. message2.add_repeated_int32(message1.repeated_int32(1));
  398. int32 i = message1.repeated_int32(0);
  399. message1.clear_repeated_int32();
  400. message1.add_repeated_int32(i);
  401. message1.MergeFrom(message2);
  402. TestUtil::ExpectAllFieldsSet(message1);
  403. }
  404. #ifdef GTEST_HAS_DEATH_TEST
  405. TEST(GeneratedMessageTest, MergeFromSelf) {
  406. unittest::TestAllTypes message;
  407. EXPECT_DEATH(message.MergeFrom(message), "&from");
  408. EXPECT_DEATH(message.MergeFrom(implicit_cast<const Message&>(message)),
  409. "&from");
  410. }
  411. #endif // GTEST_HAS_DEATH_TEST
  412. // Test the generated SerializeWithCachedSizesToArray(),
  413. TEST(GeneratedMessageTest, SerializationToArray) {
  414. unittest::TestAllTypes message1, message2;
  415. string data;
  416. TestUtil::SetAllFields(&message1);
  417. int size = message1.ByteSize();
  418. data.resize(size);
  419. uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
  420. uint8* end = message1.SerializeWithCachedSizesToArray(start);
  421. EXPECT_EQ(size, end - start);
  422. EXPECT_TRUE(message2.ParseFromString(data));
  423. TestUtil::ExpectAllFieldsSet(message2);
  424. }
  425. TEST(GeneratedMessageTest, PackedFieldsSerializationToArray) {
  426. unittest::TestPackedTypes packed_message1, packed_message2;
  427. string packed_data;
  428. TestUtil::SetPackedFields(&packed_message1);
  429. int packed_size = packed_message1.ByteSize();
  430. packed_data.resize(packed_size);
  431. uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data));
  432. uint8* end = packed_message1.SerializeWithCachedSizesToArray(start);
  433. EXPECT_EQ(packed_size, end - start);
  434. EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
  435. TestUtil::ExpectPackedFieldsSet(packed_message2);
  436. }
  437. // Test the generated SerializeWithCachedSizes() by forcing the buffer to write
  438. // one byte at a time.
  439. TEST(GeneratedMessageTest, SerializationToStream) {
  440. unittest::TestAllTypes message1, message2;
  441. TestUtil::SetAllFields(&message1);
  442. int size = message1.ByteSize();
  443. string data;
  444. data.resize(size);
  445. {
  446. // Allow the output stream to buffer only one byte at a time.
  447. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  448. io::CodedOutputStream output_stream(&array_stream);
  449. message1.SerializeWithCachedSizes(&output_stream);
  450. EXPECT_FALSE(output_stream.HadError());
  451. EXPECT_EQ(size, output_stream.ByteCount());
  452. }
  453. EXPECT_TRUE(message2.ParseFromString(data));
  454. TestUtil::ExpectAllFieldsSet(message2);
  455. }
  456. TEST(GeneratedMessageTest, PackedFieldsSerializationToStream) {
  457. unittest::TestPackedTypes message1, message2;
  458. TestUtil::SetPackedFields(&message1);
  459. int size = message1.ByteSize();
  460. string data;
  461. data.resize(size);
  462. {
  463. // Allow the output stream to buffer only one byte at a time.
  464. io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
  465. io::CodedOutputStream output_stream(&array_stream);
  466. message1.SerializeWithCachedSizes(&output_stream);
  467. EXPECT_FALSE(output_stream.HadError());
  468. EXPECT_EQ(size, output_stream.ByteCount());
  469. }
  470. EXPECT_TRUE(message2.ParseFromString(data));
  471. TestUtil::ExpectPackedFieldsSet(message2);
  472. }
  473. TEST(GeneratedMessageTest, Required) {
  474. // Test that IsInitialized() returns false if required fields are missing.
  475. unittest::TestRequired message;
  476. EXPECT_FALSE(message.IsInitialized());
  477. message.set_a(1);
  478. EXPECT_FALSE(message.IsInitialized());
  479. message.set_b(2);
  480. EXPECT_FALSE(message.IsInitialized());
  481. message.set_c(3);
  482. EXPECT_TRUE(message.IsInitialized());
  483. }
  484. TEST(GeneratedMessageTest, RequiredForeign) {
  485. // Test that IsInitialized() returns false if required fields in nested
  486. // messages are missing.
  487. unittest::TestRequiredForeign message;
  488. EXPECT_TRUE(message.IsInitialized());
  489. message.mutable_optional_message();
  490. EXPECT_FALSE(message.IsInitialized());
  491. message.mutable_optional_message()->set_a(1);
  492. message.mutable_optional_message()->set_b(2);
  493. message.mutable_optional_message()->set_c(3);
  494. EXPECT_TRUE(message.IsInitialized());
  495. message.add_repeated_message();
  496. EXPECT_FALSE(message.IsInitialized());
  497. message.mutable_repeated_message(0)->set_a(1);
  498. message.mutable_repeated_message(0)->set_b(2);
  499. message.mutable_repeated_message(0)->set_c(3);
  500. EXPECT_TRUE(message.IsInitialized());
  501. }
  502. TEST(GeneratedMessageTest, ForeignNested) {
  503. // Test that TestAllTypes::NestedMessage can be embedded directly into
  504. // another message.
  505. unittest::TestForeignNested message;
  506. // If this compiles and runs without crashing, it must work. We have
  507. // nothing more to test.
  508. unittest::TestAllTypes::NestedMessage* nested =
  509. message.mutable_foreign_nested();
  510. nested->set_bb(1);
  511. }
  512. TEST(GeneratedMessageTest, ReallyLargeTagNumber) {
  513. // Test that really large tag numbers don't break anything.
  514. unittest::TestReallyLargeTagNumber message1, message2;
  515. string data;
  516. // For the most part, if this compiles and runs then we're probably good.
  517. // (The most likely cause for failure would be if something were attempting
  518. // to allocate a lookup table of some sort using tag numbers as the index.)
  519. // We'll try serializing just for fun.
  520. message1.set_a(1234);
  521. message1.set_bb(5678);
  522. message1.SerializeToString(&data);
  523. EXPECT_TRUE(message2.ParseFromString(data));
  524. EXPECT_EQ(1234, message2.a());
  525. EXPECT_EQ(5678, message2.bb());
  526. }
  527. TEST(GeneratedMessageTest, MutualRecursion) {
  528. // Test that mutually-recursive message types work.
  529. unittest::TestMutualRecursionA message;
  530. unittest::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a();
  531. unittest::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a();
  532. // Again, if the above compiles and runs, that's all we really have to
  533. // test, but just for run we'll check that the system didn't somehow come
  534. // up with a pointer loop...
  535. EXPECT_NE(&message, nested);
  536. EXPECT_NE(&message, nested2);
  537. EXPECT_NE(nested, nested2);
  538. }
  539. TEST(GeneratedMessageTest, CamelCaseFieldNames) {
  540. // This test is mainly checking that the following compiles, which verifies
  541. // that the field names were coerced to lower-case.
  542. //
  543. // Protocol buffers standard style is to use lowercase-with-underscores for
  544. // field names. Some old proto1 .protos unfortunately used camel-case field
  545. // names. In proto1, these names were forced to lower-case. So, we do the
  546. // same thing in proto2.
  547. unittest::TestCamelCaseFieldNames message;
  548. message.set_primitivefield(2);
  549. message.set_stringfield("foo");
  550. message.set_enumfield(unittest::FOREIGN_FOO);
  551. message.mutable_messagefield()->set_c(6);
  552. message.add_repeatedprimitivefield(8);
  553. message.add_repeatedstringfield("qux");
  554. message.add_repeatedenumfield(unittest::FOREIGN_BAR);
  555. message.add_repeatedmessagefield()->set_c(15);
  556. EXPECT_EQ(2, message.primitivefield());
  557. EXPECT_EQ("foo", message.stringfield());
  558. EXPECT_EQ(unittest::FOREIGN_FOO, message.enumfield());
  559. EXPECT_EQ(6, message.messagefield().c());
  560. EXPECT_EQ(8, message.repeatedprimitivefield(0));
  561. EXPECT_EQ("qux", message.repeatedstringfield(0));
  562. EXPECT_EQ(unittest::FOREIGN_BAR, message.repeatedenumfield(0));
  563. EXPECT_EQ(15, message.repeatedmessagefield(0).c());
  564. }
  565. TEST(GeneratedMessageTest, TestConflictingSymbolNames) {
  566. // test_bad_identifiers.proto successfully compiled, then it works. The
  567. // following is just a token usage to insure that the code is, in fact,
  568. // being compiled and linked.
  569. protobuf_unittest::TestConflictingSymbolNames message;
  570. message.set_uint32(1);
  571. EXPECT_EQ(3, message.ByteSize());
  572. message.set_friend_(5);
  573. EXPECT_EQ(5, message.friend_());
  574. }
  575. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  576. TEST(GeneratedMessageTest, TestOptimizedForSize) {
  577. // We rely on the tests in reflection_ops_unittest and wire_format_unittest
  578. // to really test that reflection-based methods work. Here we are mostly
  579. // just making sure that TestOptimizedForSize actually builds and seems to
  580. // function.
  581. protobuf_unittest::TestOptimizedForSize message, message2;
  582. message.set_i(1);
  583. message.mutable_msg()->set_c(2);
  584. message2.CopyFrom(message);
  585. EXPECT_EQ(1, message2.i());
  586. EXPECT_EQ(2, message2.msg().c());
  587. }
  588. TEST(GeneratedMessageTest, TestEmbedOptimizedForSize) {
  589. // Verifies that something optimized for speed can contain something optimized
  590. // for size.
  591. protobuf_unittest::TestEmbedOptimizedForSize message, message2;
  592. message.mutable_optional_message()->set_i(1);
  593. message.add_repeated_message()->mutable_msg()->set_c(2);
  594. string data;
  595. message.SerializeToString(&data);
  596. ASSERT_TRUE(message2.ParseFromString(data));
  597. EXPECT_EQ(1, message2.optional_message().i());
  598. EXPECT_EQ(2, message2.repeated_message(0).msg().c());
  599. }
  600. TEST(GeneratedMessageTest, TestSpaceUsed) {
  601. unittest::TestAllTypes message1;
  602. // sizeof provides a lower bound on SpaceUsed().
  603. EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsed());
  604. const int empty_message_size = message1.SpaceUsed();
  605. // Setting primitive types shouldn't affect the space used.
  606. message1.set_optional_int32(123);
  607. message1.set_optional_int64(12345);
  608. message1.set_optional_uint32(123);
  609. message1.set_optional_uint64(12345);
  610. EXPECT_EQ(empty_message_size, message1.SpaceUsed());
  611. // On some STL implementations, setting the string to a small value should
  612. // only increase SpaceUsed() by the size of a string object, though this is
  613. // not true everywhere.
  614. message1.set_optional_string("abc");
  615. EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsed());
  616. // Setting a string to a value larger than the string object itself should
  617. // increase SpaceUsed(), because it cannot store the value internally.
  618. message1.set_optional_string(string(sizeof(string) + 1, 'x'));
  619. int min_expected_increase = message1.optional_string().capacity() +
  620. sizeof(string);
  621. EXPECT_LE(empty_message_size + min_expected_increase,
  622. message1.SpaceUsed());
  623. int previous_size = message1.SpaceUsed();
  624. // Adding an optional message should increase the size by the size of the
  625. // nested message type. NestedMessage is simple enough (1 int field) that it
  626. // is equal to sizeof(NestedMessage)
  627. message1.mutable_optional_nested_message();
  628. ASSERT_EQ(sizeof(unittest::TestAllTypes::NestedMessage),
  629. message1.optional_nested_message().SpaceUsed());
  630. EXPECT_EQ(previous_size +
  631. sizeof(unittest::TestAllTypes::NestedMessage),
  632. message1.SpaceUsed());
  633. }
  634. #endif // !PROTOBUF_TEST_NO_DESCRIPTORS
  635. TEST(GeneratedMessageTest, FieldConstantValues) {
  636. unittest::TestRequired message;
  637. EXPECT_EQ(unittest::TestAllTypes_NestedMessage::kBbFieldNumber, 1);
  638. EXPECT_EQ(unittest::TestAllTypes::kOptionalInt32FieldNumber, 1);
  639. EXPECT_EQ(unittest::TestAllTypes::kOptionalgroupFieldNumber, 16);
  640. EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedMessageFieldNumber, 18);
  641. EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedEnumFieldNumber, 21);
  642. EXPECT_EQ(unittest::TestAllTypes::kRepeatedInt32FieldNumber, 31);
  643. EXPECT_EQ(unittest::TestAllTypes::kRepeatedgroupFieldNumber, 46);
  644. EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48);
  645. EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51);
  646. }
  647. TEST(GeneratedMessageTest, ExtensionConstantValues) {
  648. EXPECT_EQ(unittest::TestRequired::kSingleFieldNumber, 1000);
  649. EXPECT_EQ(unittest::TestRequired::kMultiFieldNumber, 1001);
  650. EXPECT_EQ(unittest::kOptionalInt32ExtensionFieldNumber, 1);
  651. EXPECT_EQ(unittest::kOptionalgroupExtensionFieldNumber, 16);
  652. EXPECT_EQ(unittest::kOptionalNestedMessageExtensionFieldNumber, 18);
  653. EXPECT_EQ(unittest::kOptionalNestedEnumExtensionFieldNumber, 21);
  654. EXPECT_EQ(unittest::kRepeatedInt32ExtensionFieldNumber, 31);
  655. EXPECT_EQ(unittest::kRepeatedgroupExtensionFieldNumber, 46);
  656. EXPECT_EQ(unittest::kRepeatedNestedMessageExtensionFieldNumber, 48);
  657. EXPECT_EQ(unittest::kRepeatedNestedEnumExtensionFieldNumber, 51);
  658. }
  659. // ===================================================================
  660. TEST(GeneratedEnumTest, EnumValuesAsSwitchCases) {
  661. // Test that our nested enum values can be used as switch cases. This test
  662. // doesn't actually do anything, the proof that it works is that it
  663. // compiles.
  664. int i =0;
  665. unittest::TestAllTypes::NestedEnum a = unittest::TestAllTypes::BAR;
  666. switch (a) {
  667. case unittest::TestAllTypes::FOO:
  668. i = 1;
  669. break;
  670. case unittest::TestAllTypes::BAR:
  671. i = 2;
  672. break;
  673. case unittest::TestAllTypes::BAZ:
  674. i = 3;
  675. break;
  676. // no default case: We want to make sure the compiler recognizes that
  677. // all cases are covered. (GCC warns if you do not cover all cases of
  678. // an enum in a switch.)
  679. }
  680. // Token check just for fun.
  681. EXPECT_EQ(2, i);
  682. }
  683. TEST(GeneratedEnumTest, IsValidValue) {
  684. // Test enum IsValidValue.
  685. EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(1));
  686. EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(2));
  687. EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(3));
  688. EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(0));
  689. EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(4));
  690. // Make sure it also works when there are dups.
  691. EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(1));
  692. EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(2));
  693. EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(3));
  694. EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(0));
  695. EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(4));
  696. }
  697. TEST(GeneratedEnumTest, MinAndMax) {
  698. EXPECT_EQ(unittest::TestAllTypes::FOO,
  699. unittest::TestAllTypes::NestedEnum_MIN);
  700. EXPECT_EQ(unittest::TestAllTypes::BAZ,
  701. unittest::TestAllTypes::NestedEnum_MAX);
  702. EXPECT_EQ(4, unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
  703. EXPECT_EQ(unittest::FOREIGN_FOO, unittest::ForeignEnum_MIN);
  704. EXPECT_EQ(unittest::FOREIGN_BAZ, unittest::ForeignEnum_MAX);
  705. EXPECT_EQ(7, unittest::ForeignEnum_ARRAYSIZE);
  706. EXPECT_EQ(1, unittest::TestEnumWithDupValue_MIN);
  707. EXPECT_EQ(3, unittest::TestEnumWithDupValue_MAX);
  708. EXPECT_EQ(4, unittest::TestEnumWithDupValue_ARRAYSIZE);
  709. EXPECT_EQ(unittest::SPARSE_E, unittest::TestSparseEnum_MIN);
  710. EXPECT_EQ(unittest::SPARSE_C, unittest::TestSparseEnum_MAX);
  711. EXPECT_EQ(12589235, unittest::TestSparseEnum_ARRAYSIZE);
  712. // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE.
  713. void* null_pointer = 0; // NULL may be integer-type, not pointer-type.
  714. EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MIN);
  715. EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MAX);
  716. EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
  717. EXPECT_NE(null_pointer, &unittest::ForeignEnum_MIN);
  718. EXPECT_NE(null_pointer, &unittest::ForeignEnum_MAX);
  719. EXPECT_NE(null_pointer, &unittest::ForeignEnum_ARRAYSIZE);
  720. // Make sure we can use _MIN, _MAX and _ARRAYSIZE as switch cases.
  721. switch (unittest::SPARSE_A) {
  722. case unittest::TestSparseEnum_MIN:
  723. case unittest::TestSparseEnum_MAX:
  724. case unittest::TestSparseEnum_ARRAYSIZE:
  725. break;
  726. default:
  727. break;
  728. }
  729. }
  730. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  731. TEST(GeneratedEnumTest, Name) {
  732. // "Names" in the presence of dup values are a bit arbitrary.
  733. EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO1));
  734. EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO2));
  735. EXPECT_EQ("SPARSE_A", unittest::TestSparseEnum_Name(unittest::SPARSE_A));
  736. EXPECT_EQ("SPARSE_B", unittest::TestSparseEnum_Name(unittest::SPARSE_B));
  737. EXPECT_EQ("SPARSE_C", unittest::TestSparseEnum_Name(unittest::SPARSE_C));
  738. EXPECT_EQ("SPARSE_D", unittest::TestSparseEnum_Name(unittest::SPARSE_D));
  739. EXPECT_EQ("SPARSE_E", unittest::TestSparseEnum_Name(unittest::SPARSE_E));
  740. EXPECT_EQ("SPARSE_F", unittest::TestSparseEnum_Name(unittest::SPARSE_F));
  741. EXPECT_EQ("SPARSE_G", unittest::TestSparseEnum_Name(unittest::SPARSE_G));
  742. }
  743. TEST(GeneratedEnumTest, Parse) {
  744. unittest::TestEnumWithDupValue dup_value = unittest::FOO1;
  745. EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO1", &dup_value));
  746. EXPECT_EQ(unittest::FOO1, dup_value);
  747. EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO2", &dup_value));
  748. EXPECT_EQ(unittest::FOO2, dup_value);
  749. EXPECT_FALSE(unittest::TestEnumWithDupValue_Parse("FOO", &dup_value));
  750. }
  751. TEST(GeneratedEnumTest, GetEnumDescriptor) {
  752. EXPECT_EQ(unittest::TestAllTypes::NestedEnum_descriptor(),
  753. GetEnumDescriptor<unittest::TestAllTypes::NestedEnum>());
  754. EXPECT_EQ(unittest::ForeignEnum_descriptor(),
  755. GetEnumDescriptor<unittest::ForeignEnum>());
  756. EXPECT_EQ(unittest::TestEnumWithDupValue_descriptor(),
  757. GetEnumDescriptor<unittest::TestEnumWithDupValue>());
  758. EXPECT_EQ(unittest::TestSparseEnum_descriptor(),
  759. GetEnumDescriptor<unittest::TestSparseEnum>());
  760. }
  761. #endif // PROTOBUF_TEST_NO_DESCRIPTORS
  762. // ===================================================================
  763. #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
  764. // Support code for testing services.
  765. class GeneratedServiceTest : public testing::Test {
  766. protected:
  767. class MockTestService : public unittest::TestService {
  768. public:
  769. MockTestService()
  770. : called_(false),
  771. method_(""),
  772. controller_(NULL),
  773. request_(NULL),
  774. response_(NULL),
  775. done_(NULL) {}
  776. ~MockTestService() {}
  777. void Reset() { called_ = false; }
  778. // implements TestService ----------------------------------------
  779. void Foo(RpcController* controller,
  780. const unittest::FooRequest* request,
  781. unittest::FooResponse* response,
  782. Closure* done) {
  783. ASSERT_FALSE(called_);
  784. called_ = true;
  785. method_ = "Foo";
  786. controller_ = controller;
  787. request_ = request;
  788. response_ = response;
  789. done_ = done;
  790. }
  791. void Bar(RpcController* controller,
  792. const unittest::BarRequest* request,
  793. unittest::BarResponse* response,
  794. Closure* done) {
  795. ASSERT_FALSE(called_);
  796. called_ = true;
  797. method_ = "Bar";
  798. controller_ = controller;
  799. request_ = request;
  800. response_ = response;
  801. done_ = done;
  802. }
  803. // ---------------------------------------------------------------
  804. bool called_;
  805. string method_;
  806. RpcController* controller_;
  807. const Message* request_;
  808. Message* response_;
  809. Closure* done_;
  810. };
  811. class MockRpcChannel : public RpcChannel {
  812. public:
  813. MockRpcChannel()
  814. : called_(false),
  815. method_(NULL),
  816. controller_(NULL),
  817. request_(NULL),
  818. response_(NULL),
  819. done_(NULL),
  820. destroyed_(NULL) {}
  821. ~MockRpcChannel() {
  822. if (destroyed_ != NULL) *destroyed_ = true;
  823. }
  824. void Reset() { called_ = false; }
  825. // implements TestService ----------------------------------------
  826. void CallMethod(const MethodDescriptor* method,
  827. RpcController* controller,
  828. const Message* request,
  829. Message* response,
  830. Closure* done) {
  831. ASSERT_FALSE(called_);
  832. called_ = true;
  833. method_ = method;
  834. controller_ = controller;
  835. request_ = request;
  836. response_ = response;
  837. done_ = done;
  838. }
  839. // ---------------------------------------------------------------
  840. bool called_;
  841. const MethodDescriptor* method_;
  842. RpcController* controller_;
  843. const Message* request_;
  844. Message* response_;
  845. Closure* done_;
  846. bool* destroyed_;
  847. };
  848. class MockController : public RpcController {
  849. public:
  850. void Reset() {
  851. ADD_FAILURE() << "Reset() not expected during this test.";
  852. }
  853. bool Failed() const {
  854. ADD_FAILURE() << "Failed() not expected during this test.";
  855. return false;
  856. }
  857. string ErrorText() const {
  858. ADD_FAILURE() << "ErrorText() not expected during this test.";
  859. return "";
  860. }
  861. void StartCancel() {
  862. ADD_FAILURE() << "StartCancel() not expected during this test.";
  863. }
  864. void SetFailed(const string& reason) {
  865. ADD_FAILURE() << "SetFailed() not expected during this test.";
  866. }
  867. bool IsCanceled() const {
  868. ADD_FAILURE() << "IsCanceled() not expected during this test.";
  869. return false;
  870. }
  871. void NotifyOnCancel(Closure* callback) {
  872. ADD_FAILURE() << "NotifyOnCancel() not expected during this test.";
  873. }
  874. };
  875. GeneratedServiceTest()
  876. : descriptor_(unittest::TestService::descriptor()),
  877. foo_(descriptor_->FindMethodByName("Foo")),
  878. bar_(descriptor_->FindMethodByName("Bar")),
  879. stub_(&mock_channel_),
  880. done_(NewPermanentCallback(&DoNothing)) {}
  881. virtual void SetUp() {
  882. ASSERT_TRUE(foo_ != NULL);
  883. ASSERT_TRUE(bar_ != NULL);
  884. }
  885. const ServiceDescriptor* descriptor_;
  886. const MethodDescriptor* foo_;
  887. const MethodDescriptor* bar_;
  888. MockTestService mock_service_;
  889. MockController mock_controller_;
  890. MockRpcChannel mock_channel_;
  891. unittest::TestService::Stub stub_;
  892. // Just so we don't have to re-define these with every test.
  893. unittest::FooRequest foo_request_;
  894. unittest::FooResponse foo_response_;
  895. unittest::BarRequest bar_request_;
  896. unittest::BarResponse bar_response_;
  897. scoped_ptr<Closure> done_;
  898. };
  899. TEST_F(GeneratedServiceTest, GetDescriptor) {
  900. // Test that GetDescriptor() works.
  901. EXPECT_EQ(descriptor_, mock_service_.GetDescriptor());
  902. }
  903. TEST_F(GeneratedServiceTest, GetChannel) {
  904. EXPECT_EQ(&mock_channel_, stub_.channel());
  905. }
  906. TEST_F(GeneratedServiceTest, OwnsChannel) {
  907. MockRpcChannel* channel = new MockRpcChannel;
  908. bool destroyed = false;
  909. channel->destroyed_ = &destroyed;
  910. {
  911. unittest::TestService::Stub owning_stub(channel,
  912. Service::STUB_OWNS_CHANNEL);
  913. EXPECT_FALSE(destroyed);
  914. }
  915. EXPECT_TRUE(destroyed);
  916. }
  917. TEST_F(GeneratedServiceTest, CallMethod) {
  918. // Test that CallMethod() works.
  919. // Call Foo() via CallMethod().
  920. mock_service_.CallMethod(foo_, &mock_controller_,
  921. &foo_request_, &foo_response_, done_.get());
  922. ASSERT_TRUE(mock_service_.called_);
  923. EXPECT_EQ("Foo" , mock_service_.method_ );
  924. EXPECT_EQ(&mock_controller_, mock_service_.controller_);
  925. EXPECT_EQ(&foo_request_ , mock_service_.request_ );
  926. EXPECT_EQ(&foo_response_ , mock_service_.response_ );
  927. EXPECT_EQ(done_.get() , mock_service_.done_ );
  928. // Try again, but call Bar() instead.
  929. mock_service_.Reset();
  930. mock_service_.CallMethod(bar_, &mock_controller_,
  931. &bar_request_, &bar_response_, done_.get());
  932. ASSERT_TRUE(mock_service_.called_);
  933. EXPECT_EQ("Bar", mock_service_.method_);
  934. }
  935. TEST_F(GeneratedServiceTest, CallMethodTypeFailure) {
  936. // Verify death if we call Foo() with Bar's message types.
  937. #ifdef GTEST_HAS_DEATH_TEST // death tests do not work on Windows yet
  938. EXPECT_DEBUG_DEATH(
  939. mock_service_.CallMethod(foo_, &mock_controller_,
  940. &foo_request_, &bar_response_, done_.get()),
  941. "dynamic_cast");
  942. mock_service_.Reset();
  943. EXPECT_DEBUG_DEATH(
  944. mock_service_.CallMethod(foo_, &mock_controller_,
  945. &bar_request_, &foo_response_, done_.get()),
  946. "dynamic_cast");
  947. #endif // GTEST_HAS_DEATH_TEST
  948. }
  949. TEST_F(GeneratedServiceTest, GetPrototypes) {
  950. // Test Get{Request,Response}Prototype() methods.
  951. EXPECT_EQ(&unittest::FooRequest::default_instance(),
  952. &mock_service_.GetRequestPrototype(foo_));
  953. EXPECT_EQ(&unittest::BarRequest::default_instance(),
  954. &mock_service_.GetRequestPrototype(bar_));
  955. EXPECT_EQ(&unittest::FooResponse::default_instance(),
  956. &mock_service_.GetResponsePrototype(foo_));
  957. EXPECT_EQ(&unittest::BarResponse::default_instance(),
  958. &mock_service_.GetResponsePrototype(bar_));
  959. }
  960. TEST_F(GeneratedServiceTest, Stub) {
  961. // Test that the stub class works.
  962. // Call Foo() via the stub.
  963. stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get());
  964. ASSERT_TRUE(mock_channel_.called_);
  965. EXPECT_EQ(foo_ , mock_channel_.method_ );
  966. EXPECT_EQ(&mock_controller_, mock_channel_.controller_);
  967. EXPECT_EQ(&foo_request_ , mock_channel_.request_ );
  968. EXPECT_EQ(&foo_response_ , mock_channel_.response_ );
  969. EXPECT_EQ(done_.get() , mock_channel_.done_ );
  970. // Call Bar() via the stub.
  971. mock_channel_.Reset();
  972. stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get());
  973. ASSERT_TRUE(mock_channel_.called_);
  974. EXPECT_EQ(bar_, mock_channel_.method_);
  975. }
  976. TEST_F(GeneratedServiceTest, NotImplemented) {
  977. // Test that failing to implement a method of a service causes it to fail
  978. // with a "not implemented" error message.
  979. // A service which doesn't implement any methods.
  980. class UnimplementedService : public unittest::TestService {
  981. public:
  982. UnimplementedService() {}
  983. };
  984. UnimplementedService unimplemented_service;
  985. // And a controller which expects to get a "not implemented" error.
  986. class ExpectUnimplementedController : public MockController {
  987. public:
  988. ExpectUnimplementedController() : called_(false) {}
  989. void SetFailed(const string& reason) {
  990. EXPECT_FALSE(called_);
  991. called_ = true;
  992. EXPECT_EQ("Method Foo() not implemented.", reason);
  993. }
  994. bool called_;
  995. };
  996. ExpectUnimplementedController controller;
  997. // Call Foo.
  998. unimplemented_service.Foo(&controller, &foo_request_, &foo_response_,
  999. done_.get());
  1000. EXPECT_TRUE(controller.called_);
  1001. }
  1002. } // namespace cpp_unittest
  1003. } // namespace cpp
  1004. } // namespace compiler
  1005. namespace no_generic_services_test {
  1006. // Verify that no class called "TestService" was defined in
  1007. // unittest_no_generic_services.pb.h by defining a different type by the same
  1008. // name. If such a service was generated, this will not compile.
  1009. struct TestService {
  1010. int i;
  1011. };
  1012. }
  1013. namespace compiler {
  1014. namespace cpp {
  1015. namespace cpp_unittest {
  1016. TEST_F(GeneratedServiceTest, NoGenericServices) {
  1017. // Verify that non-services in unittest_no_generic_services.proto were
  1018. // generated.
  1019. no_generic_services_test::TestMessage message;
  1020. message.set_a(1);
  1021. message.SetExtension(no_generic_services_test::test_extension, 123);
  1022. no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
  1023. EXPECT_EQ(e, 1);
  1024. // Verify that a ServiceDescriptor is generated for the service even if the
  1025. // class itself is not.
  1026. const FileDescriptor* file =
  1027. no_generic_services_test::TestMessage::descriptor()->file();
  1028. ASSERT_EQ(1, file->service_count());
  1029. EXPECT_EQ("TestService", file->service(0)->name());
  1030. ASSERT_EQ(1, file->service(0)->method_count());
  1031. EXPECT_EQ("Foo", file->service(0)->method(0)->name());
  1032. }
  1033. #endif // !PROTOBUF_TEST_NO_DESCRIPTORS
  1034. // ===================================================================
  1035. // This test must run last. It verifies that descriptors were or were not
  1036. // initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined.
  1037. // When this is defined, we skip all tests which are expected to trigger
  1038. // descriptor initialization. This verifies that everything else still works
  1039. // if descriptors are not initialized.
  1040. TEST(DescriptorInitializationTest, Initialized) {
  1041. #ifdef PROTOBUF_TEST_NO_DESCRIPTORS
  1042. bool should_have_descriptors = false;
  1043. #else
  1044. bool should_have_descriptors = true;
  1045. #endif
  1046. EXPECT_EQ(should_have_descriptors,
  1047. DescriptorPool::generated_pool()->InternalIsFileLoaded(
  1048. "google/protobuf/unittest.proto"));
  1049. }
  1050. } // namespace cpp_unittest
  1051. } // namespace cpp
  1052. } // namespace compiler
  1053. } // namespace protobuf
  1054. } // namespace google