PageRenderTime 209ms CodeModel.GetById 35ms RepoModel.GetById 1ms app.codeStats 0ms

/src/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.cc

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