1
// Protocol Buffers - Google's data interchange format
2
// Copyright 2008 Google Inc. All rights reserved.
3
// http://code.google.com/p/protobuf/
5
// Redistribution and use in source and binary forms, with or without
6
// modification, are permitted provided that the following conditions are
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
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.
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.
31
// Author: kenton@google.com (Kenton Varda)
32
// Based on original Protocol Buffers design by
33
// Sanjay Ghemawat, Jeff Dean, and others.
35
// To test the code generator, we actually use it to generate code for
36
// google/protobuf/unittest.proto, then test that. This means that we
37
// are actually testing the parser and other parts of the system at the same
38
// time, and that problems in the generator may show up as compile-time errors
39
// rather than unittest failures, which may be surprising. However, testing
40
// the output of the C++ generator directly would be very hard. We can't very
41
// well just check it against golden files since those files would have to be
42
// updated for any small change; such a test would be very brittle and probably
43
// not very helpful. What we really want to test is that the code compiles
44
// correctly and produces the interfaces we expect, which is why this test
45
// is written this way.
49
#include <google/protobuf/unittest.pb.h>
50
#include <google/protobuf/unittest_optimize_for.pb.h>
51
#include <google/protobuf/unittest_embed_optimize_for.pb.h>
52
#include <google/protobuf/unittest_no_generic_services.pb.h>
53
#include <google/protobuf/test_util.h>
54
#include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h>
55
#include <google/protobuf/compiler/importer.h>
56
#include <google/protobuf/io/coded_stream.h>
57
#include <google/protobuf/io/zero_copy_stream_impl.h>
58
#include <google/protobuf/descriptor.h>
59
#include <google/protobuf/descriptor.pb.h>
60
#include <google/protobuf/dynamic_message.h>
62
#include <google/protobuf/stubs/common.h>
63
#include <google/protobuf/stubs/strutil.h>
64
#include <google/protobuf/stubs/substitute.h>
65
#include <google/protobuf/testing/googletest.h>
66
#include <gtest/gtest.h>
67
#include <google/protobuf/stubs/stl_util-inl.h>
74
// Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
75
namespace cpp_unittest {
78
class MockErrorCollector : public MultiFileErrorCollector {
80
MockErrorCollector() {}
81
~MockErrorCollector() {}
85
// implements ErrorCollector ---------------------------------------
86
void AddError(const string& filename, int line, int column,
87
const string& message) {
88
strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
89
filename, line, column, message);
93
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
95
// Test that generated code has proper descriptors:
96
// Parse a descriptor directly (using google::protobuf::compiler::Importer) and
97
// compare it to the one that was produced by generated code.
98
TEST(GeneratedDescriptorTest, IdenticalDescriptors) {
99
const FileDescriptor* generated_descriptor =
100
unittest::TestAllTypes::descriptor()->file();
102
// Set up the Importer.
103
MockErrorCollector error_collector;
104
DiskSourceTree source_tree;
105
source_tree.MapPath("", TestSourceDir());
106
Importer importer(&source_tree, &error_collector);
108
// Import (parse) unittest.proto.
109
const FileDescriptor* parsed_descriptor =
110
importer.Import("google/protobuf/unittest.proto");
111
EXPECT_EQ("", error_collector.text_);
112
ASSERT_TRUE(parsed_descriptor != NULL);
114
// Test that descriptors are generated correctly by converting them to
115
// FileDescriptorProtos and comparing.
116
FileDescriptorProto generated_decsriptor_proto, parsed_descriptor_proto;
117
generated_descriptor->CopyTo(&generated_decsriptor_proto);
118
parsed_descriptor->CopyTo(&parsed_descriptor_proto);
120
EXPECT_EQ(parsed_descriptor_proto.DebugString(),
121
generated_decsriptor_proto.DebugString());
124
#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
126
// ===================================================================
128
TEST(GeneratedMessageTest, Defaults) {
129
// Check that all default values are set correctly in the initial message.
130
unittest::TestAllTypes message;
132
TestUtil::ExpectClear(message);
134
// Messages should return pointers to default instances until first use.
135
// (This is not checked by ExpectClear() since it is not actually true after
136
// the fields have been set and then cleared.)
137
EXPECT_EQ(&unittest::TestAllTypes::OptionalGroup::default_instance(),
138
&message.optionalgroup());
139
EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
140
&message.optional_nested_message());
141
EXPECT_EQ(&unittest::ForeignMessage::default_instance(),
142
&message.optional_foreign_message());
143
EXPECT_EQ(&unittest_import::ImportMessage::default_instance(),
144
&message.optional_import_message());
147
TEST(GeneratedMessageTest, FloatingPointDefaults) {
148
const unittest::TestExtremeDefaultValues& extreme_default =
149
unittest::TestExtremeDefaultValues::default_instance();
151
EXPECT_EQ(0.0f, extreme_default.zero_float());
152
EXPECT_EQ(1.0f, extreme_default.one_float());
153
EXPECT_EQ(1.5f, extreme_default.small_float());
154
EXPECT_EQ(-1.0f, extreme_default.negative_one_float());
155
EXPECT_EQ(-1.5f, extreme_default.negative_float());
156
EXPECT_EQ(2.0e8f, extreme_default.large_float());
157
EXPECT_EQ(-8e-28f, extreme_default.small_negative_float());
158
EXPECT_EQ(numeric_limits<double>::infinity(),
159
extreme_default.inf_double());
160
EXPECT_EQ(-numeric_limits<double>::infinity(),
161
extreme_default.neg_inf_double());
162
EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double());
163
EXPECT_EQ(numeric_limits<float>::infinity(),
164
extreme_default.inf_float());
165
EXPECT_EQ(-numeric_limits<float>::infinity(),
166
extreme_default.neg_inf_float());
167
EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float());
170
TEST(GeneratedMessageTest, Accessors) {
171
// Set every field to a unique value then go back and check all those
173
unittest::TestAllTypes message;
175
TestUtil::SetAllFields(&message);
176
TestUtil::ExpectAllFieldsSet(message);
178
TestUtil::ModifyRepeatedFields(&message);
179
TestUtil::ExpectRepeatedFieldsModified(message);
182
TEST(GeneratedMessageTest, MutableStringDefault) {
183
// mutable_foo() for a string should return a string initialized to its
185
unittest::TestAllTypes message;
187
EXPECT_EQ("hello", *message.mutable_default_string());
189
// Note that the first time we call mutable_foo(), we get a newly-allocated
190
// string, but if we clear it and call it again, we get the same object again.
191
// We should verify that it has its default value in both cases.
192
message.set_default_string("blah");
195
EXPECT_EQ("hello", *message.mutable_default_string());
198
TEST(GeneratedMessageTest, Clear) {
199
// Set every field to a unique value, clear the message, then check that
201
unittest::TestAllTypes message;
203
TestUtil::SetAllFields(&message);
205
TestUtil::ExpectClear(message);
207
// Unlike with the defaults test, we do NOT expect that requesting embedded
208
// messages will return a pointer to the default instance. Instead, they
209
// should return the objects that were created when mutable_blah() was
211
EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(),
212
&message.optionalgroup());
213
EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(),
214
&message.optional_nested_message());
215
EXPECT_NE(&unittest::ForeignMessage::default_instance(),
216
&message.optional_foreign_message());
217
EXPECT_NE(&unittest_import::ImportMessage::default_instance(),
218
&message.optional_import_message());
221
TEST(GeneratedMessageTest, EmbeddedNullsInBytesCharStar) {
222
unittest::TestAllTypes message;
224
const char* value = "\0lalala\0\0";
225
message.set_optional_bytes(value, 9);
226
ASSERT_EQ(9, message.optional_bytes().size());
227
EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9));
229
message.add_repeated_bytes(value, 9);
230
ASSERT_EQ(9, message.repeated_bytes(0).size());
231
EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9));
234
TEST(GeneratedMessageTest, ClearOneField) {
235
// Set every field to a unique value, then clear one value and insure that
236
// only that one value is cleared.
237
unittest::TestAllTypes message;
239
TestUtil::SetAllFields(&message);
240
int64 original_value = message.optional_int64();
242
// Clear the field and make sure it shows up as cleared.
243
message.clear_optional_int64();
244
EXPECT_FALSE(message.has_optional_int64());
245
EXPECT_EQ(0, message.optional_int64());
247
// Other adjacent fields should not be cleared.
248
EXPECT_TRUE(message.has_optional_int32());
249
EXPECT_TRUE(message.has_optional_uint32());
251
// Make sure if we set it again, then all fields are set.
252
message.set_optional_int64(original_value);
253
TestUtil::ExpectAllFieldsSet(message);
256
TEST(GeneratedMessageTest, StringCharStarLength) {
257
// Verify that we can use a char*,length to set one of the string fields.
258
unittest::TestAllTypes message;
259
message.set_optional_string("abcdef", 3);
260
EXPECT_EQ("abc", message.optional_string());
262
// Verify that we can use a char*,length to add to a repeated string field.
263
message.add_repeated_string("abcdef", 3);
264
EXPECT_EQ(1, message.repeated_string_size());
265
EXPECT_EQ("abc", message.repeated_string(0));
267
// Verify that we can use a char*,length to set a repeated string field.
268
message.set_repeated_string(0, "wxyz", 2);
269
EXPECT_EQ("wx", message.repeated_string(0));
273
TEST(GeneratedMessageTest, CopyFrom) {
274
unittest::TestAllTypes message1, message2;
276
TestUtil::SetAllFields(&message1);
277
message2.CopyFrom(message1);
278
TestUtil::ExpectAllFieldsSet(message2);
280
// Copying from self should be a no-op.
281
message2.CopyFrom(message2);
282
TestUtil::ExpectAllFieldsSet(message2);
285
TEST(GeneratedMessageTest, SwapWithEmpty) {
286
unittest::TestAllTypes message1, message2;
287
TestUtil::SetAllFields(&message1);
289
TestUtil::ExpectAllFieldsSet(message1);
290
TestUtil::ExpectClear(message2);
291
message1.Swap(&message2);
292
TestUtil::ExpectAllFieldsSet(message2);
293
TestUtil::ExpectClear(message1);
296
TEST(GeneratedMessageTest, SwapWithSelf) {
297
unittest::TestAllTypes message;
298
TestUtil::SetAllFields(&message);
299
TestUtil::ExpectAllFieldsSet(message);
300
message.Swap(&message);
301
TestUtil::ExpectAllFieldsSet(message);
304
TEST(GeneratedMessageTest, SwapWithOther) {
305
unittest::TestAllTypes message1, message2;
307
message1.set_optional_int32(123);
308
message1.set_optional_string("abc");
309
message1.mutable_optional_nested_message()->set_bb(1);
310
message1.set_optional_nested_enum(unittest::TestAllTypes::FOO);
311
message1.add_repeated_int32(1);
312
message1.add_repeated_int32(2);
313
message1.add_repeated_string("a");
314
message1.add_repeated_string("b");
315
message1.add_repeated_nested_message()->set_bb(7);
316
message1.add_repeated_nested_message()->set_bb(8);
317
message1.add_repeated_nested_enum(unittest::TestAllTypes::FOO);
318
message1.add_repeated_nested_enum(unittest::TestAllTypes::BAR);
320
message2.set_optional_int32(456);
321
message2.set_optional_string("def");
322
message2.mutable_optional_nested_message()->set_bb(2);
323
message2.set_optional_nested_enum(unittest::TestAllTypes::BAR);
324
message2.add_repeated_int32(3);
325
message2.add_repeated_string("c");
326
message2.add_repeated_nested_message()->set_bb(9);
327
message2.add_repeated_nested_enum(unittest::TestAllTypes::BAZ);
329
message1.Swap(&message2);
331
EXPECT_EQ(456, message1.optional_int32());
332
EXPECT_EQ("def", message1.optional_string());
333
EXPECT_EQ(2, message1.optional_nested_message().bb());
334
EXPECT_EQ(unittest::TestAllTypes::BAR, message1.optional_nested_enum());
335
ASSERT_EQ(1, message1.repeated_int32_size());
336
EXPECT_EQ(3, message1.repeated_int32(0));
337
ASSERT_EQ(1, message1.repeated_string_size());
338
EXPECT_EQ("c", message1.repeated_string(0));
339
ASSERT_EQ(1, message1.repeated_nested_message_size());
340
EXPECT_EQ(9, message1.repeated_nested_message(0).bb());
341
ASSERT_EQ(1, message1.repeated_nested_enum_size());
342
EXPECT_EQ(unittest::TestAllTypes::BAZ, message1.repeated_nested_enum(0));
344
EXPECT_EQ(123, message2.optional_int32());
345
EXPECT_EQ("abc", message2.optional_string());
346
EXPECT_EQ(1, message2.optional_nested_message().bb());
347
EXPECT_EQ(unittest::TestAllTypes::FOO, message2.optional_nested_enum());
348
ASSERT_EQ(2, message2.repeated_int32_size());
349
EXPECT_EQ(1, message2.repeated_int32(0));
350
EXPECT_EQ(2, message2.repeated_int32(1));
351
ASSERT_EQ(2, message2.repeated_string_size());
352
EXPECT_EQ("a", message2.repeated_string(0));
353
EXPECT_EQ("b", message2.repeated_string(1));
354
ASSERT_EQ(2, message2.repeated_nested_message_size());
355
EXPECT_EQ(7, message2.repeated_nested_message(0).bb());
356
EXPECT_EQ(8, message2.repeated_nested_message(1).bb());
357
ASSERT_EQ(2, message2.repeated_nested_enum_size());
358
EXPECT_EQ(unittest::TestAllTypes::FOO, message2.repeated_nested_enum(0));
359
EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1));
362
TEST(GeneratedMessageTest, CopyConstructor) {
363
unittest::TestAllTypes message1;
364
TestUtil::SetAllFields(&message1);
366
unittest::TestAllTypes message2(message1);
367
TestUtil::ExpectAllFieldsSet(message2);
370
TEST(GeneratedMessageTest, CopyAssignmentOperator) {
371
unittest::TestAllTypes message1;
372
TestUtil::SetAllFields(&message1);
374
unittest::TestAllTypes message2;
376
TestUtil::ExpectAllFieldsSet(message2);
378
// Make sure that self-assignment does something sane.
380
TestUtil::ExpectAllFieldsSet(message2);
383
TEST(GeneratedMessageTest, UpcastCopyFrom) {
384
// Test the CopyFrom method that takes in the generic const Message&
386
unittest::TestAllTypes message1, message2;
388
TestUtil::SetAllFields(&message1);
390
const Message* source = implicit_cast<const Message*>(&message1);
391
message2.CopyFrom(*source);
393
TestUtil::ExpectAllFieldsSet(message2);
396
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
398
TEST(GeneratedMessageTest, DynamicMessageCopyFrom) {
399
// Test copying from a DynamicMessage, which must fall back to using
401
unittest::TestAllTypes message2;
403
// Construct a new version of the dynamic message via the factory.
404
DynamicMessageFactory factory;
405
scoped_ptr<Message> message1;
406
message1.reset(factory.GetPrototype(
407
unittest::TestAllTypes::descriptor())->New());
409
TestUtil::ReflectionTester reflection_tester(
410
unittest::TestAllTypes::descriptor());
411
reflection_tester.SetAllFieldsViaReflection(message1.get());
413
message2.CopyFrom(*message1);
415
TestUtil::ExpectAllFieldsSet(message2);
418
#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
420
TEST(GeneratedMessageTest, NonEmptyMergeFrom) {
421
// Test merging with a non-empty message. Code is a modified form
422
// of that found in google/protobuf/reflection_ops_unittest.cc.
423
unittest::TestAllTypes message1, message2;
425
TestUtil::SetAllFields(&message1);
427
// This field will test merging into an empty spot.
428
message2.set_optional_int32(message1.optional_int32());
429
message1.clear_optional_int32();
431
// This tests overwriting.
432
message2.set_optional_string(message1.optional_string());
433
message1.set_optional_string("something else");
435
// This tests concatenating.
436
message2.add_repeated_int32(message1.repeated_int32(1));
437
int32 i = message1.repeated_int32(0);
438
message1.clear_repeated_int32();
439
message1.add_repeated_int32(i);
441
message1.MergeFrom(message2);
443
TestUtil::ExpectAllFieldsSet(message1);
446
#ifdef GTEST_HAS_DEATH_TEST
448
TEST(GeneratedMessageTest, MergeFromSelf) {
449
unittest::TestAllTypes message;
450
EXPECT_DEATH(message.MergeFrom(message), "&from");
451
EXPECT_DEATH(message.MergeFrom(implicit_cast<const Message&>(message)),
455
#endif // GTEST_HAS_DEATH_TEST
457
// Test the generated SerializeWithCachedSizesToArray(),
458
TEST(GeneratedMessageTest, SerializationToArray) {
459
unittest::TestAllTypes message1, message2;
461
TestUtil::SetAllFields(&message1);
462
int size = message1.ByteSize();
464
uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
465
uint8* end = message1.SerializeWithCachedSizesToArray(start);
466
EXPECT_EQ(size, end - start);
467
EXPECT_TRUE(message2.ParseFromString(data));
468
TestUtil::ExpectAllFieldsSet(message2);
472
TEST(GeneratedMessageTest, PackedFieldsSerializationToArray) {
473
unittest::TestPackedTypes packed_message1, packed_message2;
475
TestUtil::SetPackedFields(&packed_message1);
476
int packed_size = packed_message1.ByteSize();
477
packed_data.resize(packed_size);
478
uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data));
479
uint8* end = packed_message1.SerializeWithCachedSizesToArray(start);
480
EXPECT_EQ(packed_size, end - start);
481
EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
482
TestUtil::ExpectPackedFieldsSet(packed_message2);
485
// Test the generated SerializeWithCachedSizes() by forcing the buffer to write
486
// one byte at a time.
487
TEST(GeneratedMessageTest, SerializationToStream) {
488
unittest::TestAllTypes message1, message2;
489
TestUtil::SetAllFields(&message1);
490
int size = message1.ByteSize();
494
// Allow the output stream to buffer only one byte at a time.
495
io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
496
io::CodedOutputStream output_stream(&array_stream);
497
message1.SerializeWithCachedSizes(&output_stream);
498
EXPECT_FALSE(output_stream.HadError());
499
EXPECT_EQ(size, output_stream.ByteCount());
501
EXPECT_TRUE(message2.ParseFromString(data));
502
TestUtil::ExpectAllFieldsSet(message2);
506
TEST(GeneratedMessageTest, PackedFieldsSerializationToStream) {
507
unittest::TestPackedTypes message1, message2;
508
TestUtil::SetPackedFields(&message1);
509
int size = message1.ByteSize();
513
// Allow the output stream to buffer only one byte at a time.
514
io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
515
io::CodedOutputStream output_stream(&array_stream);
516
message1.SerializeWithCachedSizes(&output_stream);
517
EXPECT_FALSE(output_stream.HadError());
518
EXPECT_EQ(size, output_stream.ByteCount());
520
EXPECT_TRUE(message2.ParseFromString(data));
521
TestUtil::ExpectPackedFieldsSet(message2);
525
TEST(GeneratedMessageTest, Required) {
526
// Test that IsInitialized() returns false if required fields are missing.
527
unittest::TestRequired message;
529
EXPECT_FALSE(message.IsInitialized());
531
EXPECT_FALSE(message.IsInitialized());
533
EXPECT_FALSE(message.IsInitialized());
535
EXPECT_TRUE(message.IsInitialized());
538
TEST(GeneratedMessageTest, RequiredForeign) {
539
// Test that IsInitialized() returns false if required fields in nested
540
// messages are missing.
541
unittest::TestRequiredForeign message;
543
EXPECT_TRUE(message.IsInitialized());
545
message.mutable_optional_message();
546
EXPECT_FALSE(message.IsInitialized());
548
message.mutable_optional_message()->set_a(1);
549
message.mutable_optional_message()->set_b(2);
550
message.mutable_optional_message()->set_c(3);
551
EXPECT_TRUE(message.IsInitialized());
553
message.add_repeated_message();
554
EXPECT_FALSE(message.IsInitialized());
556
message.mutable_repeated_message(0)->set_a(1);
557
message.mutable_repeated_message(0)->set_b(2);
558
message.mutable_repeated_message(0)->set_c(3);
559
EXPECT_TRUE(message.IsInitialized());
562
TEST(GeneratedMessageTest, ForeignNested) {
563
// Test that TestAllTypes::NestedMessage can be embedded directly into
565
unittest::TestForeignNested message;
567
// If this compiles and runs without crashing, it must work. We have
568
// nothing more to test.
569
unittest::TestAllTypes::NestedMessage* nested =
570
message.mutable_foreign_nested();
574
TEST(GeneratedMessageTest, ReallyLargeTagNumber) {
575
// Test that really large tag numbers don't break anything.
576
unittest::TestReallyLargeTagNumber message1, message2;
579
// For the most part, if this compiles and runs then we're probably good.
580
// (The most likely cause for failure would be if something were attempting
581
// to allocate a lookup table of some sort using tag numbers as the index.)
582
// We'll try serializing just for fun.
583
message1.set_a(1234);
584
message1.set_bb(5678);
585
message1.SerializeToString(&data);
586
EXPECT_TRUE(message2.ParseFromString(data));
587
EXPECT_EQ(1234, message2.a());
588
EXPECT_EQ(5678, message2.bb());
591
TEST(GeneratedMessageTest, MutualRecursion) {
592
// Test that mutually-recursive message types work.
593
unittest::TestMutualRecursionA message;
594
unittest::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a();
595
unittest::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a();
597
// Again, if the above compiles and runs, that's all we really have to
598
// test, but just for run we'll check that the system didn't somehow come
599
// up with a pointer loop...
600
EXPECT_NE(&message, nested);
601
EXPECT_NE(&message, nested2);
602
EXPECT_NE(nested, nested2);
605
TEST(GeneratedMessageTest, CamelCaseFieldNames) {
606
// This test is mainly checking that the following compiles, which verifies
607
// that the field names were coerced to lower-case.
609
// Protocol buffers standard style is to use lowercase-with-underscores for
610
// field names. Some old proto1 .protos unfortunately used camel-case field
611
// names. In proto1, these names were forced to lower-case. So, we do the
612
// same thing in proto2.
614
unittest::TestCamelCaseFieldNames message;
616
message.set_primitivefield(2);
617
message.set_stringfield("foo");
618
message.set_enumfield(unittest::FOREIGN_FOO);
619
message.mutable_messagefield()->set_c(6);
621
message.add_repeatedprimitivefield(8);
622
message.add_repeatedstringfield("qux");
623
message.add_repeatedenumfield(unittest::FOREIGN_BAR);
624
message.add_repeatedmessagefield()->set_c(15);
626
EXPECT_EQ(2, message.primitivefield());
627
EXPECT_EQ("foo", message.stringfield());
628
EXPECT_EQ(unittest::FOREIGN_FOO, message.enumfield());
629
EXPECT_EQ(6, message.messagefield().c());
631
EXPECT_EQ(8, message.repeatedprimitivefield(0));
632
EXPECT_EQ("qux", message.repeatedstringfield(0));
633
EXPECT_EQ(unittest::FOREIGN_BAR, message.repeatedenumfield(0));
634
EXPECT_EQ(15, message.repeatedmessagefield(0).c());
637
TEST(GeneratedMessageTest, TestConflictingSymbolNames) {
638
// test_bad_identifiers.proto successfully compiled, then it works. The
639
// following is just a token usage to insure that the code is, in fact,
640
// being compiled and linked.
642
protobuf_unittest::TestConflictingSymbolNames message;
643
message.set_uint32(1);
644
EXPECT_EQ(3, message.ByteSize());
646
message.set_friend_(5);
647
EXPECT_EQ(5, message.friend_());
650
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
652
TEST(GeneratedMessageTest, TestOptimizedForSize) {
653
// We rely on the tests in reflection_ops_unittest and wire_format_unittest
654
// to really test that reflection-based methods work. Here we are mostly
655
// just making sure that TestOptimizedForSize actually builds and seems to
658
protobuf_unittest::TestOptimizedForSize message, message2;
660
message.mutable_msg()->set_c(2);
661
message2.CopyFrom(message);
662
EXPECT_EQ(1, message2.i());
663
EXPECT_EQ(2, message2.msg().c());
666
TEST(GeneratedMessageTest, TestEmbedOptimizedForSize) {
667
// Verifies that something optimized for speed can contain something optimized
670
protobuf_unittest::TestEmbedOptimizedForSize message, message2;
671
message.mutable_optional_message()->set_i(1);
672
message.add_repeated_message()->mutable_msg()->set_c(2);
674
message.SerializeToString(&data);
675
ASSERT_TRUE(message2.ParseFromString(data));
676
EXPECT_EQ(1, message2.optional_message().i());
677
EXPECT_EQ(2, message2.repeated_message(0).msg().c());
680
TEST(GeneratedMessageTest, TestSpaceUsed) {
681
unittest::TestAllTypes message1;
682
// sizeof provides a lower bound on SpaceUsed().
683
EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsed());
684
const int empty_message_size = message1.SpaceUsed();
686
// Setting primitive types shouldn't affect the space used.
687
message1.set_optional_int32(123);
688
message1.set_optional_int64(12345);
689
message1.set_optional_uint32(123);
690
message1.set_optional_uint64(12345);
691
EXPECT_EQ(empty_message_size, message1.SpaceUsed());
693
// On some STL implementations, setting the string to a small value should
694
// only increase SpaceUsed() by the size of a string object, though this is
695
// not true everywhere.
696
message1.set_optional_string("abc");
697
EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsed());
699
// Setting a string to a value larger than the string object itself should
700
// increase SpaceUsed(), because it cannot store the value internally.
701
message1.set_optional_string(string(sizeof(string) + 1, 'x'));
702
int min_expected_increase = message1.optional_string().capacity() +
704
EXPECT_LE(empty_message_size + min_expected_increase,
705
message1.SpaceUsed());
707
int previous_size = message1.SpaceUsed();
708
// Adding an optional message should increase the size by the size of the
709
// nested message type. NestedMessage is simple enough (1 int field) that it
710
// is equal to sizeof(NestedMessage)
711
message1.mutable_optional_nested_message();
712
ASSERT_EQ(sizeof(unittest::TestAllTypes::NestedMessage),
713
message1.optional_nested_message().SpaceUsed());
714
EXPECT_EQ(previous_size +
715
sizeof(unittest::TestAllTypes::NestedMessage),
716
message1.SpaceUsed());
719
#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
721
TEST(GeneratedMessageTest, FieldConstantValues) {
722
unittest::TestRequired message;
723
EXPECT_EQ(unittest::TestAllTypes_NestedMessage::kBbFieldNumber, 1);
724
EXPECT_EQ(unittest::TestAllTypes::kOptionalInt32FieldNumber, 1);
725
EXPECT_EQ(unittest::TestAllTypes::kOptionalgroupFieldNumber, 16);
726
EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedMessageFieldNumber, 18);
727
EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedEnumFieldNumber, 21);
728
EXPECT_EQ(unittest::TestAllTypes::kRepeatedInt32FieldNumber, 31);
729
EXPECT_EQ(unittest::TestAllTypes::kRepeatedgroupFieldNumber, 46);
730
EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48);
731
EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51);
734
TEST(GeneratedMessageTest, ExtensionConstantValues) {
735
EXPECT_EQ(unittest::TestRequired::kSingleFieldNumber, 1000);
736
EXPECT_EQ(unittest::TestRequired::kMultiFieldNumber, 1001);
737
EXPECT_EQ(unittest::kOptionalInt32ExtensionFieldNumber, 1);
738
EXPECT_EQ(unittest::kOptionalgroupExtensionFieldNumber, 16);
739
EXPECT_EQ(unittest::kOptionalNestedMessageExtensionFieldNumber, 18);
740
EXPECT_EQ(unittest::kOptionalNestedEnumExtensionFieldNumber, 21);
741
EXPECT_EQ(unittest::kRepeatedInt32ExtensionFieldNumber, 31);
742
EXPECT_EQ(unittest::kRepeatedgroupExtensionFieldNumber, 46);
743
EXPECT_EQ(unittest::kRepeatedNestedMessageExtensionFieldNumber, 48);
744
EXPECT_EQ(unittest::kRepeatedNestedEnumExtensionFieldNumber, 51);
747
// ===================================================================
749
TEST(GeneratedEnumTest, EnumValuesAsSwitchCases) {
750
// Test that our nested enum values can be used as switch cases. This test
751
// doesn't actually do anything, the proof that it works is that it
754
unittest::TestAllTypes::NestedEnum a = unittest::TestAllTypes::BAR;
756
case unittest::TestAllTypes::FOO:
759
case unittest::TestAllTypes::BAR:
762
case unittest::TestAllTypes::BAZ:
765
// no default case: We want to make sure the compiler recognizes that
766
// all cases are covered. (GCC warns if you do not cover all cases of
767
// an enum in a switch.)
770
// Token check just for fun.
774
TEST(GeneratedEnumTest, IsValidValue) {
775
// Test enum IsValidValue.
776
EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(1));
777
EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(2));
778
EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(3));
780
EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(0));
781
EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(4));
783
// Make sure it also works when there are dups.
784
EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(1));
785
EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(2));
786
EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(3));
788
EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(0));
789
EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(4));
792
TEST(GeneratedEnumTest, MinAndMax) {
793
EXPECT_EQ(unittest::TestAllTypes::FOO,
794
unittest::TestAllTypes::NestedEnum_MIN);
795
EXPECT_EQ(unittest::TestAllTypes::BAZ,
796
unittest::TestAllTypes::NestedEnum_MAX);
797
EXPECT_EQ(4, unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
799
EXPECT_EQ(unittest::FOREIGN_FOO, unittest::ForeignEnum_MIN);
800
EXPECT_EQ(unittest::FOREIGN_BAZ, unittest::ForeignEnum_MAX);
801
EXPECT_EQ(7, unittest::ForeignEnum_ARRAYSIZE);
803
EXPECT_EQ(1, unittest::TestEnumWithDupValue_MIN);
804
EXPECT_EQ(3, unittest::TestEnumWithDupValue_MAX);
805
EXPECT_EQ(4, unittest::TestEnumWithDupValue_ARRAYSIZE);
807
EXPECT_EQ(unittest::SPARSE_E, unittest::TestSparseEnum_MIN);
808
EXPECT_EQ(unittest::SPARSE_C, unittest::TestSparseEnum_MAX);
809
EXPECT_EQ(12589235, unittest::TestSparseEnum_ARRAYSIZE);
811
// Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE.
812
void* nullptr = 0; // NULL may be integer-type, not pointer-type.
813
EXPECT_NE(nullptr, &unittest::TestAllTypes::NestedEnum_MIN);
814
EXPECT_NE(nullptr, &unittest::TestAllTypes::NestedEnum_MAX);
815
EXPECT_NE(nullptr, &unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
817
EXPECT_NE(nullptr, &unittest::ForeignEnum_MIN);
818
EXPECT_NE(nullptr, &unittest::ForeignEnum_MAX);
819
EXPECT_NE(nullptr, &unittest::ForeignEnum_ARRAYSIZE);
821
// Make sure we can use _MIN, _MAX and _ARRAYSIZE as switch cases.
822
switch (unittest::SPARSE_A) {
823
case unittest::TestSparseEnum_MIN:
824
case unittest::TestSparseEnum_MAX:
825
case unittest::TestSparseEnum_ARRAYSIZE:
832
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
834
TEST(GeneratedEnumTest, Name) {
835
// "Names" in the presence of dup values are a bit arbitrary.
836
EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO1));
837
EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO2));
839
EXPECT_EQ("SPARSE_A", unittest::TestSparseEnum_Name(unittest::SPARSE_A));
840
EXPECT_EQ("SPARSE_B", unittest::TestSparseEnum_Name(unittest::SPARSE_B));
841
EXPECT_EQ("SPARSE_C", unittest::TestSparseEnum_Name(unittest::SPARSE_C));
842
EXPECT_EQ("SPARSE_D", unittest::TestSparseEnum_Name(unittest::SPARSE_D));
843
EXPECT_EQ("SPARSE_E", unittest::TestSparseEnum_Name(unittest::SPARSE_E));
844
EXPECT_EQ("SPARSE_F", unittest::TestSparseEnum_Name(unittest::SPARSE_F));
845
EXPECT_EQ("SPARSE_G", unittest::TestSparseEnum_Name(unittest::SPARSE_G));
848
TEST(GeneratedEnumTest, Parse) {
849
unittest::TestEnumWithDupValue dup_value = unittest::FOO1;
850
EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO1", &dup_value));
851
EXPECT_EQ(unittest::FOO1, dup_value);
852
EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO2", &dup_value));
853
EXPECT_EQ(unittest::FOO2, dup_value);
854
EXPECT_FALSE(unittest::TestEnumWithDupValue_Parse("FOO", &dup_value));
857
TEST(GeneratedEnumTest, GetEnumDescriptor) {
858
EXPECT_EQ(unittest::TestAllTypes::NestedEnum_descriptor(),
859
GetEnumDescriptor<unittest::TestAllTypes::NestedEnum>());
860
EXPECT_EQ(unittest::ForeignEnum_descriptor(),
861
GetEnumDescriptor<unittest::ForeignEnum>());
862
EXPECT_EQ(unittest::TestEnumWithDupValue_descriptor(),
863
GetEnumDescriptor<unittest::TestEnumWithDupValue>());
864
EXPECT_EQ(unittest::TestSparseEnum_descriptor(),
865
GetEnumDescriptor<unittest::TestSparseEnum>());
868
#endif // PROTOBUF_TEST_NO_DESCRIPTORS
870
// ===================================================================
872
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
874
// Support code for testing services.
875
class GeneratedServiceTest : public testing::Test {
877
class MockTestService : public unittest::TestService {
887
~MockTestService() {}
889
void Reset() { called_ = false; }
891
// implements TestService ----------------------------------------
893
void Foo(RpcController* controller,
894
const unittest::FooRequest* request,
895
unittest::FooResponse* response,
897
ASSERT_FALSE(called_);
900
controller_ = controller;
902
response_ = response;
906
void Bar(RpcController* controller,
907
const unittest::BarRequest* request,
908
unittest::BarResponse* response,
910
ASSERT_FALSE(called_);
913
controller_ = controller;
915
response_ = response;
919
// ---------------------------------------------------------------
923
RpcController* controller_;
924
const Message* request_;
929
class MockRpcChannel : public RpcChannel {
941
if (destroyed_ != NULL) *destroyed_ = true;
944
void Reset() { called_ = false; }
946
// implements TestService ----------------------------------------
948
void CallMethod(const MethodDescriptor* method,
949
RpcController* controller,
950
const Message* request,
953
ASSERT_FALSE(called_);
956
controller_ = controller;
958
response_ = response;
962
// ---------------------------------------------------------------
965
const MethodDescriptor* method_;
966
RpcController* controller_;
967
const Message* request_;
973
class MockController : public RpcController {
976
ADD_FAILURE() << "Reset() not expected during this test.";
978
bool Failed() const {
979
ADD_FAILURE() << "Failed() not expected during this test.";
982
string ErrorText() const {
983
ADD_FAILURE() << "ErrorText() not expected during this test.";
987
ADD_FAILURE() << "StartCancel() not expected during this test.";
989
void SetFailed(const string& reason) {
990
ADD_FAILURE() << "SetFailed() not expected during this test.";
992
bool IsCanceled() const {
993
ADD_FAILURE() << "IsCanceled() not expected during this test.";
996
void NotifyOnCancel(Closure* callback) {
997
ADD_FAILURE() << "NotifyOnCancel() not expected during this test.";
1001
GeneratedServiceTest()
1002
: descriptor_(unittest::TestService::descriptor()),
1003
foo_(descriptor_->FindMethodByName("Foo")),
1004
bar_(descriptor_->FindMethodByName("Bar")),
1005
stub_(&mock_channel_),
1006
done_(NewPermanentCallback(&DoNothing)) {}
1008
virtual void SetUp() {
1009
ASSERT_TRUE(foo_ != NULL);
1010
ASSERT_TRUE(bar_ != NULL);
1013
const ServiceDescriptor* descriptor_;
1014
const MethodDescriptor* foo_;
1015
const MethodDescriptor* bar_;
1017
MockTestService mock_service_;
1018
MockController mock_controller_;
1020
MockRpcChannel mock_channel_;
1021
unittest::TestService::Stub stub_;
1023
// Just so we don't have to re-define these with every test.
1024
unittest::FooRequest foo_request_;
1025
unittest::FooResponse foo_response_;
1026
unittest::BarRequest bar_request_;
1027
unittest::BarResponse bar_response_;
1028
scoped_ptr<Closure> done_;
1031
TEST_F(GeneratedServiceTest, GetDescriptor) {
1032
// Test that GetDescriptor() works.
1034
EXPECT_EQ(descriptor_, mock_service_.GetDescriptor());
1037
TEST_F(GeneratedServiceTest, GetChannel) {
1038
EXPECT_EQ(&mock_channel_, stub_.channel());
1041
TEST_F(GeneratedServiceTest, OwnsChannel) {
1042
MockRpcChannel* channel = new MockRpcChannel;
1043
bool destroyed = false;
1044
channel->destroyed_ = &destroyed;
1047
unittest::TestService::Stub owning_stub(channel,
1048
Service::STUB_OWNS_CHANNEL);
1049
EXPECT_FALSE(destroyed);
1052
EXPECT_TRUE(destroyed);
1055
TEST_F(GeneratedServiceTest, CallMethod) {
1056
// Test that CallMethod() works.
1058
// Call Foo() via CallMethod().
1059
mock_service_.CallMethod(foo_, &mock_controller_,
1060
&foo_request_, &foo_response_, done_.get());
1062
ASSERT_TRUE(mock_service_.called_);
1064
EXPECT_EQ("Foo" , mock_service_.method_ );
1065
EXPECT_EQ(&mock_controller_, mock_service_.controller_);
1066
EXPECT_EQ(&foo_request_ , mock_service_.request_ );
1067
EXPECT_EQ(&foo_response_ , mock_service_.response_ );
1068
EXPECT_EQ(done_.get() , mock_service_.done_ );
1070
// Try again, but call Bar() instead.
1071
mock_service_.Reset();
1072
mock_service_.CallMethod(bar_, &mock_controller_,
1073
&bar_request_, &bar_response_, done_.get());
1075
ASSERT_TRUE(mock_service_.called_);
1076
EXPECT_EQ("Bar", mock_service_.method_);
1079
TEST_F(GeneratedServiceTest, CallMethodTypeFailure) {
1080
// Verify death if we call Foo() with Bar's message types.
1082
#ifdef GTEST_HAS_DEATH_TEST // death tests do not work on Windows yet
1084
mock_service_.CallMethod(foo_, &mock_controller_,
1085
&foo_request_, &bar_response_, done_.get()),
1088
mock_service_.Reset();
1090
mock_service_.CallMethod(foo_, &mock_controller_,
1091
&bar_request_, &foo_response_, done_.get()),
1093
#endif // GTEST_HAS_DEATH_TEST
1096
TEST_F(GeneratedServiceTest, GetPrototypes) {
1097
// Test Get{Request,Response}Prototype() methods.
1099
EXPECT_EQ(&unittest::FooRequest::default_instance(),
1100
&mock_service_.GetRequestPrototype(foo_));
1101
EXPECT_EQ(&unittest::BarRequest::default_instance(),
1102
&mock_service_.GetRequestPrototype(bar_));
1104
EXPECT_EQ(&unittest::FooResponse::default_instance(),
1105
&mock_service_.GetResponsePrototype(foo_));
1106
EXPECT_EQ(&unittest::BarResponse::default_instance(),
1107
&mock_service_.GetResponsePrototype(bar_));
1110
TEST_F(GeneratedServiceTest, Stub) {
1111
// Test that the stub class works.
1113
// Call Foo() via the stub.
1114
stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get());
1116
ASSERT_TRUE(mock_channel_.called_);
1118
EXPECT_EQ(foo_ , mock_channel_.method_ );
1119
EXPECT_EQ(&mock_controller_, mock_channel_.controller_);
1120
EXPECT_EQ(&foo_request_ , mock_channel_.request_ );
1121
EXPECT_EQ(&foo_response_ , mock_channel_.response_ );
1122
EXPECT_EQ(done_.get() , mock_channel_.done_ );
1124
// Call Bar() via the stub.
1125
mock_channel_.Reset();
1126
stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get());
1128
ASSERT_TRUE(mock_channel_.called_);
1129
EXPECT_EQ(bar_, mock_channel_.method_);
1132
TEST_F(GeneratedServiceTest, NotImplemented) {
1133
// Test that failing to implement a method of a service causes it to fail
1134
// with a "not implemented" error message.
1136
// A service which doesn't implement any methods.
1137
class UnimplementedService : public unittest::TestService {
1139
UnimplementedService() {}
1142
UnimplementedService unimplemented_service;
1144
// And a controller which expects to get a "not implemented" error.
1145
class ExpectUnimplementedController : public MockController {
1147
ExpectUnimplementedController() : called_(false) {}
1149
void SetFailed(const string& reason) {
1150
EXPECT_FALSE(called_);
1152
EXPECT_EQ("Method Foo() not implemented.", reason);
1158
ExpectUnimplementedController controller;
1161
unimplemented_service.Foo(&controller, &foo_request_, &foo_response_,
1164
EXPECT_TRUE(controller.called_);
1167
} // namespace cpp_unittest
1169
} // namespace compiler
1171
namespace no_generic_services_test {
1172
// Verify that no class called "TestService" was defined in
1173
// unittest_no_generic_services.pb.h by defining a different type by the same
1174
// name. If such a service was generated, this will not compile.
1175
struct TestService {
1180
namespace compiler {
1182
namespace cpp_unittest {
1184
TEST_F(GeneratedServiceTest, NoGenericServices) {
1185
// Verify that non-services in unittest_no_generic_services.proto were
1187
no_generic_services_test::TestMessage message;
1189
message.SetExtension(no_generic_services_test::test_extension, 123);
1190
no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
1193
// Verify that a ServiceDescriptor is generated for the service even if the
1194
// class itself is not.
1195
const FileDescriptor* file =
1196
no_generic_services_test::TestMessage::descriptor()->file();
1198
ASSERT_EQ(1, file->service_count());
1199
EXPECT_EQ("TestService", file->service(0)->name());
1200
ASSERT_EQ(1, file->service(0)->method_count());
1201
EXPECT_EQ("Foo", file->service(0)->method(0)->name());
1204
#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
1206
// ===================================================================
1208
// This test must run last. It verifies that descriptors were or were not
1209
// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined.
1210
// When this is defined, we skip all tests which are expected to trigger
1211
// descriptor initialization. This verifies that everything else still works
1212
// if descriptors are not initialized.
1213
TEST(DescriptorInitializationTest, Initialized) {
1214
#ifdef PROTOBUF_TEST_NO_DESCRIPTORS
1215
bool should_have_descriptors = false;
1217
bool should_have_descriptors = true;
1220
EXPECT_EQ(should_have_descriptors,
1221
DescriptorPool::generated_pool()->InternalIsFileLoaded(
1222
"google/protobuf/unittest.proto"));
1225
} // namespace cpp_unittest
1228
} // namespace compiler
1229
} // namespace protobuf
1230
} // namespace google