message_unittest.inc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: kenton@google.com (Kenton Varda)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. //
  34. // This file needs to be included as .inc as it depends on certain macros being
  35. // defined prior to its inclusion.
  36. #include <fcntl.h>
  37. #include <sys/stat.h>
  38. #include <sys/types.h>
  39. #include <google/protobuf/message.h>
  40. #ifndef _MSC_VER
  41. #include <unistd.h>
  42. #endif
  43. #include <fstream>
  44. #include <sstream>
  45. #include <google/protobuf/stubs/logging.h>
  46. #include <google/protobuf/stubs/common.h>
  47. #include <google/protobuf/test_util2.h>
  48. #include <google/protobuf/io/coded_stream.h>
  49. #include <google/protobuf/io/zero_copy_stream.h>
  50. #include <google/protobuf/io/zero_copy_stream_impl.h>
  51. #include <google/protobuf/descriptor.pb.h>
  52. #include <google/protobuf/arena.h>
  53. #include <google/protobuf/descriptor.h>
  54. #include <google/protobuf/generated_message_reflection.h>
  55. #include <google/protobuf/testing/googletest.h>
  56. #include <gtest/gtest.h>
  57. #include <google/protobuf/stubs/logging.h>
  58. #include <google/protobuf/io/io_win32.h>
  59. namespace google {
  60. namespace protobuf {
  61. #if defined(_WIN32)
  62. // DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
  63. // them like we do below.
  64. using google::protobuf::io::win32::close;
  65. using google::protobuf::io::win32::open;
  66. #endif
  67. #ifndef O_BINARY
  68. #ifdef _O_BINARY
  69. #define O_BINARY _O_BINARY
  70. #else
  71. #define O_BINARY 0 // If this isn't defined, the platform doesn't need it.
  72. #endif
  73. #endif
  74. TEST(MESSAGE_TEST_NAME, SerializeHelpers) {
  75. // TODO(kenton): Test more helpers? They're all two-liners so it seems
  76. // like a waste of time.
  77. UNITTEST::TestAllTypes message;
  78. TestUtil::SetAllFields(&message);
  79. std::stringstream stream;
  80. std::string str1("foo");
  81. std::string str2("bar");
  82. EXPECT_TRUE(message.SerializeToString(&str1));
  83. EXPECT_TRUE(message.AppendToString(&str2));
  84. EXPECT_TRUE(message.SerializeToOstream(&stream));
  85. EXPECT_EQ(str1.size() + 3, str2.size());
  86. EXPECT_EQ("bar", str2.substr(0, 3));
  87. // Don't use EXPECT_EQ because we don't want to dump raw binary data to
  88. // stdout.
  89. EXPECT_TRUE(str2.substr(3) == str1);
  90. // GCC gives some sort of error if we try to just do stream.str() == str1.
  91. std::string temp = stream.str();
  92. EXPECT_TRUE(temp == str1);
  93. EXPECT_TRUE(message.SerializeAsString() == str1);
  94. }
  95. TEST(MESSAGE_TEST_NAME, SerializeToBrokenOstream) {
  96. std::ofstream out;
  97. UNITTEST::TestAllTypes message;
  98. message.set_optional_int32(123);
  99. EXPECT_FALSE(message.SerializeToOstream(&out));
  100. }
  101. TEST(MESSAGE_TEST_NAME, ParseFromFileDescriptor) {
  102. std::string filename =
  103. TestUtil::GetTestDataPath("net/proto2/internal/testdata/golden_message");
  104. int file = open(filename.c_str(), O_RDONLY | O_BINARY);
  105. ASSERT_GE(file, 0);
  106. UNITTEST::TestAllTypes message;
  107. EXPECT_TRUE(message.ParseFromFileDescriptor(file));
  108. TestUtil::ExpectAllFieldsSet(message);
  109. EXPECT_GE(close(file), 0);
  110. }
  111. TEST(MESSAGE_TEST_NAME, ParsePackedFromFileDescriptor) {
  112. std::string filename = TestUtil::GetTestDataPath(
  113. "net/proto2/internal/testdata/golden_packed_fields_message");
  114. int file = open(filename.c_str(), O_RDONLY | O_BINARY);
  115. ASSERT_GE(file, 0);
  116. UNITTEST::TestPackedTypes message;
  117. EXPECT_TRUE(message.ParseFromFileDescriptor(file));
  118. TestUtil::ExpectPackedFieldsSet(message);
  119. EXPECT_GE(close(file), 0);
  120. }
  121. TEST(MESSAGE_TEST_NAME, ParseHelpers) {
  122. // TODO(kenton): Test more helpers? They're all two-liners so it seems
  123. // like a waste of time.
  124. std::string data;
  125. {
  126. // Set up.
  127. UNITTEST::TestAllTypes message;
  128. TestUtil::SetAllFields(&message);
  129. message.SerializeToString(&data);
  130. }
  131. {
  132. // Test ParseFromString.
  133. UNITTEST::TestAllTypes message;
  134. EXPECT_TRUE(message.ParseFromString(data));
  135. TestUtil::ExpectAllFieldsSet(message);
  136. }
  137. {
  138. // Test ParseFromIstream.
  139. UNITTEST::TestAllTypes message;
  140. std::stringstream stream(data);
  141. EXPECT_TRUE(message.ParseFromIstream(&stream));
  142. EXPECT_TRUE(stream.eof());
  143. TestUtil::ExpectAllFieldsSet(message);
  144. }
  145. {
  146. // Test ParseFromBoundedZeroCopyStream.
  147. std::string data_with_junk(data);
  148. data_with_junk.append("some junk on the end");
  149. io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size());
  150. UNITTEST::TestAllTypes message;
  151. EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size()));
  152. TestUtil::ExpectAllFieldsSet(message);
  153. }
  154. {
  155. // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if
  156. // EOF is reached before the expected number of bytes.
  157. io::ArrayInputStream stream(data.data(), data.size());
  158. UNITTEST::TestAllTypes message;
  159. EXPECT_FALSE(
  160. message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1));
  161. }
  162. }
  163. TEST(MESSAGE_TEST_NAME, ParseFailsIfNotInitialized) {
  164. UNITTEST::TestRequired message;
  165. std::vector<std::string> errors;
  166. {
  167. ScopedMemoryLog log;
  168. EXPECT_FALSE(message.ParseFromString(""));
  169. errors = log.GetMessages(ERROR);
  170. }
  171. ASSERT_EQ(1, errors.size());
  172. EXPECT_EQ(
  173. "Can't parse message of type \"" + std::string(UNITTEST_PACKAGE_NAME) +
  174. ".TestRequired\" because it is missing required fields: a, b, c",
  175. errors[0]);
  176. }
  177. TEST(MESSAGE_TEST_NAME, BypassInitializationCheckOnParse) {
  178. UNITTEST::TestRequired message;
  179. io::ArrayInputStream raw_input(nullptr, 0);
  180. io::CodedInputStream input(&raw_input);
  181. EXPECT_TRUE(message.MergePartialFromCodedStream(&input));
  182. }
  183. TEST(MESSAGE_TEST_NAME, InitializationErrorString) {
  184. UNITTEST::TestRequired message;
  185. EXPECT_EQ("a, b, c", message.InitializationErrorString());
  186. }
  187. TEST(MESSAGE_TEST_NAME, DynamicCastToGenerated) {
  188. UNITTEST::TestAllTypes test_all_types;
  189. Message* test_all_types_pointer = &test_all_types;
  190. EXPECT_EQ(&test_all_types, DynamicCastToGenerated<UNITTEST::TestAllTypes>(
  191. test_all_types_pointer));
  192. EXPECT_EQ(nullptr, DynamicCastToGenerated<UNITTEST::TestRequired>(
  193. test_all_types_pointer));
  194. const Message* test_all_types_pointer_const = &test_all_types;
  195. EXPECT_EQ(&test_all_types,
  196. DynamicCastToGenerated<const UNITTEST::TestAllTypes>(
  197. test_all_types_pointer_const));
  198. EXPECT_EQ(nullptr, DynamicCastToGenerated<const UNITTEST::TestRequired>(
  199. test_all_types_pointer_const));
  200. Message* test_all_types_pointer_nullptr = nullptr;
  201. EXPECT_EQ(nullptr, DynamicCastToGenerated<UNITTEST::TestAllTypes>(
  202. test_all_types_pointer_nullptr));
  203. }
  204. #ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet.
  205. TEST(MESSAGE_TEST_NAME, SerializeFailsIfNotInitialized) {
  206. UNITTEST::TestRequired message;
  207. std::string data;
  208. EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)),
  209. "Can't serialize message of type \"" +
  210. std::string(UNITTEST_PACKAGE_NAME) +
  211. ".TestRequired\" because "
  212. "it is missing required fields: a, b, c");
  213. }
  214. TEST(MESSAGE_TEST_NAME, CheckInitialized) {
  215. UNITTEST::TestRequired message;
  216. EXPECT_DEATH(message.CheckInitialized(),
  217. "Message of type \"" + std::string(UNITTEST_PACKAGE_NAME) +
  218. ".TestRequired\" is missing required "
  219. "fields: a, b, c");
  220. }
  221. #endif // PROTOBUF_HAS_DEATH_TEST
  222. namespace {
  223. // An input stream that repeats a std::string's content for a number of times.
  224. // It helps us create a really large input without consuming too much memory.
  225. // Used to test the parsing behavior when the input size exceeds 2G or close to
  226. // it.
  227. class RepeatedInputStream : public io::ZeroCopyInputStream {
  228. public:
  229. RepeatedInputStream(const std::string& data, size_t count)
  230. : data_(data), count_(count), position_(0), total_byte_count_(0) {}
  231. bool Next(const void** data, int* size) override {
  232. if (position_ == data_.size()) {
  233. if (--count_ == 0) {
  234. return false;
  235. }
  236. position_ = 0;
  237. }
  238. *data = &data_[position_];
  239. *size = static_cast<int>(data_.size() - position_);
  240. position_ = data_.size();
  241. total_byte_count_ += *size;
  242. return true;
  243. }
  244. void BackUp(int count) override {
  245. position_ -= static_cast<size_t>(count);
  246. total_byte_count_ -= count;
  247. }
  248. bool Skip(int count) override {
  249. while (count > 0) {
  250. const void* data;
  251. int size;
  252. if (!Next(&data, &size)) {
  253. break;
  254. }
  255. if (size >= count) {
  256. BackUp(size - count);
  257. return true;
  258. } else {
  259. count -= size;
  260. }
  261. }
  262. return false;
  263. }
  264. int64_t ByteCount() const override { return total_byte_count_; }
  265. private:
  266. std::string data_;
  267. size_t count_; // The number of strings that haven't been consumed.
  268. size_t position_; // Position in the std::string for the next read.
  269. int64 total_byte_count_;
  270. };
  271. } // namespace
  272. TEST(MESSAGE_TEST_NAME, TestParseMessagesCloseTo2G) {
  273. // Create a message with a large std::string field.
  274. std::string value = std::string(64 * 1024 * 1024, 'x');
  275. UNITTEST::TestAllTypes message;
  276. message.set_optional_string(value);
  277. // Repeat this message in the input stream to make the total input size
  278. // close to 2G.
  279. std::string data = message.SerializeAsString();
  280. size_t count = static_cast<size_t>(kint32max) / data.size();
  281. RepeatedInputStream input(data, count);
  282. // The parsing should succeed.
  283. UNITTEST::TestAllTypes result;
  284. EXPECT_TRUE(result.ParseFromZeroCopyStream(&input));
  285. // When there are multiple occurrences of a singular field, the last one
  286. // should win.
  287. EXPECT_EQ(value, result.optional_string());
  288. }
  289. TEST(MESSAGE_TEST_NAME, TestParseMessagesOver2G) {
  290. // Create a message with a large std::string field.
  291. std::string value = std::string(64 * 1024 * 1024, 'x');
  292. UNITTEST::TestAllTypes message;
  293. message.set_optional_string(value);
  294. // Repeat this message in the input stream to make the total input size
  295. // larger than 2G.
  296. std::string data = message.SerializeAsString();
  297. size_t count = static_cast<size_t>(kint32max) / data.size() + 1;
  298. RepeatedInputStream input(data, count);
  299. // The parsing should fail.
  300. UNITTEST::TestAllTypes result;
  301. EXPECT_FALSE(result.ParseFromZeroCopyStream(&input));
  302. }
  303. TEST(MESSAGE_TEST_NAME, BypassInitializationCheckOnSerialize) {
  304. UNITTEST::TestRequired message;
  305. io::ArrayOutputStream raw_output(nullptr, 0);
  306. io::CodedOutputStream output(&raw_output);
  307. EXPECT_TRUE(message.SerializePartialToCodedStream(&output));
  308. }
  309. TEST(MESSAGE_TEST_NAME, FindInitializationErrors) {
  310. UNITTEST::TestRequired message;
  311. std::vector<std::string> errors;
  312. message.FindInitializationErrors(&errors);
  313. ASSERT_EQ(3, errors.size());
  314. EXPECT_EQ("a", errors[0]);
  315. EXPECT_EQ("b", errors[1]);
  316. EXPECT_EQ("c", errors[2]);
  317. }
  318. TEST(MESSAGE_TEST_NAME, ParseFailsOnInvalidMessageEnd) {
  319. UNITTEST::TestAllTypes message;
  320. // Control case.
  321. EXPECT_TRUE(message.ParseFromArray("", 0));
  322. // The byte is a valid varint, but not a valid tag (zero).
  323. EXPECT_FALSE(message.ParseFromArray("\0", 1));
  324. // The byte is a malformed varint.
  325. EXPECT_FALSE(message.ParseFromArray("\200", 1));
  326. // The byte is an endgroup tag, but we aren't parsing a group.
  327. EXPECT_FALSE(message.ParseFromArray("\014", 1));
  328. }
  329. // Regression test for b/23630858
  330. TEST(MESSAGE_TEST_NAME, MessageIsStillValidAfterParseFails) {
  331. UNITTEST::TestAllTypes message;
  332. // 9 0xFFs for the "optional_uint64" field.
  333. std::string invalid_data = "\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF";
  334. EXPECT_FALSE(message.ParseFromString(invalid_data));
  335. message.Clear();
  336. EXPECT_EQ(0, message.optional_uint64());
  337. // invalid data for field "optional_string". Length prefix is 1 but no
  338. // payload.
  339. std::string invalid_string_data = "\x72\x01";
  340. {
  341. Arena arena;
  342. UNITTEST::TestAllTypes* arena_message =
  343. Arena::CreateMessage<UNITTEST::TestAllTypes>(&arena);
  344. EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data));
  345. arena_message->Clear();
  346. EXPECT_EQ("", arena_message->optional_string());
  347. }
  348. }
  349. namespace {
  350. void ExpectMessageMerged(const UNITTEST::TestAllTypes& message) {
  351. EXPECT_EQ(3, message.optional_int32());
  352. EXPECT_EQ(2, message.optional_int64());
  353. EXPECT_EQ("hello", message.optional_string());
  354. }
  355. void AssignParsingMergeMessages(UNITTEST::TestAllTypes* msg1,
  356. UNITTEST::TestAllTypes* msg2,
  357. UNITTEST::TestAllTypes* msg3) {
  358. msg1->set_optional_int32(1);
  359. msg2->set_optional_int64(2);
  360. msg3->set_optional_int32(3);
  361. msg3->set_optional_string("hello");
  362. }
  363. } // namespace
  364. // Test that if an optional or required message/group field appears multiple
  365. // times in the input, they need to be merged.
  366. TEST(MESSAGE_TEST_NAME, ParsingMerge) {
  367. UNITTEST::TestParsingMerge::RepeatedFieldsGenerator generator;
  368. UNITTEST::TestAllTypes* msg1;
  369. UNITTEST::TestAllTypes* msg2;
  370. UNITTEST::TestAllTypes* msg3;
  371. #define ASSIGN_REPEATED_FIELD(FIELD) \
  372. msg1 = generator.add_##FIELD(); \
  373. msg2 = generator.add_##FIELD(); \
  374. msg3 = generator.add_##FIELD(); \
  375. AssignParsingMergeMessages(msg1, msg2, msg3)
  376. ASSIGN_REPEATED_FIELD(field1);
  377. ASSIGN_REPEATED_FIELD(field2);
  378. ASSIGN_REPEATED_FIELD(field3);
  379. ASSIGN_REPEATED_FIELD(ext1);
  380. ASSIGN_REPEATED_FIELD(ext2);
  381. #undef ASSIGN_REPEATED_FIELD
  382. #define ASSIGN_REPEATED_GROUP(FIELD) \
  383. msg1 = generator.add_##FIELD()->mutable_field1(); \
  384. msg2 = generator.add_##FIELD()->mutable_field1(); \
  385. msg3 = generator.add_##FIELD()->mutable_field1(); \
  386. AssignParsingMergeMessages(msg1, msg2, msg3)
  387. ASSIGN_REPEATED_GROUP(group1);
  388. ASSIGN_REPEATED_GROUP(group2);
  389. #undef ASSIGN_REPEATED_GROUP
  390. std::string buffer;
  391. generator.SerializeToString(&buffer);
  392. UNITTEST::TestParsingMerge parsing_merge;
  393. parsing_merge.ParseFromString(buffer);
  394. // Required and optional fields should be merged.
  395. ExpectMessageMerged(parsing_merge.required_all_types());
  396. ExpectMessageMerged(parsing_merge.optional_all_types());
  397. ExpectMessageMerged(parsing_merge.optionalgroup().optional_group_all_types());
  398. ExpectMessageMerged(
  399. parsing_merge.GetExtension(UNITTEST::TestParsingMerge::optional_ext));
  400. // Repeated fields should not be merged.
  401. EXPECT_EQ(3, parsing_merge.repeated_all_types_size());
  402. EXPECT_EQ(3, parsing_merge.repeatedgroup_size());
  403. EXPECT_EQ(
  404. 3, parsing_merge.ExtensionSize(UNITTEST::TestParsingMerge::repeated_ext));
  405. }
  406. TEST(MESSAGE_TEST_NAME, MergeFrom) {
  407. UNITTEST::TestAllTypes source, dest;
  408. // Optional fields
  409. source.set_optional_int32(1); // only source
  410. source.set_optional_int64(2); // both source and dest
  411. dest.set_optional_int64(3);
  412. dest.set_optional_uint32(4); // only dest
  413. // Optional fields with defaults
  414. source.set_default_int32(13); // only source
  415. source.set_default_int64(14); // both source and dest
  416. dest.set_default_int64(15);
  417. dest.set_default_uint32(16); // only dest
  418. // Repeated fields
  419. source.add_repeated_int32(5); // only source
  420. source.add_repeated_int32(6);
  421. source.add_repeated_int64(7); // both source and dest
  422. source.add_repeated_int64(8);
  423. dest.add_repeated_int64(9);
  424. dest.add_repeated_int64(10);
  425. dest.add_repeated_uint32(11); // only dest
  426. dest.add_repeated_uint32(12);
  427. dest.MergeFrom(source);
  428. // Optional fields: source overwrites dest if source is specified
  429. EXPECT_EQ(1, dest.optional_int32()); // only source: use source
  430. EXPECT_EQ(2, dest.optional_int64()); // source and dest: use source
  431. EXPECT_EQ(4, dest.optional_uint32()); // only dest: use dest
  432. EXPECT_EQ(0, dest.optional_uint64()); // neither: use default
  433. // Optional fields with defaults
  434. EXPECT_EQ(13, dest.default_int32()); // only source: use source
  435. EXPECT_EQ(14, dest.default_int64()); // source and dest: use source
  436. EXPECT_EQ(16, dest.default_uint32()); // only dest: use dest
  437. EXPECT_EQ(44, dest.default_uint64()); // neither: use default
  438. // Repeated fields: concatenate source onto the end of dest
  439. ASSERT_EQ(2, dest.repeated_int32_size());
  440. EXPECT_EQ(5, dest.repeated_int32(0));
  441. EXPECT_EQ(6, dest.repeated_int32(1));
  442. ASSERT_EQ(4, dest.repeated_int64_size());
  443. EXPECT_EQ(9, dest.repeated_int64(0));
  444. EXPECT_EQ(10, dest.repeated_int64(1));
  445. EXPECT_EQ(7, dest.repeated_int64(2));
  446. EXPECT_EQ(8, dest.repeated_int64(3));
  447. ASSERT_EQ(2, dest.repeated_uint32_size());
  448. EXPECT_EQ(11, dest.repeated_uint32(0));
  449. EXPECT_EQ(12, dest.repeated_uint32(1));
  450. ASSERT_EQ(0, dest.repeated_uint64_size());
  451. }
  452. TEST(MESSAGE_TEST_NAME, IsInitialized) {
  453. UNITTEST::TestIsInitialized msg;
  454. EXPECT_TRUE(msg.IsInitialized());
  455. UNITTEST::TestIsInitialized::SubMessage* sub_message =
  456. msg.mutable_sub_message();
  457. EXPECT_TRUE(msg.IsInitialized());
  458. UNITTEST::TestIsInitialized::SubMessage::SubGroup* sub_group =
  459. sub_message->mutable_subgroup();
  460. EXPECT_FALSE(msg.IsInitialized());
  461. sub_group->set_i(1);
  462. EXPECT_TRUE(msg.IsInitialized());
  463. }
  464. TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryLookup) {
  465. EXPECT_EQ(MessageFactory::generated_factory()->GetPrototype(
  466. UNITTEST::TestAllTypes::descriptor()),
  467. &UNITTEST::TestAllTypes::default_instance());
  468. }
  469. TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryUnknownType) {
  470. // Construct a new descriptor.
  471. DescriptorPool pool;
  472. FileDescriptorProto file;
  473. file.set_name("foo.proto");
  474. file.add_message_type()->set_name("Foo");
  475. const Descriptor* descriptor = pool.BuildFile(file)->message_type(0);
  476. // Trying to construct it should return nullptr.
  477. EXPECT_TRUE(MessageFactory::generated_factory()->GetPrototype(descriptor) ==
  478. nullptr);
  479. }
  480. TEST(MESSAGE_TEST_NAME, MOMIParserEdgeCases) {
  481. {
  482. UNITTEST::TestAllTypes msg;
  483. // Parser ends in last 16 bytes of buffer due to a 0.
  484. std::string data;
  485. // 12 bytes of data
  486. for (int i = 0; i < 4; i++) data += "\370\1\1";
  487. // 13 byte is terminator
  488. data += '\0'; // Terminator
  489. // followed by the rest of the stream
  490. // space is ascii 32 so no end group
  491. data += std::string(30, ' ');
  492. io::ArrayInputStream zcis(data.data(), data.size(), 17);
  493. io::CodedInputStream cis(&zcis);
  494. EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis));
  495. EXPECT_EQ(cis.CurrentPosition(), 3 * 4 + 1);
  496. }
  497. {
  498. // Parser ends in last 16 bytes of buffer due to a end-group.
  499. // Must use a message that is a group. Otherwise ending on a group end is
  500. // a failure.
  501. UNITTEST::TestAllTypes::OptionalGroup msg;
  502. std::string data;
  503. for (int i = 0; i < 3; i++) data += "\370\1\1";
  504. data += '\14'; // Octal end-group tag 12 (1 * 8 + 4(
  505. data += std::string(30, ' ');
  506. io::ArrayInputStream zcis(data.data(), data.size(), 17);
  507. io::CodedInputStream cis(&zcis);
  508. EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis));
  509. EXPECT_EQ(cis.CurrentPosition(), 3 * 3 + 1);
  510. EXPECT_TRUE(cis.LastTagWas(12));
  511. }
  512. {
  513. // Parser ends in last 16 bytes of buffer due to a end-group. But is inside
  514. // a length delimited field.
  515. // a failure.
  516. UNITTEST::TestAllTypes::OptionalGroup msg;
  517. std::string data;
  518. data += "\22\3foo";
  519. data += '\14'; // Octal end-group tag 12 (1 * 8 + 4(
  520. data += std::string(30, ' ');
  521. io::ArrayInputStream zcis(data.data(), data.size(), 17);
  522. io::CodedInputStream cis(&zcis);
  523. EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis));
  524. EXPECT_EQ(cis.CurrentPosition(), 6);
  525. EXPECT_TRUE(cis.LastTagWas(12));
  526. }
  527. {
  528. // Parser fails when ending on 0 if from ZeroCopyInputStream
  529. UNITTEST::TestAllTypes msg;
  530. std::string data;
  531. // 12 bytes of data
  532. for (int i = 0; i < 4; i++) data += "\370\1\1";
  533. // 13 byte is terminator
  534. data += '\0'; // Terminator
  535. data += std::string(30, ' ');
  536. io::ArrayInputStream zcis(data.data(), data.size(), 17);
  537. EXPECT_FALSE(msg.ParsePartialFromZeroCopyStream(&zcis));
  538. }
  539. }
  540. } // namespace protobuf
  541. } // namespace google