blob: 2d4780fe6de5b266ac774c3f0cdb732c9dde571d [file] [log] [blame]
Brian Silverman9c614bc2016-02-15 20:20:02 -05001// 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
31// Author: kenton@google.com (Kenton Varda)
32// Based on original Protocol Buffers design by
33// Sanjay Ghemawat, Jeff Dean, and others.
34
35#include <google/protobuf/message.h>
36
37#include <sys/types.h>
38#include <sys/stat.h>
39#include <fcntl.h>
40#ifdef _MSC_VER
41#include <io.h>
42#else
43#include <unistd.h>
44#endif
45#include <sstream>
46#include <fstream>
47
48#include <google/protobuf/test_util.h>
49#include <google/protobuf/unittest.pb.h>
50#include <google/protobuf/io/coded_stream.h>
51#include <google/protobuf/io/zero_copy_stream_impl.h>
52#include <google/protobuf/descriptor.pb.h>
53#include <google/protobuf/descriptor.h>
54#include <google/protobuf/generated_message_reflection.h>
55
56#include <google/protobuf/stubs/logging.h>
57#include <google/protobuf/stubs/common.h>
58#include <google/protobuf/testing/googletest.h>
59#include <gtest/gtest.h>
60
61namespace google {
62namespace protobuf {
63
64#ifndef O_BINARY
65#ifdef _O_BINARY
66#define O_BINARY _O_BINARY
67#else
68#define O_BINARY 0 // If this isn't defined, the platform doesn't need it.
69#endif
70#endif
71
72TEST(MessageTest, SerializeHelpers) {
73 // TODO(kenton): Test more helpers? They're all two-liners so it seems
74 // like a waste of time.
75
76 protobuf_unittest::TestAllTypes message;
77 TestUtil::SetAllFields(&message);
78 stringstream stream;
79
80 string str1("foo");
81 string str2("bar");
82
83 EXPECT_TRUE(message.SerializeToString(&str1));
84 EXPECT_TRUE(message.AppendToString(&str2));
85 EXPECT_TRUE(message.SerializeToOstream(&stream));
86
87 EXPECT_EQ(str1.size() + 3, str2.size());
88 EXPECT_EQ("bar", str2.substr(0, 3));
89 // Don't use EXPECT_EQ because we don't want to dump raw binary data to
90 // stdout.
91 EXPECT_TRUE(str2.substr(3) == str1);
92
93 // GCC gives some sort of error if we try to just do stream.str() == str1.
94 string temp = stream.str();
95 EXPECT_TRUE(temp == str1);
96
97 EXPECT_TRUE(message.SerializeAsString() == str1);
98
99}
100
101TEST(MessageTest, SerializeToBrokenOstream) {
102 ofstream out;
103 protobuf_unittest::TestAllTypes message;
104 message.set_optional_int32(123);
105
106 EXPECT_FALSE(message.SerializeToOstream(&out));
107}
108
109TEST(MessageTest, ParseFromFileDescriptor) {
110 string filename = TestSourceDir() +
111 "/google/protobuf/testdata/golden_message";
112 int file = open(filename.c_str(), O_RDONLY | O_BINARY);
113
114 unittest::TestAllTypes message;
115 EXPECT_TRUE(message.ParseFromFileDescriptor(file));
116 TestUtil::ExpectAllFieldsSet(message);
117
118 EXPECT_GE(close(file), 0);
119}
120
121TEST(MessageTest, ParsePackedFromFileDescriptor) {
122 string filename =
123 TestSourceDir() +
124 "/google/protobuf/testdata/golden_packed_fields_message";
125 int file = open(filename.c_str(), O_RDONLY | O_BINARY);
126
127 unittest::TestPackedTypes message;
128 EXPECT_TRUE(message.ParseFromFileDescriptor(file));
129 TestUtil::ExpectPackedFieldsSet(message);
130
131 EXPECT_GE(close(file), 0);
132}
133
134TEST(MessageTest, ParseHelpers) {
135 // TODO(kenton): Test more helpers? They're all two-liners so it seems
136 // like a waste of time.
137 string data;
138
139 {
140 // Set up.
141 protobuf_unittest::TestAllTypes message;
142 TestUtil::SetAllFields(&message);
143 message.SerializeToString(&data);
144 }
145
146 {
147 // Test ParseFromString.
148 protobuf_unittest::TestAllTypes message;
149 EXPECT_TRUE(message.ParseFromString(data));
150 TestUtil::ExpectAllFieldsSet(message);
151 }
152
153 {
154 // Test ParseFromIstream.
155 protobuf_unittest::TestAllTypes message;
156 stringstream stream(data);
157 EXPECT_TRUE(message.ParseFromIstream(&stream));
158 EXPECT_TRUE(stream.eof());
159 TestUtil::ExpectAllFieldsSet(message);
160 }
161
162 {
163 // Test ParseFromBoundedZeroCopyStream.
164 string data_with_junk(data);
165 data_with_junk.append("some junk on the end");
166 io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size());
167 protobuf_unittest::TestAllTypes message;
168 EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size()));
169 TestUtil::ExpectAllFieldsSet(message);
170 }
171
172 {
173 // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if
174 // EOF is reached before the expected number of bytes.
175 io::ArrayInputStream stream(data.data(), data.size());
176 protobuf_unittest::TestAllTypes message;
177 EXPECT_FALSE(
178 message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1));
179 }
180}
181
182TEST(MessageTest, ParseFailsIfNotInitialized) {
183 unittest::TestRequired message;
184 vector<string> errors;
185
186 {
187 ScopedMemoryLog log;
188 EXPECT_FALSE(message.ParseFromString(""));
189 errors = log.GetMessages(ERROR);
190 }
191
192 ASSERT_EQ(1, errors.size());
193 EXPECT_EQ("Can't parse message of type \"protobuf_unittest.TestRequired\" "
194 "because it is missing required fields: a, b, c",
195 errors[0]);
196}
197
198TEST(MessageTest, BypassInitializationCheckOnParse) {
199 unittest::TestRequired message;
200 io::ArrayInputStream raw_input(NULL, 0);
201 io::CodedInputStream input(&raw_input);
202 EXPECT_TRUE(message.MergePartialFromCodedStream(&input));
203}
204
205TEST(MessageTest, InitializationErrorString) {
206 unittest::TestRequired message;
207 EXPECT_EQ("a, b, c", message.InitializationErrorString());
208}
209
210TEST(MessageTest, DynamicCastToGenerated) {
211 unittest::TestAllTypes test_all_types;
212
213 google::protobuf::Message* test_all_types_pointer = &test_all_types;
214 EXPECT_EQ(&test_all_types,
215 google::protobuf::internal::DynamicCastToGenerated<unittest::TestAllTypes>(
216 test_all_types_pointer));
217 EXPECT_EQ(NULL,
218 google::protobuf::internal::DynamicCastToGenerated<unittest::TestRequired>(
219 test_all_types_pointer));
220
221 const google::protobuf::Message* test_all_types_pointer_const = &test_all_types;
222 EXPECT_EQ(
223 &test_all_types,
224 google::protobuf::internal::DynamicCastToGenerated<const unittest::TestAllTypes>(
225 test_all_types_pointer_const));
226 EXPECT_EQ(
227 NULL,
228 google::protobuf::internal::DynamicCastToGenerated<const unittest::TestRequired>(
229 test_all_types_pointer_const));
230}
231
232#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet.
233
234TEST(MessageTest, SerializeFailsIfNotInitialized) {
235 unittest::TestRequired message;
236 string data;
237 EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)),
238 "Can't serialize message of type \"protobuf_unittest.TestRequired\" because "
239 "it is missing required fields: a, b, c");
240}
241
242TEST(MessageTest, CheckInitialized) {
243 unittest::TestRequired message;
244 EXPECT_DEATH(message.CheckInitialized(),
245 "Message of type \"protobuf_unittest.TestRequired\" is missing required "
246 "fields: a, b, c");
247}
248
249TEST(MessageTest, CheckOverflow) {
250 unittest::TestAllTypes message;
251 // Create a message with size just over 2GB. This triggers integer overflow
252 // when computing message size.
253 const string data(1024, 'x');
254 Cord one_megabyte;
255 for (int i = 0; i < 1024; i++) {
256 one_megabyte.Append(data);
257 }
258
259 for (int i = 0; i < 2 * 1024 + 1; ++i) {
260 message.add_repeated_cord()->CopyFrom(one_megabyte);
261 }
262
263 Cord serialized;
264 EXPECT_FALSE(message.AppendToCord(&serialized));
265}
266
267#endif // PROTOBUF_HAS_DEATH_TEST
268
269namespace {
270
271class NegativeByteSize : public unittest::TestRequired {
272 public:
273 virtual int ByteSize() const { return -1; }
274};
275
276} // namespace
277
278TEST(MessageTest, SerializationFailsOnNegativeByteSize) {
279 NegativeByteSize message;
280 string string_output;
281 EXPECT_FALSE(message.AppendPartialToString(&string_output));
282
283 io::ArrayOutputStream coded_raw_output(NULL, 100);
284 io::CodedOutputStream coded_output(&coded_raw_output);
285 EXPECT_FALSE(message.SerializePartialToCodedStream(&coded_output));
286}
287
288TEST(MessageTest, BypassInitializationCheckOnSerialize) {
289 unittest::TestRequired message;
290 io::ArrayOutputStream raw_output(NULL, 0);
291 io::CodedOutputStream output(&raw_output);
292 EXPECT_TRUE(message.SerializePartialToCodedStream(&output));
293}
294
295TEST(MessageTest, FindInitializationErrors) {
296 unittest::TestRequired message;
297 vector<string> errors;
298 message.FindInitializationErrors(&errors);
299 ASSERT_EQ(3, errors.size());
300 EXPECT_EQ("a", errors[0]);
301 EXPECT_EQ("b", errors[1]);
302 EXPECT_EQ("c", errors[2]);
303}
304
305TEST(MessageTest, ParseFailsOnInvalidMessageEnd) {
306 unittest::TestAllTypes message;
307
308 // Control case.
309 EXPECT_TRUE(message.ParseFromArray("", 0));
310
311 // The byte is a valid varint, but not a valid tag (zero).
312 EXPECT_FALSE(message.ParseFromArray("\0", 1));
313
314 // The byte is a malformed varint.
315 EXPECT_FALSE(message.ParseFromArray("\200", 1));
316
317 // The byte is an endgroup tag, but we aren't parsing a group.
318 EXPECT_FALSE(message.ParseFromArray("\014", 1));
319}
320
321namespace {
322
323void ExpectMessageMerged(const unittest::TestAllTypes& message) {
324 EXPECT_EQ(3, message.optional_int32());
325 EXPECT_EQ(2, message.optional_int64());
326 EXPECT_EQ("hello", message.optional_string());
327}
328
329void AssignParsingMergeMessages(
330 unittest::TestAllTypes* msg1,
331 unittest::TestAllTypes* msg2,
332 unittest::TestAllTypes* msg3) {
333 msg1->set_optional_int32(1);
334 msg2->set_optional_int64(2);
335 msg3->set_optional_int32(3);
336 msg3->set_optional_string("hello");
337}
338
339} // namespace
340
341// Test that if an optional or required message/group field appears multiple
342// times in the input, they need to be merged.
343TEST(MessageTest, ParsingMerge) {
344 unittest::TestParsingMerge::RepeatedFieldsGenerator generator;
345 unittest::TestAllTypes* msg1;
346 unittest::TestAllTypes* msg2;
347 unittest::TestAllTypes* msg3;
348
349#define ASSIGN_REPEATED_FIELD(FIELD) \
350 msg1 = generator.add_##FIELD(); \
351 msg2 = generator.add_##FIELD(); \
352 msg3 = generator.add_##FIELD(); \
353 AssignParsingMergeMessages(msg1, msg2, msg3)
354
355 ASSIGN_REPEATED_FIELD(field1);
356 ASSIGN_REPEATED_FIELD(field2);
357 ASSIGN_REPEATED_FIELD(field3);
358 ASSIGN_REPEATED_FIELD(ext1);
359 ASSIGN_REPEATED_FIELD(ext2);
360
361#undef ASSIGN_REPEATED_FIELD
362#define ASSIGN_REPEATED_GROUP(FIELD) \
363 msg1 = generator.add_##FIELD()->mutable_field1(); \
364 msg2 = generator.add_##FIELD()->mutable_field1(); \
365 msg3 = generator.add_##FIELD()->mutable_field1(); \
366 AssignParsingMergeMessages(msg1, msg2, msg3)
367
368 ASSIGN_REPEATED_GROUP(group1);
369 ASSIGN_REPEATED_GROUP(group2);
370
371#undef ASSIGN_REPEATED_GROUP
372
373 string buffer;
374 generator.SerializeToString(&buffer);
375 unittest::TestParsingMerge parsing_merge;
376 parsing_merge.ParseFromString(buffer);
377
378 // Required and optional fields should be merged.
379 ExpectMessageMerged(parsing_merge.required_all_types());
380 ExpectMessageMerged(parsing_merge.optional_all_types());
381 ExpectMessageMerged(
382 parsing_merge.optionalgroup().optional_group_all_types());
383 ExpectMessageMerged(
384 parsing_merge.GetExtension(unittest::TestParsingMerge::optional_ext));
385
386 // Repeated fields should not be merged.
387 EXPECT_EQ(3, parsing_merge.repeated_all_types_size());
388 EXPECT_EQ(3, parsing_merge.repeatedgroup_size());
389 EXPECT_EQ(3, parsing_merge.ExtensionSize(
390 unittest::TestParsingMerge::repeated_ext));
391}
392
393TEST(MessageTest, MergeFrom) {
394 unittest::TestAllTypes source;
395 unittest::TestAllTypes dest;
396
397 // Optional fields
398 source.set_optional_int32(1); // only source
399 source.set_optional_int64(2); // both source and dest
400 dest.set_optional_int64(3);
401 dest.set_optional_uint32(4); // only dest
402
403 // Optional fields with defaults
404 source.set_default_int32(13); // only source
405 source.set_default_int64(14); // both source and dest
406 dest.set_default_int64(15);
407 dest.set_default_uint32(16); // only dest
408
409 // Repeated fields
410 source.add_repeated_int32(5); // only source
411 source.add_repeated_int32(6);
412 source.add_repeated_int64(7); // both source and dest
413 source.add_repeated_int64(8);
414 dest.add_repeated_int64(9);
415 dest.add_repeated_int64(10);
416 dest.add_repeated_uint32(11); // only dest
417 dest.add_repeated_uint32(12);
418
419 dest.MergeFrom(source);
420
421 // Optional fields: source overwrites dest if source is specified
422 EXPECT_EQ(1, dest.optional_int32()); // only source: use source
423 EXPECT_EQ(2, dest.optional_int64()); // source and dest: use source
424 EXPECT_EQ(4, dest.optional_uint32()); // only dest: use dest
425 EXPECT_EQ(0, dest.optional_uint64()); // neither: use default
426
427 // Optional fields with defaults
428 EXPECT_EQ(13, dest.default_int32()); // only source: use source
429 EXPECT_EQ(14, dest.default_int64()); // source and dest: use source
430 EXPECT_EQ(16, dest.default_uint32()); // only dest: use dest
431 EXPECT_EQ(44, dest.default_uint64()); // neither: use default
432
433 // Repeated fields: concatenate source onto the end of dest
434 ASSERT_EQ(2, dest.repeated_int32_size());
435 EXPECT_EQ(5, dest.repeated_int32(0));
436 EXPECT_EQ(6, dest.repeated_int32(1));
437 ASSERT_EQ(4, dest.repeated_int64_size());
438 EXPECT_EQ(9, dest.repeated_int64(0));
439 EXPECT_EQ(10, dest.repeated_int64(1));
440 EXPECT_EQ(7, dest.repeated_int64(2));
441 EXPECT_EQ(8, dest.repeated_int64(3));
442 ASSERT_EQ(2, dest.repeated_uint32_size());
443 EXPECT_EQ(11, dest.repeated_uint32(0));
444 EXPECT_EQ(12, dest.repeated_uint32(1));
445 ASSERT_EQ(0, dest.repeated_uint64_size());
446}
447
448TEST(MessageFactoryTest, GeneratedFactoryLookup) {
449 EXPECT_EQ(
450 MessageFactory::generated_factory()->GetPrototype(
451 protobuf_unittest::TestAllTypes::descriptor()),
452 &protobuf_unittest::TestAllTypes::default_instance());
453}
454
455TEST(MessageFactoryTest, GeneratedFactoryUnknownType) {
456 // Construct a new descriptor.
457 DescriptorPool pool;
458 FileDescriptorProto file;
459 file.set_name("foo.proto");
460 file.add_message_type()->set_name("Foo");
461 const Descriptor* descriptor = pool.BuildFile(file)->message_type(0);
462
463 // Trying to construct it should return NULL.
464 EXPECT_TRUE(
465 MessageFactory::generated_factory()->GetPrototype(descriptor) == NULL);
466}
467
468
469} // namespace protobuf
470} // namespace google