PageRenderTime 57ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/include/google/protobuf/message_unittest.cc

https://gitlab.com/bugdone/demoinfogo_windows_build
C++ | 427 lines | 290 code | 74 blank | 63 comment | 6 complexity | 89cd123a900ad5a5b32c9312fb4e136a MD5 | raw file
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: kenton@google.com (Kenton Varda)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. #include <google/protobuf/message.h>
  34. #include <sys/types.h>
  35. #include <sys/stat.h>
  36. #include <fcntl.h>
  37. #ifdef _MSC_VER
  38. #include <io.h>
  39. #else
  40. #include <unistd.h>
  41. #endif
  42. #include <sstream>
  43. #include <fstream>
  44. #include <google/protobuf/io/zero_copy_stream_impl.h>
  45. #include <google/protobuf/io/coded_stream.h>
  46. #include <google/protobuf/descriptor.h>
  47. #include <google/protobuf/descriptor.pb.h>
  48. #include <google/protobuf/unittest.pb.h>
  49. #include <google/protobuf/test_util.h>
  50. #include <google/protobuf/stubs/common.h>
  51. #include <google/protobuf/testing/googletest.h>
  52. #include <gtest/gtest.h>
  53. namespace google {
  54. namespace protobuf {
  55. #ifndef O_BINARY
  56. #ifdef _O_BINARY
  57. #define O_BINARY _O_BINARY
  58. #else
  59. #define O_BINARY 0 // If this isn't defined, the platform doesn't need it.
  60. #endif
  61. #endif
  62. TEST(MessageTest, SerializeHelpers) {
  63. // TODO(kenton): Test more helpers? They're all two-liners so it seems
  64. // like a waste of time.
  65. protobuf_unittest::TestAllTypes message;
  66. TestUtil::SetAllFields(&message);
  67. stringstream stream;
  68. string str1("foo");
  69. string str2("bar");
  70. EXPECT_TRUE(message.SerializeToString(&str1));
  71. EXPECT_TRUE(message.AppendToString(&str2));
  72. EXPECT_TRUE(message.SerializeToOstream(&stream));
  73. EXPECT_EQ(str1.size() + 3, str2.size());
  74. EXPECT_EQ("bar", str2.substr(0, 3));
  75. // Don't use EXPECT_EQ because we don't want to dump raw binary data to
  76. // stdout.
  77. EXPECT_TRUE(str2.substr(3) == str1);
  78. // GCC gives some sort of error if we try to just do stream.str() == str1.
  79. string temp = stream.str();
  80. EXPECT_TRUE(temp == str1);
  81. EXPECT_TRUE(message.SerializeAsString() == str1);
  82. }
  83. TEST(MessageTest, SerializeToBrokenOstream) {
  84. ofstream out;
  85. protobuf_unittest::TestAllTypes message;
  86. message.set_optional_int32(123);
  87. EXPECT_FALSE(message.SerializeToOstream(&out));
  88. }
  89. TEST(MessageTest, ParseFromFileDescriptor) {
  90. string filename = TestSourceDir() +
  91. "/google/protobuf/testdata/golden_message";
  92. int file = open(filename.c_str(), O_RDONLY | O_BINARY);
  93. unittest::TestAllTypes message;
  94. EXPECT_TRUE(message.ParseFromFileDescriptor(file));
  95. TestUtil::ExpectAllFieldsSet(message);
  96. EXPECT_GE(close(file), 0);
  97. }
  98. TEST(MessageTest, ParsePackedFromFileDescriptor) {
  99. string filename =
  100. TestSourceDir() +
  101. "/google/protobuf/testdata/golden_packed_fields_message";
  102. int file = open(filename.c_str(), O_RDONLY | O_BINARY);
  103. unittest::TestPackedTypes message;
  104. EXPECT_TRUE(message.ParseFromFileDescriptor(file));
  105. TestUtil::ExpectPackedFieldsSet(message);
  106. EXPECT_GE(close(file), 0);
  107. }
  108. TEST(MessageTest, ParseHelpers) {
  109. // TODO(kenton): Test more helpers? They're all two-liners so it seems
  110. // like a waste of time.
  111. string data;
  112. {
  113. // Set up.
  114. protobuf_unittest::TestAllTypes message;
  115. TestUtil::SetAllFields(&message);
  116. message.SerializeToString(&data);
  117. }
  118. {
  119. // Test ParseFromString.
  120. protobuf_unittest::TestAllTypes message;
  121. EXPECT_TRUE(message.ParseFromString(data));
  122. TestUtil::ExpectAllFieldsSet(message);
  123. }
  124. {
  125. // Test ParseFromIstream.
  126. protobuf_unittest::TestAllTypes message;
  127. stringstream stream(data);
  128. EXPECT_TRUE(message.ParseFromIstream(&stream));
  129. EXPECT_TRUE(stream.eof());
  130. TestUtil::ExpectAllFieldsSet(message);
  131. }
  132. {
  133. // Test ParseFromBoundedZeroCopyStream.
  134. string data_with_junk(data);
  135. data_with_junk.append("some junk on the end");
  136. io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size());
  137. protobuf_unittest::TestAllTypes message;
  138. EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size()));
  139. TestUtil::ExpectAllFieldsSet(message);
  140. }
  141. {
  142. // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if
  143. // EOF is reached before the expected number of bytes.
  144. io::ArrayInputStream stream(data.data(), data.size());
  145. protobuf_unittest::TestAllTypes message;
  146. EXPECT_FALSE(
  147. message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1));
  148. }
  149. }
  150. TEST(MessageTest, ParseFailsIfNotInitialized) {
  151. unittest::TestRequired message;
  152. vector<string> errors;
  153. {
  154. ScopedMemoryLog log;
  155. EXPECT_FALSE(message.ParseFromString(""));
  156. errors = log.GetMessages(ERROR);
  157. }
  158. ASSERT_EQ(1, errors.size());
  159. EXPECT_EQ("Can't parse message of type \"protobuf_unittest.TestRequired\" "
  160. "because it is missing required fields: a, b, c",
  161. errors[0]);
  162. }
  163. TEST(MessageTest, BypassInitializationCheckOnParse) {
  164. unittest::TestRequired message;
  165. io::ArrayInputStream raw_input(NULL, 0);
  166. io::CodedInputStream input(&raw_input);
  167. EXPECT_TRUE(message.MergePartialFromCodedStream(&input));
  168. }
  169. TEST(MessageTest, InitializationErrorString) {
  170. unittest::TestRequired message;
  171. EXPECT_EQ("a, b, c", message.InitializationErrorString());
  172. }
  173. #ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet.
  174. TEST(MessageTest, SerializeFailsIfNotInitialized) {
  175. unittest::TestRequired message;
  176. string data;
  177. EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)),
  178. "Can't serialize message of type \"protobuf_unittest.TestRequired\" because "
  179. "it is missing required fields: a, b, c");
  180. }
  181. TEST(MessageTest, CheckInitialized) {
  182. unittest::TestRequired message;
  183. EXPECT_DEATH(message.CheckInitialized(),
  184. "Message of type \"protobuf_unittest.TestRequired\" is missing required "
  185. "fields: a, b, c");
  186. }
  187. TEST(MessageTest, CheckOverflow) {
  188. unittest::TestAllTypes message;
  189. // Create a message with size just over 2GB. This triggers integer overflow
  190. // when computing message size.
  191. const string data(1024, 'x');
  192. Cord one_megabyte;
  193. for (int i = 0; i < 1024; i++) {
  194. one_megabyte.Append(data);
  195. }
  196. for (int i = 0; i < 2 * 1024 + 1; ++i) {
  197. message.add_repeated_cord()->CopyFrom(one_megabyte);
  198. }
  199. Cord serialized;
  200. EXPECT_FALSE(message.AppendToCord(&serialized));
  201. }
  202. #endif // PROTOBUF_HAS_DEATH_TEST
  203. TEST(MessageTest, BypassInitializationCheckOnSerialize) {
  204. unittest::TestRequired message;
  205. io::ArrayOutputStream raw_output(NULL, 0);
  206. io::CodedOutputStream output(&raw_output);
  207. EXPECT_TRUE(message.SerializePartialToCodedStream(&output));
  208. }
  209. TEST(MessageTest, FindInitializationErrors) {
  210. unittest::TestRequired message;
  211. vector<string> errors;
  212. message.FindInitializationErrors(&errors);
  213. ASSERT_EQ(3, errors.size());
  214. EXPECT_EQ("a", errors[0]);
  215. EXPECT_EQ("b", errors[1]);
  216. EXPECT_EQ("c", errors[2]);
  217. }
  218. TEST(MessageTest, ParseFailsOnInvalidMessageEnd) {
  219. unittest::TestAllTypes message;
  220. // Control case.
  221. EXPECT_TRUE(message.ParseFromArray("", 0));
  222. // The byte is a valid varint, but not a valid tag (zero).
  223. EXPECT_FALSE(message.ParseFromArray("\0", 1));
  224. // The byte is a malformed varint.
  225. EXPECT_FALSE(message.ParseFromArray("\200", 1));
  226. // The byte is an endgroup tag, but we aren't parsing a group.
  227. EXPECT_FALSE(message.ParseFromArray("\014", 1));
  228. }
  229. namespace {
  230. void ExpectMessageMerged(const unittest::TestAllTypes& message) {
  231. EXPECT_EQ(3, message.optional_int32());
  232. EXPECT_EQ(2, message.optional_int64());
  233. EXPECT_EQ("hello", message.optional_string());
  234. }
  235. void AssignParsingMergeMessages(
  236. unittest::TestAllTypes* msg1,
  237. unittest::TestAllTypes* msg2,
  238. unittest::TestAllTypes* msg3) {
  239. msg1->set_optional_int32(1);
  240. msg2->set_optional_int64(2);
  241. msg3->set_optional_int32(3);
  242. msg3->set_optional_string("hello");
  243. }
  244. } // namespace
  245. // Test that if an optional or required message/group field appears multiple
  246. // times in the input, they need to be merged.
  247. TEST(MessageTest, ParsingMerge) {
  248. unittest::TestParsingMerge::RepeatedFieldsGenerator generator;
  249. unittest::TestAllTypes* msg1;
  250. unittest::TestAllTypes* msg2;
  251. unittest::TestAllTypes* msg3;
  252. #define ASSIGN_REPEATED_FIELD(FIELD) \
  253. msg1 = generator.add_##FIELD(); \
  254. msg2 = generator.add_##FIELD(); \
  255. msg3 = generator.add_##FIELD(); \
  256. AssignParsingMergeMessages(msg1, msg2, msg3)
  257. ASSIGN_REPEATED_FIELD(field1);
  258. ASSIGN_REPEATED_FIELD(field2);
  259. ASSIGN_REPEATED_FIELD(field3);
  260. ASSIGN_REPEATED_FIELD(ext1);
  261. ASSIGN_REPEATED_FIELD(ext2);
  262. #undef ASSIGN_REPEATED_FIELD
  263. #define ASSIGN_REPEATED_GROUP(FIELD) \
  264. msg1 = generator.add_##FIELD()->mutable_field1(); \
  265. msg2 = generator.add_##FIELD()->mutable_field1(); \
  266. msg3 = generator.add_##FIELD()->mutable_field1(); \
  267. AssignParsingMergeMessages(msg1, msg2, msg3)
  268. ASSIGN_REPEATED_GROUP(group1);
  269. ASSIGN_REPEATED_GROUP(group2);
  270. #undef ASSIGN_REPEATED_GROUP
  271. string buffer;
  272. generator.SerializeToString(&buffer);
  273. unittest::TestParsingMerge parsing_merge;
  274. parsing_merge.ParseFromString(buffer);
  275. // Required and optional fields should be merged.
  276. ExpectMessageMerged(parsing_merge.required_all_types());
  277. ExpectMessageMerged(parsing_merge.optional_all_types());
  278. ExpectMessageMerged(
  279. parsing_merge.optionalgroup().optional_group_all_types());
  280. ExpectMessageMerged(
  281. parsing_merge.GetExtension(unittest::TestParsingMerge::optional_ext));
  282. // Repeated fields should not be merged.
  283. EXPECT_EQ(3, parsing_merge.repeated_all_types_size());
  284. EXPECT_EQ(3, parsing_merge.repeatedgroup_size());
  285. EXPECT_EQ(3, parsing_merge.ExtensionSize(
  286. unittest::TestParsingMerge::repeated_ext));
  287. }
  288. TEST(MessageTest, MergeFrom) {
  289. unittest::TestAllTypes source;
  290. unittest::TestAllTypes dest;
  291. // Optional fields
  292. source.set_optional_int32(1); // only source
  293. source.set_optional_int64(2); // both source and dest
  294. dest.set_optional_int64(3);
  295. dest.set_optional_uint32(4); // only dest
  296. // Optional fields with defaults
  297. source.set_default_int32(13); // only source
  298. source.set_default_int64(14); // both source and dest
  299. dest.set_default_int64(15);
  300. dest.set_default_uint32(16); // only dest
  301. // Repeated fields
  302. source.add_repeated_int32(5); // only source
  303. source.add_repeated_int32(6);
  304. source.add_repeated_int64(7); // both source and dest
  305. source.add_repeated_int64(8);
  306. dest.add_repeated_int64(9);
  307. dest.add_repeated_int64(10);
  308. dest.add_repeated_uint32(11); // only dest
  309. dest.add_repeated_uint32(12);
  310. dest.MergeFrom(source);
  311. // Optional fields: source overwrites dest if source is specified
  312. EXPECT_EQ(1, dest.optional_int32()); // only source: use source
  313. EXPECT_EQ(2, dest.optional_int64()); // source and dest: use source
  314. EXPECT_EQ(4, dest.optional_uint32()); // only dest: use dest
  315. EXPECT_EQ(0, dest.optional_uint64()); // neither: use default
  316. // Optional fields with defaults
  317. EXPECT_EQ(13, dest.default_int32()); // only source: use source
  318. EXPECT_EQ(14, dest.default_int64()); // source and dest: use source
  319. EXPECT_EQ(16, dest.default_uint32()); // only dest: use dest
  320. EXPECT_EQ(44, dest.default_uint64()); // neither: use default
  321. // Repeated fields: concatenate source onto the end of dest
  322. ASSERT_EQ(2, dest.repeated_int32_size());
  323. EXPECT_EQ(5, dest.repeated_int32(0));
  324. EXPECT_EQ(6, dest.repeated_int32(1));
  325. ASSERT_EQ(4, dest.repeated_int64_size());
  326. EXPECT_EQ(9, dest.repeated_int64(0));
  327. EXPECT_EQ(10, dest.repeated_int64(1));
  328. EXPECT_EQ(7, dest.repeated_int64(2));
  329. EXPECT_EQ(8, dest.repeated_int64(3));
  330. ASSERT_EQ(2, dest.repeated_uint32_size());
  331. EXPECT_EQ(11, dest.repeated_uint32(0));
  332. EXPECT_EQ(12, dest.repeated_uint32(1));
  333. ASSERT_EQ(0, dest.repeated_uint64_size());
  334. }
  335. TEST(MessageFactoryTest, GeneratedFactoryLookup) {
  336. EXPECT_EQ(
  337. MessageFactory::generated_factory()->GetPrototype(
  338. protobuf_unittest::TestAllTypes::descriptor()),
  339. &protobuf_unittest::TestAllTypes::default_instance());
  340. }
  341. TEST(MessageFactoryTest, GeneratedFactoryUnknownType) {
  342. // Construct a new descriptor.
  343. DescriptorPool pool;
  344. FileDescriptorProto file;
  345. file.set_name("foo.proto");
  346. file.add_message_type()->set_name("Foo");
  347. const Descriptor* descriptor = pool.BuildFile(file)->message_type(0);
  348. // Trying to construct it should return NULL.
  349. EXPECT_TRUE(
  350. MessageFactory::generated_factory()->GetPrototype(descriptor) == NULL);
  351. }
  352. } // namespace protobuf
  353. } // namespace google