1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7
8 // Adapted from the patch of kenton@google.com (Kenton Varda)
9 // See https://github.com/protocolbuffers/protobuf/pull/710 for details.
10
11 #include "google/protobuf/util/delimited_message_util.h"
12
13 #include <sstream>
14
15 #include "google/protobuf/testing/googletest.h"
16 #include <gtest/gtest.h>
17 #include "google/protobuf/test_util.h"
18 #include "google/protobuf/unittest.pb.h"
19
20 namespace google {
21 namespace protobuf {
22 namespace util {
23
TEST(DelimitedMessageUtilTest,DelimitedMessages)24 TEST(DelimitedMessageUtilTest, DelimitedMessages) {
25 std::stringstream stream;
26
27 {
28 protobuf_unittest::TestAllTypes message1;
29 TestUtil::SetAllFields(&message1);
30 EXPECT_TRUE(SerializeDelimitedToOstream(message1, &stream));
31
32 protobuf_unittest::TestPackedTypes message2;
33 TestUtil::SetPackedFields(&message2);
34 EXPECT_TRUE(SerializeDelimitedToOstream(message2, &stream));
35 }
36
37 {
38 bool clean_eof;
39 io::IstreamInputStream zstream(&stream);
40
41 protobuf_unittest::TestAllTypes message1;
42 clean_eof = true;
43 EXPECT_TRUE(ParseDelimitedFromZeroCopyStream(&message1,
44 &zstream, &clean_eof));
45 EXPECT_FALSE(clean_eof);
46 TestUtil::ExpectAllFieldsSet(message1);
47
48 protobuf_unittest::TestPackedTypes message2;
49 clean_eof = true;
50 EXPECT_TRUE(ParseDelimitedFromZeroCopyStream(&message2,
51 &zstream, &clean_eof));
52 EXPECT_FALSE(clean_eof);
53 TestUtil::ExpectPackedFieldsSet(message2);
54
55 clean_eof = false;
56 EXPECT_FALSE(ParseDelimitedFromZeroCopyStream(&message2,
57 &zstream, &clean_eof));
58 EXPECT_TRUE(clean_eof);
59 }
60 }
61
TEST(DelimitedMessageUtilTest,FailsAtEndOfStream)62 TEST(DelimitedMessageUtilTest, FailsAtEndOfStream) {
63 std::stringstream full_stream;
64 std::stringstream partial_stream;
65
66 {
67 protobuf_unittest::ForeignMessage message;
68 message.set_c(42);
69 message.set_d(24);
70 EXPECT_TRUE(SerializeDelimitedToOstream(message, &full_stream));
71
72 std::string full_output = full_stream.str();
73 ASSERT_GT(full_output.size(), size_t{2});
74 ASSERT_EQ(full_output[0], 4);
75
76 partial_stream << full_output[0] << full_output[1] << full_output[2];
77 }
78
79 {
80 bool clean_eof;
81 io::IstreamInputStream zstream(&partial_stream);
82
83 protobuf_unittest::ForeignMessage message;
84 clean_eof = true;
85 EXPECT_FALSE(ParseDelimitedFromZeroCopyStream(&message,
86 &zstream, &clean_eof));
87 EXPECT_FALSE(clean_eof);
88 }
89 }
90
91 } // namespace util
92 } // namespace protobuf
93 } // namespace google
94