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 
31 // Author: kenton@google.com (Kenton Varda)
32 //  Based on original Protocol Buffers design by
33 //  Sanjay Ghemawat, Jeff Dean, and others.
34 //
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.
46 
47 #include <google/protobuf/compiler/cpp/cpp_unittest.h>
48 
49 #include <memory>
50 #include <vector>
51 
52 #include <google/protobuf/unittest.pb.h>
53 #include <google/protobuf/unittest_optimize_for.pb.h>
54 #include <google/protobuf/unittest_embed_optimize_for.pb.h>
55 #include <google/protobuf/unittest_no_generic_services.pb.h>
56 #include <google/protobuf/test_util.h>
57 #include <google/protobuf/compiler/cpp/cpp_helpers.h>
58 #include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h>
59 #include <google/protobuf/compiler/importer.h>
60 #include <google/protobuf/io/coded_stream.h>
61 #include <google/protobuf/io/zero_copy_stream_impl.h>
62 #include <google/protobuf/descriptor.h>
63 #include <google/protobuf/descriptor.pb.h>
64 #include <google/protobuf/dynamic_message.h>
65 
66 #include <google/protobuf/stubs/common.h>
67 #include <google/protobuf/stubs/strutil.h>
68 #include <google/protobuf/stubs/substitute.h>
69 #include <google/protobuf/testing/googletest.h>
70 #include <gtest/gtest.h>
71 #include <google/protobuf/stubs/stl_util.h>
72 
73 namespace google {
74 namespace protobuf {
75 namespace compiler {
76 namespace cpp {
77 
78 // Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
79 namespace cpp_unittest {
80 
81 namespace protobuf_unittest = ::protobuf_unittest;
82 
83 
84 class MockErrorCollector : public MultiFileErrorCollector {
85  public:
MockErrorCollector()86   MockErrorCollector() {}
~MockErrorCollector()87   ~MockErrorCollector() {}
88 
89   string text_;
90 
91   // implements ErrorCollector ---------------------------------------
AddError(const string & filename,int line,int column,const string & message)92   void AddError(const string& filename, int line, int column,
93                 const string& message) {
94     strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
95                                  filename, line, column, message);
96   }
97 };
98 
99 #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
100 
101 // Test that generated code has proper descriptors:
102 // Parse a descriptor directly (using google::protobuf::compiler::Importer) and
103 // compare it to the one that was produced by generated code.
TEST(GeneratedDescriptorTest,IdenticalDescriptors)104 TEST(GeneratedDescriptorTest, IdenticalDescriptors) {
105   const FileDescriptor* generated_descriptor =
106     unittest::TestAllTypes::descriptor()->file();
107 
108   // Set up the Importer.
109   MockErrorCollector error_collector;
110   DiskSourceTree source_tree;
111   source_tree.MapPath("", TestSourceDir());
112   Importer importer(&source_tree, &error_collector);
113 
114   // Import (parse) unittest.proto.
115   const FileDescriptor* parsed_descriptor =
116     importer.Import("google/protobuf/unittest.proto");
117   EXPECT_EQ("", error_collector.text_);
118   ASSERT_TRUE(parsed_descriptor != NULL);
119 
120   // Test that descriptors are generated correctly by converting them to
121   // FileDescriptorProtos and comparing.
122   FileDescriptorProto generated_decsriptor_proto, parsed_descriptor_proto;
123   generated_descriptor->CopyTo(&generated_decsriptor_proto);
124   parsed_descriptor->CopyTo(&parsed_descriptor_proto);
125 
126   EXPECT_EQ(parsed_descriptor_proto.DebugString(),
127             generated_decsriptor_proto.DebugString());
128 }
129 
130 #endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
131 
132 // ===================================================================
133 
TEST(GeneratedMessageTest,Defaults)134 TEST(GeneratedMessageTest, Defaults) {
135   // Check that all default values are set correctly in the initial message.
136   unittest::TestAllTypes message;
137 
138   TestUtil::ExpectClear(message);
139 
140   // Messages should return pointers to default instances until first use.
141   // (This is not checked by ExpectClear() since it is not actually true after
142   // the fields have been set and then cleared.)
143   EXPECT_EQ(&unittest::TestAllTypes::OptionalGroup::default_instance(),
144             &message.optionalgroup());
145   EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
146             &message.optional_nested_message());
147   EXPECT_EQ(&unittest::ForeignMessage::default_instance(),
148             &message.optional_foreign_message());
149   EXPECT_EQ(&unittest_import::ImportMessage::default_instance(),
150             &message.optional_import_message());
151 }
152 
TEST(GeneratedMessageTest,Int32StringConversion)153 TEST(GeneratedMessageTest, Int32StringConversion) {
154   EXPECT_EQ("971", Int32ToString(971));
155   EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min));
156   EXPECT_EQ("2147483647", Int32ToString(kint32max));
157 }
158 
TEST(GeneratedMessageTest,Int64StringConversion)159 TEST(GeneratedMessageTest, Int64StringConversion) {
160   EXPECT_EQ("GOOGLE_LONGLONG(971)", Int64ToString(971));
161   EXPECT_EQ("GOOGLE_LONGLONG(-2147483648)", Int64ToString(kint32min));
162   EXPECT_EQ("GOOGLE_LONGLONG(~0x7fffffffffffffff)", Int64ToString(kint64min));
163   EXPECT_EQ("GOOGLE_LONGLONG(9223372036854775807)", Int64ToString(kint64max));
164 }
165 
TEST(GeneratedMessageTest,FloatingPointDefaults)166 TEST(GeneratedMessageTest, FloatingPointDefaults) {
167   const unittest::TestExtremeDefaultValues& extreme_default =
168       unittest::TestExtremeDefaultValues::default_instance();
169 
170   EXPECT_EQ(0.0f, extreme_default.zero_float());
171   EXPECT_EQ(1.0f, extreme_default.one_float());
172   EXPECT_EQ(1.5f, extreme_default.small_float());
173   EXPECT_EQ(-1.0f, extreme_default.negative_one_float());
174   EXPECT_EQ(-1.5f, extreme_default.negative_float());
175   EXPECT_EQ(2.0e8f, extreme_default.large_float());
176   EXPECT_EQ(-8e-28f, extreme_default.small_negative_float());
177   EXPECT_EQ(numeric_limits<double>::infinity(),
178             extreme_default.inf_double());
179   EXPECT_EQ(-numeric_limits<double>::infinity(),
180             extreme_default.neg_inf_double());
181   EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double());
182   EXPECT_EQ(numeric_limits<float>::infinity(),
183             extreme_default.inf_float());
184   EXPECT_EQ(-numeric_limits<float>::infinity(),
185             extreme_default.neg_inf_float());
186   EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float());
187 }
188 
TEST(GeneratedMessageTest,Trigraph)189 TEST(GeneratedMessageTest, Trigraph) {
190   const unittest::TestExtremeDefaultValues& extreme_default =
191       unittest::TestExtremeDefaultValues::default_instance();
192 
193   EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph());
194 }
195 
TEST(GeneratedMessageTest,ExtremeSmallIntegerDefault)196 TEST(GeneratedMessageTest, ExtremeSmallIntegerDefault) {
197   const unittest::TestExtremeDefaultValues& extreme_default =
198       unittest::TestExtremeDefaultValues::default_instance();
199   EXPECT_EQ(~0x7fffffff, kint32min);
200   EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min);
201   EXPECT_EQ(kint32min, extreme_default.really_small_int32());
202   EXPECT_EQ(kint64min, extreme_default.really_small_int64());
203 }
204 
TEST(GeneratedMessageTest,Accessors)205 TEST(GeneratedMessageTest, Accessors) {
206   // Set every field to a unique value then go back and check all those
207   // values.
208   unittest::TestAllTypes message;
209 
210   TestUtil::SetAllFields(&message);
211   TestUtil::ExpectAllFieldsSet(message);
212 
213   TestUtil::ModifyRepeatedFields(&message);
214   TestUtil::ExpectRepeatedFieldsModified(message);
215 }
216 
TEST(GeneratedMessageTest,MutableStringDefault)217 TEST(GeneratedMessageTest, MutableStringDefault) {
218   // mutable_foo() for a string should return a string initialized to its
219   // default value.
220   unittest::TestAllTypes message;
221 
222   EXPECT_EQ("hello", *message.mutable_default_string());
223 
224   // Note that the first time we call mutable_foo(), we get a newly-allocated
225   // string, but if we clear it and call it again, we get the same object again.
226   // We should verify that it has its default value in both cases.
227   message.set_default_string("blah");
228   message.Clear();
229 
230   EXPECT_EQ("hello", *message.mutable_default_string());
231 }
232 
TEST(GeneratedMessageTest,StringDefaults)233 TEST(GeneratedMessageTest, StringDefaults) {
234   unittest::TestExtremeDefaultValues message;
235   // Check if '\000' can be used in default string value.
236   EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero());
237   EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero());
238 }
239 
TEST(GeneratedMessageTest,ReleaseString)240 TEST(GeneratedMessageTest, ReleaseString) {
241   // Check that release_foo() starts out NULL, and gives us a value
242   // that we can delete after it's been set.
243   unittest::TestAllTypes message;
244 
245   EXPECT_EQ(NULL, message.release_default_string());
246   EXPECT_FALSE(message.has_default_string());
247   EXPECT_EQ("hello", message.default_string());
248 
249   message.set_default_string("blah");
250   EXPECT_TRUE(message.has_default_string());
251   scoped_ptr<string> str(message.release_default_string());
252   EXPECT_FALSE(message.has_default_string());
253   ASSERT_TRUE(str != NULL);
254   EXPECT_EQ("blah", *str);
255 
256   EXPECT_EQ(NULL, message.release_default_string());
257   EXPECT_FALSE(message.has_default_string());
258   EXPECT_EQ("hello", message.default_string());
259 }
260 
TEST(GeneratedMessageTest,ReleaseMessage)261 TEST(GeneratedMessageTest, ReleaseMessage) {
262   // Check that release_foo() starts out NULL, and gives us a value
263   // that we can delete after it's been set.
264   unittest::TestAllTypes message;
265 
266   EXPECT_EQ(NULL, message.release_optional_nested_message());
267   EXPECT_FALSE(message.has_optional_nested_message());
268 
269   message.mutable_optional_nested_message()->set_bb(1);
270   scoped_ptr<unittest::TestAllTypes::NestedMessage> nest(
271       message.release_optional_nested_message());
272   EXPECT_FALSE(message.has_optional_nested_message());
273   ASSERT_TRUE(nest != NULL);
274   EXPECT_EQ(1, nest->bb());
275 
276   EXPECT_EQ(NULL, message.release_optional_nested_message());
277   EXPECT_FALSE(message.has_optional_nested_message());
278 }
279 
TEST(GeneratedMessageTest,SetAllocatedString)280 TEST(GeneratedMessageTest, SetAllocatedString) {
281   // Check that set_allocated_foo() works for strings.
282   unittest::TestAllTypes message;
283 
284   EXPECT_FALSE(message.has_optional_string());
285   const string kHello("hello");
286   message.set_optional_string(kHello);
287   EXPECT_TRUE(message.has_optional_string());
288 
289   message.set_allocated_optional_string(NULL);
290   EXPECT_FALSE(message.has_optional_string());
291   EXPECT_EQ("", message.optional_string());
292 
293   message.set_allocated_optional_string(new string(kHello));
294   EXPECT_TRUE(message.has_optional_string());
295   EXPECT_EQ(kHello, message.optional_string());
296 }
297 
TEST(GeneratedMessageTest,SetAllocatedMessage)298 TEST(GeneratedMessageTest, SetAllocatedMessage) {
299   // Check that set_allocated_foo() can be called in all cases.
300   unittest::TestAllTypes message;
301 
302   EXPECT_FALSE(message.has_optional_nested_message());
303 
304   message.mutable_optional_nested_message()->set_bb(1);
305   EXPECT_TRUE(message.has_optional_nested_message());
306 
307   message.set_allocated_optional_nested_message(NULL);
308   EXPECT_FALSE(message.has_optional_nested_message());
309   EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
310             &message.optional_nested_message());
311 
312   message.mutable_optional_nested_message()->set_bb(1);
313   unittest::TestAllTypes::NestedMessage* nest =
314       message.release_optional_nested_message();
315   ASSERT_TRUE(nest != NULL);
316   EXPECT_FALSE(message.has_optional_nested_message());
317 
318   message.set_allocated_optional_nested_message(nest);
319   EXPECT_TRUE(message.has_optional_nested_message());
320   EXPECT_EQ(1, message.optional_nested_message().bb());
321 }
322 
TEST(GeneratedMessageTest,Clear)323 TEST(GeneratedMessageTest, Clear) {
324   // Set every field to a unique value, clear the message, then check that
325   // it is cleared.
326   unittest::TestAllTypes message;
327 
328   TestUtil::SetAllFields(&message);
329   message.Clear();
330   TestUtil::ExpectClear(message);
331 
332   // Unlike with the defaults test, we do NOT expect that requesting embedded
333   // messages will return a pointer to the default instance.  Instead, they
334   // should return the objects that were created when mutable_blah() was
335   // called.
336   EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(),
337             &message.optionalgroup());
338   EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(),
339             &message.optional_nested_message());
340   EXPECT_NE(&unittest::ForeignMessage::default_instance(),
341             &message.optional_foreign_message());
342   EXPECT_NE(&unittest_import::ImportMessage::default_instance(),
343             &message.optional_import_message());
344 }
345 
TEST(GeneratedMessageTest,EmbeddedNullsInBytesCharStar)346 TEST(GeneratedMessageTest, EmbeddedNullsInBytesCharStar) {
347   unittest::TestAllTypes message;
348 
349   const char* value = "\0lalala\0\0";
350   message.set_optional_bytes(value, 9);
351   ASSERT_EQ(9, message.optional_bytes().size());
352   EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9));
353 
354   message.add_repeated_bytes(value, 9);
355   ASSERT_EQ(9, message.repeated_bytes(0).size());
356   EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9));
357 }
358 
TEST(GeneratedMessageTest,ClearOneField)359 TEST(GeneratedMessageTest, ClearOneField) {
360   // Set every field to a unique value, then clear one value and insure that
361   // only that one value is cleared.
362   unittest::TestAllTypes message;
363 
364   TestUtil::SetAllFields(&message);
365   int64 original_value = message.optional_int64();
366 
367   // Clear the field and make sure it shows up as cleared.
368   message.clear_optional_int64();
369   EXPECT_FALSE(message.has_optional_int64());
370   EXPECT_EQ(0, message.optional_int64());
371 
372   // Other adjacent fields should not be cleared.
373   EXPECT_TRUE(message.has_optional_int32());
374   EXPECT_TRUE(message.has_optional_uint32());
375 
376   // Make sure if we set it again, then all fields are set.
377   message.set_optional_int64(original_value);
378   TestUtil::ExpectAllFieldsSet(message);
379 }
380 
TEST(GeneratedMessageTest,StringCharStarLength)381 TEST(GeneratedMessageTest, StringCharStarLength) {
382   // Verify that we can use a char*,length to set one of the string fields.
383   unittest::TestAllTypes message;
384   message.set_optional_string("abcdef", 3);
385   EXPECT_EQ("abc", message.optional_string());
386 
387   // Verify that we can use a char*,length to add to a repeated string field.
388   message.add_repeated_string("abcdef", 3);
389   EXPECT_EQ(1, message.repeated_string_size());
390   EXPECT_EQ("abc", message.repeated_string(0));
391 
392   // Verify that we can use a char*,length to set a repeated string field.
393   message.set_repeated_string(0, "wxyz", 2);
394   EXPECT_EQ("wx", message.repeated_string(0));
395 }
396 
397 
TEST(GeneratedMessageTest,CopyFrom)398 TEST(GeneratedMessageTest, CopyFrom) {
399   unittest::TestAllTypes message1, message2;
400 
401   TestUtil::SetAllFields(&message1);
402   message2.CopyFrom(message1);
403   TestUtil::ExpectAllFieldsSet(message2);
404 
405   // Copying from self should be a no-op.
406   message2.CopyFrom(message2);
407   TestUtil::ExpectAllFieldsSet(message2);
408 }
409 
410 
TEST(GeneratedMessageTest,SwapWithEmpty)411 TEST(GeneratedMessageTest, SwapWithEmpty) {
412   unittest::TestAllTypes message1, message2;
413   TestUtil::SetAllFields(&message1);
414 
415   TestUtil::ExpectAllFieldsSet(message1);
416   TestUtil::ExpectClear(message2);
417   message1.Swap(&message2);
418   TestUtil::ExpectAllFieldsSet(message2);
419   TestUtil::ExpectClear(message1);
420 }
421 
TEST(GeneratedMessageTest,SwapWithSelf)422 TEST(GeneratedMessageTest, SwapWithSelf) {
423   unittest::TestAllTypes message;
424   TestUtil::SetAllFields(&message);
425   TestUtil::ExpectAllFieldsSet(message);
426   message.Swap(&message);
427   TestUtil::ExpectAllFieldsSet(message);
428 }
429 
TEST(GeneratedMessageTest,SwapWithOther)430 TEST(GeneratedMessageTest, SwapWithOther) {
431   unittest::TestAllTypes message1, message2;
432 
433   message1.set_optional_int32(123);
434   message1.set_optional_string("abc");
435   message1.mutable_optional_nested_message()->set_bb(1);
436   message1.set_optional_nested_enum(unittest::TestAllTypes::FOO);
437   message1.add_repeated_int32(1);
438   message1.add_repeated_int32(2);
439   message1.add_repeated_string("a");
440   message1.add_repeated_string("b");
441   message1.add_repeated_nested_message()->set_bb(7);
442   message1.add_repeated_nested_message()->set_bb(8);
443   message1.add_repeated_nested_enum(unittest::TestAllTypes::FOO);
444   message1.add_repeated_nested_enum(unittest::TestAllTypes::BAR);
445 
446   message2.set_optional_int32(456);
447   message2.set_optional_string("def");
448   message2.mutable_optional_nested_message()->set_bb(2);
449   message2.set_optional_nested_enum(unittest::TestAllTypes::BAR);
450   message2.add_repeated_int32(3);
451   message2.add_repeated_string("c");
452   message2.add_repeated_nested_message()->set_bb(9);
453   message2.add_repeated_nested_enum(unittest::TestAllTypes::BAZ);
454 
455   message1.Swap(&message2);
456 
457   EXPECT_EQ(456, message1.optional_int32());
458   EXPECT_EQ("def", message1.optional_string());
459   EXPECT_EQ(2, message1.optional_nested_message().bb());
460   EXPECT_EQ(unittest::TestAllTypes::BAR, message1.optional_nested_enum());
461   ASSERT_EQ(1, message1.repeated_int32_size());
462   EXPECT_EQ(3, message1.repeated_int32(0));
463   ASSERT_EQ(1, message1.repeated_string_size());
464   EXPECT_EQ("c", message1.repeated_string(0));
465   ASSERT_EQ(1, message1.repeated_nested_message_size());
466   EXPECT_EQ(9, message1.repeated_nested_message(0).bb());
467   ASSERT_EQ(1, message1.repeated_nested_enum_size());
468   EXPECT_EQ(unittest::TestAllTypes::BAZ, message1.repeated_nested_enum(0));
469 
470   EXPECT_EQ(123, message2.optional_int32());
471   EXPECT_EQ("abc", message2.optional_string());
472   EXPECT_EQ(1, message2.optional_nested_message().bb());
473   EXPECT_EQ(unittest::TestAllTypes::FOO, message2.optional_nested_enum());
474   ASSERT_EQ(2, message2.repeated_int32_size());
475   EXPECT_EQ(1, message2.repeated_int32(0));
476   EXPECT_EQ(2, message2.repeated_int32(1));
477   ASSERT_EQ(2, message2.repeated_string_size());
478   EXPECT_EQ("a", message2.repeated_string(0));
479   EXPECT_EQ("b", message2.repeated_string(1));
480   ASSERT_EQ(2, message2.repeated_nested_message_size());
481   EXPECT_EQ(7, message2.repeated_nested_message(0).bb());
482   EXPECT_EQ(8, message2.repeated_nested_message(1).bb());
483   ASSERT_EQ(2, message2.repeated_nested_enum_size());
484   EXPECT_EQ(unittest::TestAllTypes::FOO, message2.repeated_nested_enum(0));
485   EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1));
486 }
487 
TEST(GeneratedMessageTest,CopyConstructor)488 TEST(GeneratedMessageTest, CopyConstructor) {
489   unittest::TestAllTypes message1;
490   TestUtil::SetAllFields(&message1);
491 
492   unittest::TestAllTypes message2(message1);
493   TestUtil::ExpectAllFieldsSet(message2);
494 }
495 
TEST(GeneratedMessageTest,CopyAssignmentOperator)496 TEST(GeneratedMessageTest, CopyAssignmentOperator) {
497   unittest::TestAllTypes message1;
498   TestUtil::SetAllFields(&message1);
499 
500   unittest::TestAllTypes message2;
501   message2 = message1;
502   TestUtil::ExpectAllFieldsSet(message2);
503 
504   // Make sure that self-assignment does something sane.
505   message2.operator=(message2);
506   TestUtil::ExpectAllFieldsSet(message2);
507 }
508 
509 #if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
510     !defined(GOOGLE_PROTOBUF_NO_RTTI)
TEST(GeneratedMessageTest,UpcastCopyFrom)511 TEST(GeneratedMessageTest, UpcastCopyFrom) {
512   // Test the CopyFrom method that takes in the generic const Message&
513   // parameter.
514   unittest::TestAllTypes message1, message2;
515 
516   TestUtil::SetAllFields(&message1);
517 
518   const Message* source = implicit_cast<const Message*>(&message1);
519   message2.CopyFrom(*source);
520 
521   TestUtil::ExpectAllFieldsSet(message2);
522 }
523 #endif
524 
525 #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
526 
TEST(GeneratedMessageTest,DynamicMessageCopyFrom)527 TEST(GeneratedMessageTest, DynamicMessageCopyFrom) {
528   // Test copying from a DynamicMessage, which must fall back to using
529   // reflection.
530   unittest::TestAllTypes message2;
531 
532   // Construct a new version of the dynamic message via the factory.
533   DynamicMessageFactory factory;
534   scoped_ptr<Message> message1;
535   message1.reset(factory.GetPrototype(
536                      unittest::TestAllTypes::descriptor())->New());
537 
538   TestUtil::ReflectionTester reflection_tester(
539     unittest::TestAllTypes::descriptor());
540   reflection_tester.SetAllFieldsViaReflection(message1.get());
541 
542   message2.CopyFrom(*message1);
543 
544   TestUtil::ExpectAllFieldsSet(message2);
545 }
546 
547 #endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
548 
TEST(GeneratedMessageTest,NonEmptyMergeFrom)549 TEST(GeneratedMessageTest, NonEmptyMergeFrom) {
550   // Test merging with a non-empty message. Code is a modified form
551   // of that found in google/protobuf/reflection_ops_unittest.cc.
552   unittest::TestAllTypes message1, message2;
553 
554   TestUtil::SetAllFields(&message1);
555 
556   // This field will test merging into an empty spot.
557   message2.set_optional_int32(message1.optional_int32());
558   message1.clear_optional_int32();
559 
560   // This tests overwriting.
561   message2.set_optional_string(message1.optional_string());
562   message1.set_optional_string("something else");
563 
564   // This tests concatenating.
565   message2.add_repeated_int32(message1.repeated_int32(1));
566   int32 i = message1.repeated_int32(0);
567   message1.clear_repeated_int32();
568   message1.add_repeated_int32(i);
569 
570   message1.MergeFrom(message2);
571 
572   TestUtil::ExpectAllFieldsSet(message1);
573 }
574 
575 #if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
576     !defined(GOOGLE_PROTOBUF_NO_RTTI)
577 #ifdef PROTOBUF_HAS_DEATH_TEST
578 
TEST(GeneratedMessageTest,MergeFromSelf)579 TEST(GeneratedMessageTest, MergeFromSelf) {
580   unittest::TestAllTypes message;
581   EXPECT_DEATH(message.MergeFrom(message), "&from");
582   EXPECT_DEATH(message.MergeFrom(implicit_cast<const Message&>(message)),
583                "&from");
584 }
585 
586 #endif  // PROTOBUF_HAS_DEATH_TEST
587 #endif  // !PROTOBUF_TEST_NO_DESCRIPTORS || !GOOGLE_PROTOBUF_NO_RTTI
588 
589 // Test the generated SerializeWithCachedSizesToArray(),
TEST(GeneratedMessageTest,SerializationToArray)590 TEST(GeneratedMessageTest, SerializationToArray) {
591   unittest::TestAllTypes message1, message2;
592   string data;
593   TestUtil::SetAllFields(&message1);
594   int size = message1.ByteSize();
595   data.resize(size);
596   uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
597   uint8* end = message1.SerializeWithCachedSizesToArray(start);
598   EXPECT_EQ(size, end - start);
599   EXPECT_TRUE(message2.ParseFromString(data));
600   TestUtil::ExpectAllFieldsSet(message2);
601 
602 }
603 
TEST(GeneratedMessageTest,PackedFieldsSerializationToArray)604 TEST(GeneratedMessageTest, PackedFieldsSerializationToArray) {
605   unittest::TestPackedTypes packed_message1, packed_message2;
606   string packed_data;
607   TestUtil::SetPackedFields(&packed_message1);
608   int packed_size = packed_message1.ByteSize();
609   packed_data.resize(packed_size);
610   uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data));
611   uint8* end = packed_message1.SerializeWithCachedSizesToArray(start);
612   EXPECT_EQ(packed_size, end - start);
613   EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
614   TestUtil::ExpectPackedFieldsSet(packed_message2);
615 }
616 
617 // Test the generated SerializeWithCachedSizes() by forcing the buffer to write
618 // one byte at a time.
TEST(GeneratedMessageTest,SerializationToStream)619 TEST(GeneratedMessageTest, SerializationToStream) {
620   unittest::TestAllTypes message1, message2;
621   TestUtil::SetAllFields(&message1);
622   int size = message1.ByteSize();
623   string data;
624   data.resize(size);
625   {
626     // Allow the output stream to buffer only one byte at a time.
627     io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
628     io::CodedOutputStream output_stream(&array_stream);
629     message1.SerializeWithCachedSizes(&output_stream);
630     EXPECT_FALSE(output_stream.HadError());
631     EXPECT_EQ(size, output_stream.ByteCount());
632   }
633   EXPECT_TRUE(message2.ParseFromString(data));
634   TestUtil::ExpectAllFieldsSet(message2);
635 
636 }
637 
TEST(GeneratedMessageTest,PackedFieldsSerializationToStream)638 TEST(GeneratedMessageTest, PackedFieldsSerializationToStream) {
639   unittest::TestPackedTypes message1, message2;
640   TestUtil::SetPackedFields(&message1);
641   int size = message1.ByteSize();
642   string data;
643   data.resize(size);
644   {
645     // Allow the output stream to buffer only one byte at a time.
646     io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
647     io::CodedOutputStream output_stream(&array_stream);
648     message1.SerializeWithCachedSizes(&output_stream);
649     EXPECT_FALSE(output_stream.HadError());
650     EXPECT_EQ(size, output_stream.ByteCount());
651   }
652   EXPECT_TRUE(message2.ParseFromString(data));
653   TestUtil::ExpectPackedFieldsSet(message2);
654 }
655 
656 
TEST(GeneratedMessageTest,Required)657 TEST(GeneratedMessageTest, Required) {
658   // Test that IsInitialized() returns false if required fields are missing.
659   unittest::TestRequired message;
660 
661   EXPECT_FALSE(message.IsInitialized());
662   message.set_a(1);
663   EXPECT_FALSE(message.IsInitialized());
664   message.set_b(2);
665   EXPECT_FALSE(message.IsInitialized());
666   message.set_c(3);
667   EXPECT_TRUE(message.IsInitialized());
668 }
669 
TEST(GeneratedMessageTest,RequiredForeign)670 TEST(GeneratedMessageTest, RequiredForeign) {
671   // Test that IsInitialized() returns false if required fields in nested
672   // messages are missing.
673   unittest::TestRequiredForeign message;
674 
675   EXPECT_TRUE(message.IsInitialized());
676 
677   message.mutable_optional_message();
678   EXPECT_FALSE(message.IsInitialized());
679 
680   message.mutable_optional_message()->set_a(1);
681   message.mutable_optional_message()->set_b(2);
682   message.mutable_optional_message()->set_c(3);
683   EXPECT_TRUE(message.IsInitialized());
684 
685   message.add_repeated_message();
686   EXPECT_FALSE(message.IsInitialized());
687 
688   message.mutable_repeated_message(0)->set_a(1);
689   message.mutable_repeated_message(0)->set_b(2);
690   message.mutable_repeated_message(0)->set_c(3);
691   EXPECT_TRUE(message.IsInitialized());
692 }
693 
TEST(GeneratedMessageTest,ForeignNested)694 TEST(GeneratedMessageTest, ForeignNested) {
695   // Test that TestAllTypes::NestedMessage can be embedded directly into
696   // another message.
697   unittest::TestForeignNested message;
698 
699   // If this compiles and runs without crashing, it must work.  We have
700   // nothing more to test.
701   unittest::TestAllTypes::NestedMessage* nested =
702     message.mutable_foreign_nested();
703   nested->set_bb(1);
704 }
705 
TEST(GeneratedMessageTest,ReallyLargeTagNumber)706 TEST(GeneratedMessageTest, ReallyLargeTagNumber) {
707   // Test that really large tag numbers don't break anything.
708   unittest::TestReallyLargeTagNumber message1, message2;
709   string data;
710 
711   // For the most part, if this compiles and runs then we're probably good.
712   // (The most likely cause for failure would be if something were attempting
713   // to allocate a lookup table of some sort using tag numbers as the index.)
714   // We'll try serializing just for fun.
715   message1.set_a(1234);
716   message1.set_bb(5678);
717   message1.SerializeToString(&data);
718   EXPECT_TRUE(message2.ParseFromString(data));
719   EXPECT_EQ(1234, message2.a());
720   EXPECT_EQ(5678, message2.bb());
721 }
722 
TEST(GeneratedMessageTest,MutualRecursion)723 TEST(GeneratedMessageTest, MutualRecursion) {
724   // Test that mutually-recursive message types work.
725   unittest::TestMutualRecursionA message;
726   unittest::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a();
727   unittest::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a();
728 
729   // Again, if the above compiles and runs, that's all we really have to
730   // test, but just for run we'll check that the system didn't somehow come
731   // up with a pointer loop...
732   EXPECT_NE(&message, nested);
733   EXPECT_NE(&message, nested2);
734   EXPECT_NE(nested, nested2);
735 }
736 
TEST(GeneratedMessageTest,CamelCaseFieldNames)737 TEST(GeneratedMessageTest, CamelCaseFieldNames) {
738   // This test is mainly checking that the following compiles, which verifies
739   // that the field names were coerced to lower-case.
740   //
741   // Protocol buffers standard style is to use lowercase-with-underscores for
742   // field names.  Some old proto1 .protos unfortunately used camel-case field
743   // names.  In proto1, these names were forced to lower-case.  So, we do the
744   // same thing in proto2.
745 
746   unittest::TestCamelCaseFieldNames message;
747 
748   message.set_primitivefield(2);
749   message.set_stringfield("foo");
750   message.set_enumfield(unittest::FOREIGN_FOO);
751   message.mutable_messagefield()->set_c(6);
752 
753   message.add_repeatedprimitivefield(8);
754   message.add_repeatedstringfield("qux");
755   message.add_repeatedenumfield(unittest::FOREIGN_BAR);
756   message.add_repeatedmessagefield()->set_c(15);
757 
758   EXPECT_EQ(2, message.primitivefield());
759   EXPECT_EQ("foo", message.stringfield());
760   EXPECT_EQ(unittest::FOREIGN_FOO, message.enumfield());
761   EXPECT_EQ(6, message.messagefield().c());
762 
763   EXPECT_EQ(8, message.repeatedprimitivefield(0));
764   EXPECT_EQ("qux", message.repeatedstringfield(0));
765   EXPECT_EQ(unittest::FOREIGN_BAR, message.repeatedenumfield(0));
766   EXPECT_EQ(15, message.repeatedmessagefield(0).c());
767 }
768 
TEST(GeneratedMessageTest,TestConflictingSymbolNames)769 TEST(GeneratedMessageTest, TestConflictingSymbolNames) {
770   // test_bad_identifiers.proto successfully compiled, then it works.  The
771   // following is just a token usage to insure that the code is, in fact,
772   // being compiled and linked.
773 
774   protobuf_unittest::TestConflictingSymbolNames message;
775   message.set_uint32(1);
776   EXPECT_EQ(3, message.ByteSize());
777 
778   message.set_friend_(5);
779   EXPECT_EQ(5, message.friend_());
780 
781   message.set_class_(6);
782   EXPECT_EQ(6, message.class_());
783 
784   // Instantiate extension template functions to test conflicting template
785   // parameter names.
786   typedef protobuf_unittest::TestConflictingSymbolNamesExtension ExtensionMessage;
787   message.AddExtension(ExtensionMessage::repeated_int32_ext, 123);
788   EXPECT_EQ(123,
789             message.GetExtension(ExtensionMessage::repeated_int32_ext, 0));
790 }
791 
792 #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
793 
TEST(GeneratedMessageTest,TestOptimizedForSize)794 TEST(GeneratedMessageTest, TestOptimizedForSize) {
795   // We rely on the tests in reflection_ops_unittest and wire_format_unittest
796   // to really test that reflection-based methods work.  Here we are mostly
797   // just making sure that TestOptimizedForSize actually builds and seems to
798   // function.
799 
800   protobuf_unittest::TestOptimizedForSize message, message2;
801   message.set_i(1);
802   message.mutable_msg()->set_c(2);
803   message2.CopyFrom(message);
804   EXPECT_EQ(1, message2.i());
805   EXPECT_EQ(2, message2.msg().c());
806 }
807 
TEST(GeneratedMessageTest,TestEmbedOptimizedForSize)808 TEST(GeneratedMessageTest, TestEmbedOptimizedForSize) {
809   // Verifies that something optimized for speed can contain something optimized
810   // for size.
811 
812   protobuf_unittest::TestEmbedOptimizedForSize message, message2;
813   message.mutable_optional_message()->set_i(1);
814   message.add_repeated_message()->mutable_msg()->set_c(2);
815   string data;
816   message.SerializeToString(&data);
817   ASSERT_TRUE(message2.ParseFromString(data));
818   EXPECT_EQ(1, message2.optional_message().i());
819   EXPECT_EQ(2, message2.repeated_message(0).msg().c());
820 }
821 
TEST(GeneratedMessageTest,TestSpaceUsed)822 TEST(GeneratedMessageTest, TestSpaceUsed) {
823   unittest::TestAllTypes message1;
824   // sizeof provides a lower bound on SpaceUsed().
825   EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsed());
826   const int empty_message_size = message1.SpaceUsed();
827 
828   // Setting primitive types shouldn't affect the space used.
829   message1.set_optional_int32(123);
830   message1.set_optional_int64(12345);
831   message1.set_optional_uint32(123);
832   message1.set_optional_uint64(12345);
833   EXPECT_EQ(empty_message_size, message1.SpaceUsed());
834 
835   // On some STL implementations, setting the string to a small value should
836   // only increase SpaceUsed() by the size of a string object, though this is
837   // not true everywhere.
838   message1.set_optional_string("abc");
839   EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsed());
840 
841   // Setting a string to a value larger than the string object itself should
842   // increase SpaceUsed(), because it cannot store the value internally.
843   message1.set_optional_string(string(sizeof(string) + 1, 'x'));
844   int min_expected_increase = message1.optional_string().capacity() +
845       sizeof(string);
846   EXPECT_LE(empty_message_size + min_expected_increase,
847             message1.SpaceUsed());
848 
849   int previous_size = message1.SpaceUsed();
850   // Adding an optional message should increase the size by the size of the
851   // nested message type. NestedMessage is simple enough (1 int field) that it
852   // is equal to sizeof(NestedMessage)
853   message1.mutable_optional_nested_message();
854   ASSERT_EQ(sizeof(unittest::TestAllTypes::NestedMessage),
855             message1.optional_nested_message().SpaceUsed());
856   EXPECT_EQ(previous_size +
857             sizeof(unittest::TestAllTypes::NestedMessage),
858             message1.SpaceUsed());
859 }
860 
TEST(GeneratedMessageTest,TestOneofSpaceUsed)861 TEST(GeneratedMessageTest, TestOneofSpaceUsed) {
862   unittest::TestOneof2 message1;
863   EXPECT_LE(sizeof(unittest::TestOneof2), message1.SpaceUsed());
864 
865   const int empty_message_size = message1.SpaceUsed();
866   // Setting primitive types shouldn't affect the space used.
867   message1.set_foo_int(123);
868   message1.set_bar_int(12345);
869   EXPECT_EQ(empty_message_size, message1.SpaceUsed());
870 
871   // Setting a string in oneof to a small value should only increase SpaceUsed()
872   // by the size of a string object.
873   message1.set_foo_string("abc");
874   EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsed());
875 
876   // Setting a string in oneof to a value larger than the string object itself
877   // should increase SpaceUsed(), because it cannot store the value internally.
878   message1.set_foo_string(string(sizeof(string) + 1, 'x'));
879   int min_expected_increase = message1.foo_string().capacity() +
880       sizeof(string);
881   EXPECT_LE(empty_message_size + min_expected_increase,
882             message1.SpaceUsed());
883 
884   // Setting a message in oneof should delete the other fields and increase the
885   // size by the size of the nested message type. NestedMessage is simple enough
886   // that it is equal to sizeof(NestedMessage)
887   message1.mutable_foo_message();
888   ASSERT_EQ(sizeof(unittest::TestOneof2::NestedMessage),
889             message1.foo_message().SpaceUsed());
890   EXPECT_EQ(empty_message_size +
891             sizeof(unittest::TestOneof2::NestedMessage),
892             message1.SpaceUsed());
893 }
894 
895 #endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
896 
897 
TEST(GeneratedMessageTest,FieldConstantValues)898 TEST(GeneratedMessageTest, FieldConstantValues) {
899   unittest::TestRequired message;
900   EXPECT_EQ(unittest::TestAllTypes_NestedMessage::kBbFieldNumber, 1);
901   EXPECT_EQ(unittest::TestAllTypes::kOptionalInt32FieldNumber, 1);
902   EXPECT_EQ(unittest::TestAllTypes::kOptionalgroupFieldNumber, 16);
903   EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedMessageFieldNumber, 18);
904   EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedEnumFieldNumber, 21);
905   EXPECT_EQ(unittest::TestAllTypes::kRepeatedInt32FieldNumber, 31);
906   EXPECT_EQ(unittest::TestAllTypes::kRepeatedgroupFieldNumber, 46);
907   EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48);
908   EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51);
909 }
910 
TEST(GeneratedMessageTest,ExtensionConstantValues)911 TEST(GeneratedMessageTest, ExtensionConstantValues) {
912   EXPECT_EQ(unittest::TestRequired::kSingleFieldNumber, 1000);
913   EXPECT_EQ(unittest::TestRequired::kMultiFieldNumber, 1001);
914   EXPECT_EQ(unittest::kOptionalInt32ExtensionFieldNumber, 1);
915   EXPECT_EQ(unittest::kOptionalgroupExtensionFieldNumber, 16);
916   EXPECT_EQ(unittest::kOptionalNestedMessageExtensionFieldNumber, 18);
917   EXPECT_EQ(unittest::kOptionalNestedEnumExtensionFieldNumber, 21);
918   EXPECT_EQ(unittest::kRepeatedInt32ExtensionFieldNumber, 31);
919   EXPECT_EQ(unittest::kRepeatedgroupExtensionFieldNumber, 46);
920   EXPECT_EQ(unittest::kRepeatedNestedMessageExtensionFieldNumber, 48);
921   EXPECT_EQ(unittest::kRepeatedNestedEnumExtensionFieldNumber, 51);
922 }
923 
924 // ===================================================================
925 
TEST(GeneratedEnumTest,EnumValuesAsSwitchCases)926 TEST(GeneratedEnumTest, EnumValuesAsSwitchCases) {
927   // Test that our nested enum values can be used as switch cases.  This test
928   // doesn't actually do anything, the proof that it works is that it
929   // compiles.
930   int i =0;
931   unittest::TestAllTypes::NestedEnum a = unittest::TestAllTypes::BAR;
932   switch (a) {
933     case unittest::TestAllTypes::FOO:
934       i = 1;
935       break;
936     case unittest::TestAllTypes::BAR:
937       i = 2;
938       break;
939     case unittest::TestAllTypes::BAZ:
940       i = 3;
941       break;
942     case unittest::TestAllTypes::NEG:
943       i = -1;
944       break;
945     // no default case:  We want to make sure the compiler recognizes that
946     //   all cases are covered.  (GCC warns if you do not cover all cases of
947     //   an enum in a switch.)
948   }
949 
950   // Token check just for fun.
951   EXPECT_EQ(2, i);
952 }
953 
TEST(GeneratedEnumTest,IsValidValue)954 TEST(GeneratedEnumTest, IsValidValue) {
955   // Test enum IsValidValue.
956   EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(1));
957   EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(2));
958   EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(3));
959 
960   EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(0));
961   EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(4));
962 
963   // Make sure it also works when there are dups.
964   EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(1));
965   EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(2));
966   EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(3));
967 
968   EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(0));
969   EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(4));
970 }
971 
TEST(GeneratedEnumTest,MinAndMax)972 TEST(GeneratedEnumTest, MinAndMax) {
973   EXPECT_EQ(unittest::TestAllTypes::NEG,
974             unittest::TestAllTypes::NestedEnum_MIN);
975   EXPECT_EQ(unittest::TestAllTypes::BAZ,
976             unittest::TestAllTypes::NestedEnum_MAX);
977   EXPECT_EQ(4, unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
978 
979   EXPECT_EQ(unittest::FOREIGN_FOO, unittest::ForeignEnum_MIN);
980   EXPECT_EQ(unittest::FOREIGN_BAZ, unittest::ForeignEnum_MAX);
981   EXPECT_EQ(7, unittest::ForeignEnum_ARRAYSIZE);
982 
983   EXPECT_EQ(1, unittest::TestEnumWithDupValue_MIN);
984   EXPECT_EQ(3, unittest::TestEnumWithDupValue_MAX);
985   EXPECT_EQ(4, unittest::TestEnumWithDupValue_ARRAYSIZE);
986 
987   EXPECT_EQ(unittest::SPARSE_E, unittest::TestSparseEnum_MIN);
988   EXPECT_EQ(unittest::SPARSE_C, unittest::TestSparseEnum_MAX);
989   EXPECT_EQ(12589235, unittest::TestSparseEnum_ARRAYSIZE);
990 
991   // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE.
992   void* null_pointer = 0;  // NULL may be integer-type, not pointer-type.
993   EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MIN);
994   EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MAX);
995   EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
996 
997   EXPECT_NE(null_pointer, &unittest::ForeignEnum_MIN);
998   EXPECT_NE(null_pointer, &unittest::ForeignEnum_MAX);
999   EXPECT_NE(null_pointer, &unittest::ForeignEnum_ARRAYSIZE);
1000 
1001   // Make sure we can use _MIN and _MAX as switch cases.
1002   switch (unittest::SPARSE_A) {
1003     case unittest::TestSparseEnum_MIN:
1004     case unittest::TestSparseEnum_MAX:
1005       break;
1006     default:
1007       break;
1008   }
1009 }
1010 
1011 #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
1012 
TEST(GeneratedEnumTest,Name)1013 TEST(GeneratedEnumTest, Name) {
1014   // "Names" in the presence of dup values are a bit arbitrary.
1015   EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO1));
1016   EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO2));
1017 
1018   EXPECT_EQ("SPARSE_A", unittest::TestSparseEnum_Name(unittest::SPARSE_A));
1019   EXPECT_EQ("SPARSE_B", unittest::TestSparseEnum_Name(unittest::SPARSE_B));
1020   EXPECT_EQ("SPARSE_C", unittest::TestSparseEnum_Name(unittest::SPARSE_C));
1021   EXPECT_EQ("SPARSE_D", unittest::TestSparseEnum_Name(unittest::SPARSE_D));
1022   EXPECT_EQ("SPARSE_E", unittest::TestSparseEnum_Name(unittest::SPARSE_E));
1023   EXPECT_EQ("SPARSE_F", unittest::TestSparseEnum_Name(unittest::SPARSE_F));
1024   EXPECT_EQ("SPARSE_G", unittest::TestSparseEnum_Name(unittest::SPARSE_G));
1025 }
1026 
TEST(GeneratedEnumTest,Parse)1027 TEST(GeneratedEnumTest, Parse) {
1028   unittest::TestEnumWithDupValue dup_value = unittest::FOO1;
1029   EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO1", &dup_value));
1030   EXPECT_EQ(unittest::FOO1, dup_value);
1031   EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO2", &dup_value));
1032   EXPECT_EQ(unittest::FOO2, dup_value);
1033   EXPECT_FALSE(unittest::TestEnumWithDupValue_Parse("FOO", &dup_value));
1034 }
1035 
TEST(GeneratedEnumTest,GetEnumDescriptor)1036 TEST(GeneratedEnumTest, GetEnumDescriptor) {
1037   EXPECT_EQ(unittest::TestAllTypes::NestedEnum_descriptor(),
1038             GetEnumDescriptor<unittest::TestAllTypes::NestedEnum>());
1039   EXPECT_EQ(unittest::ForeignEnum_descriptor(),
1040             GetEnumDescriptor<unittest::ForeignEnum>());
1041   EXPECT_EQ(unittest::TestEnumWithDupValue_descriptor(),
1042             GetEnumDescriptor<unittest::TestEnumWithDupValue>());
1043   EXPECT_EQ(unittest::TestSparseEnum_descriptor(),
1044             GetEnumDescriptor<unittest::TestSparseEnum>());
1045 }
1046 
1047 enum NonProtoEnum {
1048   kFoo = 1,
1049 };
1050 
TEST(GeneratedEnumTest,IsProtoEnumTypeTrait)1051 TEST(GeneratedEnumTest, IsProtoEnumTypeTrait) {
1052   EXPECT_TRUE(is_proto_enum<unittest::TestAllTypes::NestedEnum>::value);
1053   EXPECT_TRUE(is_proto_enum<unittest::ForeignEnum>::value);
1054   EXPECT_TRUE(is_proto_enum<unittest::TestEnumWithDupValue>::value);
1055   EXPECT_TRUE(is_proto_enum<unittest::TestSparseEnum>::value);
1056 
1057   EXPECT_FALSE(is_proto_enum<int>::value);
1058   EXPECT_FALSE(is_proto_enum<NonProtoEnum>::value);
1059 }
1060 
1061 #endif  // PROTOBUF_TEST_NO_DESCRIPTORS
1062 
1063 // ===================================================================
1064 
1065 #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
1066 
1067 // Support code for testing services.
1068 class GeneratedServiceTest : public testing::Test {
1069  protected:
1070   class MockTestService : public unittest::TestService {
1071    public:
MockTestService()1072     MockTestService()
1073       : called_(false),
1074         method_(""),
1075         controller_(NULL),
1076         request_(NULL),
1077         response_(NULL),
1078         done_(NULL) {}
1079 
~MockTestService()1080     ~MockTestService() {}
1081 
Reset()1082     void Reset() { called_ = false; }
1083 
1084     // implements TestService ----------------------------------------
1085 
Foo(RpcController * controller,const unittest::FooRequest * request,unittest::FooResponse * response,Closure * done)1086     void Foo(RpcController* controller,
1087              const unittest::FooRequest* request,
1088              unittest::FooResponse* response,
1089              Closure* done) {
1090       ASSERT_FALSE(called_);
1091       called_ = true;
1092       method_ = "Foo";
1093       controller_ = controller;
1094       request_ = request;
1095       response_ = response;
1096       done_ = done;
1097     }
1098 
Bar(RpcController * controller,const unittest::BarRequest * request,unittest::BarResponse * response,Closure * done)1099     void Bar(RpcController* controller,
1100              const unittest::BarRequest* request,
1101              unittest::BarResponse* response,
1102              Closure* done) {
1103       ASSERT_FALSE(called_);
1104       called_ = true;
1105       method_ = "Bar";
1106       controller_ = controller;
1107       request_ = request;
1108       response_ = response;
1109       done_ = done;
1110     }
1111 
1112     // ---------------------------------------------------------------
1113 
1114     bool called_;
1115     string method_;
1116     RpcController* controller_;
1117     const Message* request_;
1118     Message* response_;
1119     Closure* done_;
1120   };
1121 
1122   class MockRpcChannel : public RpcChannel {
1123    public:
MockRpcChannel()1124     MockRpcChannel()
1125       : called_(false),
1126         method_(NULL),
1127         controller_(NULL),
1128         request_(NULL),
1129         response_(NULL),
1130         done_(NULL),
1131         destroyed_(NULL) {}
1132 
~MockRpcChannel()1133     ~MockRpcChannel() {
1134       if (destroyed_ != NULL) *destroyed_ = true;
1135     }
1136 
Reset()1137     void Reset() { called_ = false; }
1138 
1139     // implements TestService ----------------------------------------
1140 
CallMethod(const MethodDescriptor * method,RpcController * controller,const Message * request,Message * response,Closure * done)1141     void CallMethod(const MethodDescriptor* method,
1142                     RpcController* controller,
1143                     const Message* request,
1144                     Message* response,
1145                     Closure* done) {
1146       ASSERT_FALSE(called_);
1147       called_ = true;
1148       method_ = method;
1149       controller_ = controller;
1150       request_ = request;
1151       response_ = response;
1152       done_ = done;
1153     }
1154 
1155     // ---------------------------------------------------------------
1156 
1157     bool called_;
1158     const MethodDescriptor* method_;
1159     RpcController* controller_;
1160     const Message* request_;
1161     Message* response_;
1162     Closure* done_;
1163     bool* destroyed_;
1164   };
1165 
1166   class MockController : public RpcController {
1167    public:
Reset()1168     void Reset() {
1169       ADD_FAILURE() << "Reset() not expected during this test.";
1170     }
Failed() const1171     bool Failed() const {
1172       ADD_FAILURE() << "Failed() not expected during this test.";
1173       return false;
1174     }
ErrorText() const1175     string ErrorText() const {
1176       ADD_FAILURE() << "ErrorText() not expected during this test.";
1177       return "";
1178     }
StartCancel()1179     void StartCancel() {
1180       ADD_FAILURE() << "StartCancel() not expected during this test.";
1181     }
SetFailed(const string & reason)1182     void SetFailed(const string& reason) {
1183       ADD_FAILURE() << "SetFailed() not expected during this test.";
1184     }
IsCanceled() const1185     bool IsCanceled() const {
1186       ADD_FAILURE() << "IsCanceled() not expected during this test.";
1187       return false;
1188     }
NotifyOnCancel(Closure * callback)1189     void NotifyOnCancel(Closure* callback) {
1190       ADD_FAILURE() << "NotifyOnCancel() not expected during this test.";
1191     }
1192   };
1193 
GeneratedServiceTest()1194   GeneratedServiceTest()
1195     : descriptor_(unittest::TestService::descriptor()),
1196       foo_(descriptor_->FindMethodByName("Foo")),
1197       bar_(descriptor_->FindMethodByName("Bar")),
1198       stub_(&mock_channel_),
1199       done_(NewPermanentCallback(&DoNothing)) {}
1200 
SetUp()1201   virtual void SetUp() {
1202     ASSERT_TRUE(foo_ != NULL);
1203     ASSERT_TRUE(bar_ != NULL);
1204   }
1205 
1206   const ServiceDescriptor* descriptor_;
1207   const MethodDescriptor* foo_;
1208   const MethodDescriptor* bar_;
1209 
1210   MockTestService mock_service_;
1211   MockController mock_controller_;
1212 
1213   MockRpcChannel mock_channel_;
1214   unittest::TestService::Stub stub_;
1215 
1216   // Just so we don't have to re-define these with every test.
1217   unittest::FooRequest foo_request_;
1218   unittest::FooResponse foo_response_;
1219   unittest::BarRequest bar_request_;
1220   unittest::BarResponse bar_response_;
1221   scoped_ptr<Closure> done_;
1222 };
1223 
TEST_F(GeneratedServiceTest,GetDescriptor)1224 TEST_F(GeneratedServiceTest, GetDescriptor) {
1225   // Test that GetDescriptor() works.
1226 
1227   EXPECT_EQ(descriptor_, mock_service_.GetDescriptor());
1228 }
1229 
TEST_F(GeneratedServiceTest,GetChannel)1230 TEST_F(GeneratedServiceTest, GetChannel) {
1231   EXPECT_EQ(&mock_channel_, stub_.channel());
1232 }
1233 
TEST_F(GeneratedServiceTest,OwnsChannel)1234 TEST_F(GeneratedServiceTest, OwnsChannel) {
1235   MockRpcChannel* channel = new MockRpcChannel;
1236   bool destroyed = false;
1237   channel->destroyed_ = &destroyed;
1238 
1239   {
1240     unittest::TestService::Stub owning_stub(channel,
1241                                             Service::STUB_OWNS_CHANNEL);
1242     EXPECT_FALSE(destroyed);
1243   }
1244 
1245   EXPECT_TRUE(destroyed);
1246 }
1247 
TEST_F(GeneratedServiceTest,CallMethod)1248 TEST_F(GeneratedServiceTest, CallMethod) {
1249   // Test that CallMethod() works.
1250 
1251   // Call Foo() via CallMethod().
1252   mock_service_.CallMethod(foo_, &mock_controller_,
1253                            &foo_request_, &foo_response_, done_.get());
1254 
1255   ASSERT_TRUE(mock_service_.called_);
1256 
1257   EXPECT_EQ("Foo"            , mock_service_.method_    );
1258   EXPECT_EQ(&mock_controller_, mock_service_.controller_);
1259   EXPECT_EQ(&foo_request_    , mock_service_.request_   );
1260   EXPECT_EQ(&foo_response_   , mock_service_.response_  );
1261   EXPECT_EQ(done_.get()      , mock_service_.done_      );
1262 
1263   // Try again, but call Bar() instead.
1264   mock_service_.Reset();
1265   mock_service_.CallMethod(bar_, &mock_controller_,
1266                            &bar_request_, &bar_response_, done_.get());
1267 
1268   ASSERT_TRUE(mock_service_.called_);
1269   EXPECT_EQ("Bar", mock_service_.method_);
1270 }
1271 
TEST_F(GeneratedServiceTest,CallMethodTypeFailure)1272 TEST_F(GeneratedServiceTest, CallMethodTypeFailure) {
1273   // Verify death if we call Foo() with Bar's message types.
1274 
1275 #ifdef PROTOBUF_HAS_DEATH_TEST  // death tests do not work on Windows yet
1276   EXPECT_DEBUG_DEATH(
1277     mock_service_.CallMethod(foo_, &mock_controller_,
1278                              &foo_request_, &bar_response_, done_.get()),
1279     "dynamic_cast");
1280 
1281   mock_service_.Reset();
1282   EXPECT_DEBUG_DEATH(
1283     mock_service_.CallMethod(foo_, &mock_controller_,
1284                              &bar_request_, &foo_response_, done_.get()),
1285     "dynamic_cast");
1286 #endif  // PROTOBUF_HAS_DEATH_TEST
1287 }
1288 
TEST_F(GeneratedServiceTest,GetPrototypes)1289 TEST_F(GeneratedServiceTest, GetPrototypes) {
1290   // Test Get{Request,Response}Prototype() methods.
1291 
1292   EXPECT_EQ(&unittest::FooRequest::default_instance(),
1293             &mock_service_.GetRequestPrototype(foo_));
1294   EXPECT_EQ(&unittest::BarRequest::default_instance(),
1295             &mock_service_.GetRequestPrototype(bar_));
1296 
1297   EXPECT_EQ(&unittest::FooResponse::default_instance(),
1298             &mock_service_.GetResponsePrototype(foo_));
1299   EXPECT_EQ(&unittest::BarResponse::default_instance(),
1300             &mock_service_.GetResponsePrototype(bar_));
1301 }
1302 
TEST_F(GeneratedServiceTest,Stub)1303 TEST_F(GeneratedServiceTest, Stub) {
1304   // Test that the stub class works.
1305 
1306   // Call Foo() via the stub.
1307   stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get());
1308 
1309   ASSERT_TRUE(mock_channel_.called_);
1310 
1311   EXPECT_EQ(foo_             , mock_channel_.method_    );
1312   EXPECT_EQ(&mock_controller_, mock_channel_.controller_);
1313   EXPECT_EQ(&foo_request_    , mock_channel_.request_   );
1314   EXPECT_EQ(&foo_response_   , mock_channel_.response_  );
1315   EXPECT_EQ(done_.get()      , mock_channel_.done_      );
1316 
1317   // Call Bar() via the stub.
1318   mock_channel_.Reset();
1319   stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get());
1320 
1321   ASSERT_TRUE(mock_channel_.called_);
1322   EXPECT_EQ(bar_, mock_channel_.method_);
1323 }
1324 
TEST_F(GeneratedServiceTest,NotImplemented)1325 TEST_F(GeneratedServiceTest, NotImplemented) {
1326   // Test that failing to implement a method of a service causes it to fail
1327   // with a "not implemented" error message.
1328 
1329   // A service which doesn't implement any methods.
1330   class UnimplementedService : public unittest::TestService {
1331    public:
1332     UnimplementedService() {}
1333   };
1334 
1335   UnimplementedService unimplemented_service;
1336 
1337   // And a controller which expects to get a "not implemented" error.
1338   class ExpectUnimplementedController : public MockController {
1339    public:
1340     ExpectUnimplementedController() : called_(false) {}
1341 
1342     void SetFailed(const string& reason) {
1343       EXPECT_FALSE(called_);
1344       called_ = true;
1345       EXPECT_EQ("Method Foo() not implemented.", reason);
1346     }
1347 
1348     bool called_;
1349   };
1350 
1351   ExpectUnimplementedController controller;
1352 
1353   // Call Foo.
1354   unimplemented_service.Foo(&controller, &foo_request_, &foo_response_,
1355                             done_.get());
1356 
1357   EXPECT_TRUE(controller.called_);
1358 }
1359 
1360 // ===================================================================
1361 
1362 class OneofTest : public testing::Test {
1363  protected:
SetUp()1364   virtual void SetUp() {
1365   }
1366 
ExpectEnumCasesWork(const unittest::TestOneof2 & message)1367   void ExpectEnumCasesWork(const unittest::TestOneof2 &message) {
1368     switch (message.foo_case()) {
1369       case unittest::TestOneof2::kFooInt:
1370         EXPECT_TRUE(message.has_foo_int());
1371         break;
1372       case unittest::TestOneof2::kFooString:
1373         EXPECT_TRUE(message.has_foo_string());
1374         break;
1375       case unittest::TestOneof2::kFooBytes:
1376         EXPECT_TRUE(message.has_foo_bytes());
1377         break;
1378       case unittest::TestOneof2::kFooEnum:
1379         EXPECT_TRUE(message.has_foo_enum());
1380         break;
1381       case unittest::TestOneof2::kFooMessage:
1382         EXPECT_TRUE(message.has_foo_message());
1383         break;
1384       case unittest::TestOneof2::kFoogroup:
1385         EXPECT_TRUE(message.has_foogroup());
1386         break;
1387       case unittest::TestOneof2::FOO_NOT_SET:
1388         break;
1389     }
1390   }
1391 };
1392 
TEST_F(OneofTest,SettingOneFieldClearsOthers)1393 TEST_F(OneofTest, SettingOneFieldClearsOthers) {
1394   unittest::TestOneof2 message;
1395 
1396   message.set_foo_int(123);
1397   EXPECT_TRUE(message.has_foo_int());
1398   TestUtil::ExpectAtMostOneFieldSetInOneof(message);
1399 
1400   message.set_foo_string("foo");
1401   EXPECT_TRUE(message.has_foo_string());
1402   TestUtil::ExpectAtMostOneFieldSetInOneof(message);
1403 
1404 
1405   message.set_foo_bytes("qux");
1406   EXPECT_TRUE(message.has_foo_bytes());
1407   TestUtil::ExpectAtMostOneFieldSetInOneof(message);
1408 
1409   message.set_foo_enum(unittest::TestOneof2::FOO);
1410   EXPECT_TRUE(message.has_foo_enum());
1411   TestUtil::ExpectAtMostOneFieldSetInOneof(message);
1412 
1413   message.mutable_foo_message()->set_qux_int(234);
1414   EXPECT_TRUE(message.has_foo_message());
1415   TestUtil::ExpectAtMostOneFieldSetInOneof(message);
1416 
1417   message.mutable_foogroup()->set_a(345);
1418   EXPECT_TRUE(message.has_foogroup());
1419   TestUtil::ExpectAtMostOneFieldSetInOneof(message);
1420 
1421 
1422   // we repeat this because we didn't test if this properly clears other fields
1423   // at the beginning.
1424   message.set_foo_int(123);
1425   EXPECT_TRUE(message.has_foo_int());
1426   TestUtil::ExpectAtMostOneFieldSetInOneof(message);
1427 }
1428 
TEST_F(OneofTest,EnumCases)1429 TEST_F(OneofTest, EnumCases) {
1430   unittest::TestOneof2 message;
1431 
1432   message.set_foo_int(123);
1433   ExpectEnumCasesWork(message);
1434   message.set_foo_string("foo");
1435   ExpectEnumCasesWork(message);
1436   message.set_foo_bytes("qux");
1437   ExpectEnumCasesWork(message);
1438   message.set_foo_enum(unittest::TestOneof2::FOO);
1439   ExpectEnumCasesWork(message);
1440   message.mutable_foo_message()->set_qux_int(234);
1441   ExpectEnumCasesWork(message);
1442   message.mutable_foogroup()->set_a(345);
1443   ExpectEnumCasesWork(message);
1444 }
1445 
TEST_F(OneofTest,PrimitiveType)1446 TEST_F(OneofTest, PrimitiveType) {
1447   unittest::TestOneof2 message;
1448   // Unset field returns default value
1449   EXPECT_EQ(message.foo_int(), 0);
1450 
1451   message.set_foo_int(123);
1452   EXPECT_TRUE(message.has_foo_int());
1453   EXPECT_EQ(message.foo_int(), 123);
1454   message.clear_foo_int();
1455   EXPECT_FALSE(message.has_foo_int());
1456 }
1457 
TEST_F(OneofTest,EnumType)1458 TEST_F(OneofTest, EnumType) {
1459   unittest::TestOneof2 message;
1460   // Unset field returns default value
1461   EXPECT_EQ(message.foo_enum(), 1);
1462 
1463   message.set_foo_enum(unittest::TestOneof2::FOO);
1464   EXPECT_TRUE(message.has_foo_enum());
1465   EXPECT_EQ(message.foo_enum(), unittest::TestOneof2::FOO);
1466   message.clear_foo_enum();
1467   EXPECT_FALSE(message.has_foo_enum());
1468 }
1469 
TEST_F(OneofTest,SetString)1470 TEST_F(OneofTest, SetString) {
1471   // Check that setting a string field in various ways works
1472   unittest::TestOneof2 message;
1473 
1474   // Unset field returns default value
1475   EXPECT_EQ(message.foo_string(), "");
1476 
1477   message.set_foo_string("foo");
1478   EXPECT_TRUE(message.has_foo_string());
1479   EXPECT_EQ(message.foo_string(), "foo");
1480   message.clear_foo_string();
1481   EXPECT_FALSE(message.has_foo_string());
1482 
1483   message.set_foo_string(string("bar"));
1484   EXPECT_TRUE(message.has_foo_string());
1485   EXPECT_EQ(message.foo_string(), "bar");
1486   message.clear_foo_string();
1487   EXPECT_FALSE(message.has_foo_string());
1488 
1489 
1490   message.set_foo_string("qux", 3);
1491   EXPECT_TRUE(message.has_foo_string());
1492   EXPECT_EQ(message.foo_string(), "qux");
1493   message.clear_foo_string();
1494   EXPECT_FALSE(message.has_foo_string());
1495 
1496   message.mutable_foo_string()->assign("quux");
1497   EXPECT_TRUE(message.has_foo_string());
1498   EXPECT_EQ(message.foo_string(), "quux");
1499   message.clear_foo_string();
1500   EXPECT_FALSE(message.has_foo_string());
1501 
1502   message.set_foo_string("corge");
1503   EXPECT_TRUE(message.has_foo_string());
1504   EXPECT_EQ(message.foo_string(), "corge");
1505   message.clear_foo_string();
1506   EXPECT_FALSE(message.has_foo_string());
1507 }
1508 
TEST_F(OneofTest,ReleaseString)1509 TEST_F(OneofTest, ReleaseString) {
1510   // Check that release_foo() starts out NULL, and gives us a value
1511   // that we can delete after it's been set.
1512   unittest::TestOneof2 message;
1513 
1514   EXPECT_EQ(NULL, message.release_foo_string());
1515   EXPECT_FALSE(message.has_foo_string());
1516 
1517   message.set_foo_string("blah");
1518   EXPECT_TRUE(message.has_foo_string());
1519   scoped_ptr<string> str(message.release_foo_string());
1520   EXPECT_FALSE(message.has_foo_string());
1521   ASSERT_TRUE(str != NULL);
1522   EXPECT_EQ("blah", *str);
1523 
1524   EXPECT_EQ(NULL, message.release_foo_string());
1525   EXPECT_FALSE(message.has_foo_string());
1526 }
1527 
TEST_F(OneofTest,SetAllocatedString)1528 TEST_F(OneofTest, SetAllocatedString) {
1529   // Check that set_allocated_foo() works for strings.
1530   unittest::TestOneof2 message;
1531 
1532   EXPECT_FALSE(message.has_foo_string());
1533   const string kHello("hello");
1534   message.set_foo_string(kHello);
1535   EXPECT_TRUE(message.has_foo_string());
1536 
1537   message.set_allocated_foo_string(NULL);
1538   EXPECT_FALSE(message.has_foo_string());
1539   EXPECT_EQ("", message.foo_string());
1540 
1541   message.set_allocated_foo_string(new string(kHello));
1542   EXPECT_TRUE(message.has_foo_string());
1543   EXPECT_EQ(kHello, message.foo_string());
1544 }
1545 
1546 
TEST_F(OneofTest,SetMessage)1547 TEST_F(OneofTest, SetMessage) {
1548   // Check that setting a message field works
1549   unittest::TestOneof2 message;
1550 
1551   // Unset field returns default instance
1552   EXPECT_EQ(&message.foo_message(),
1553             &unittest::TestOneof2_NestedMessage::default_instance());
1554   EXPECT_EQ(message.foo_message().qux_int(), 0);
1555 
1556   message.mutable_foo_message()->set_qux_int(234);
1557   EXPECT_TRUE(message.has_foo_message());
1558   EXPECT_EQ(message.foo_message().qux_int(), 234);
1559   message.clear_foo_message();
1560   EXPECT_FALSE(message.has_foo_message());
1561 }
1562 
TEST_F(OneofTest,ReleaseMessage)1563 TEST_F(OneofTest, ReleaseMessage) {
1564   // Check that release_foo() starts out NULL, and gives us a value
1565   // that we can delete after it's been set.
1566   unittest::TestOneof2 message;
1567 
1568   EXPECT_EQ(NULL, message.release_foo_message());
1569   EXPECT_FALSE(message.has_foo_message());
1570 
1571   message.mutable_foo_message()->set_qux_int(1);
1572   EXPECT_TRUE(message.has_foo_message());
1573   scoped_ptr<unittest::TestOneof2_NestedMessage> mes(
1574       message.release_foo_message());
1575   EXPECT_FALSE(message.has_foo_message());
1576   ASSERT_TRUE(mes != NULL);
1577   EXPECT_EQ(1, mes->qux_int());
1578 
1579   EXPECT_EQ(NULL, message.release_foo_message());
1580   EXPECT_FALSE(message.has_foo_message());
1581 }
1582 
TEST_F(OneofTest,SetAllocatedMessage)1583 TEST_F(OneofTest, SetAllocatedMessage) {
1584   // Check that set_allocated_foo() works for messages.
1585   unittest::TestOneof2 message;
1586 
1587   EXPECT_FALSE(message.has_foo_message());
1588 
1589   message.mutable_foo_message()->set_qux_int(1);
1590   EXPECT_TRUE(message.has_foo_message());
1591 
1592   message.set_allocated_foo_message(NULL);
1593   EXPECT_FALSE(message.has_foo_message());
1594   EXPECT_EQ(&message.foo_message(),
1595             &unittest::TestOneof2_NestedMessage::default_instance());
1596 
1597   message.mutable_foo_message()->set_qux_int(1);
1598   unittest::TestOneof2_NestedMessage* mes = message.release_foo_message();
1599   ASSERT_TRUE(mes != NULL);
1600   EXPECT_FALSE(message.has_foo_message());
1601 
1602   message.set_allocated_foo_message(mes);
1603   EXPECT_TRUE(message.has_foo_message());
1604   EXPECT_EQ(1, message.foo_message().qux_int());
1605 }
1606 
1607 
TEST_F(OneofTest,Clear)1608 TEST_F(OneofTest, Clear) {
1609   unittest::TestOneof2 message;
1610 
1611   message.set_foo_int(1);
1612   EXPECT_TRUE(message.has_foo_int());
1613   message.clear_foo_int();
1614   EXPECT_FALSE(message.has_foo_int());
1615 }
1616 
TEST_F(OneofTest,Defaults)1617 TEST_F(OneofTest, Defaults) {
1618   unittest::TestOneof2 message;
1619 
1620   EXPECT_FALSE(message.has_foo_int());
1621   EXPECT_EQ(message.foo_int(), 0);
1622 
1623   EXPECT_FALSE(message.has_foo_string());
1624   EXPECT_EQ(message.foo_string(), "");
1625 
1626 
1627   EXPECT_FALSE(message.has_foo_bytes());
1628   EXPECT_EQ(message.foo_bytes(), "");
1629 
1630   EXPECT_FALSE(message.has_foo_enum());
1631   EXPECT_EQ(message.foo_enum(), 1);
1632 
1633   EXPECT_FALSE(message.has_foo_message());
1634   EXPECT_EQ(message.foo_message().qux_int(), 0);
1635 
1636   EXPECT_FALSE(message.has_foogroup());
1637   EXPECT_EQ(message.foogroup().a(), 0);
1638 
1639 
1640   EXPECT_FALSE(message.has_bar_int());
1641   EXPECT_EQ(message.bar_int(), 5);
1642 
1643   EXPECT_FALSE(message.has_bar_string());
1644   EXPECT_EQ(message.bar_string(), "STRING");
1645 
1646 
1647   EXPECT_FALSE(message.has_bar_bytes());
1648   EXPECT_EQ(message.bar_bytes(), "BYTES");
1649 
1650   EXPECT_FALSE(message.has_bar_enum());
1651   EXPECT_EQ(message.bar_enum(), 2);
1652 }
1653 
TEST_F(OneofTest,SwapWithEmpty)1654 TEST_F(OneofTest, SwapWithEmpty) {
1655   unittest::TestOneof2 message1, message2;
1656   message1.set_foo_string("FOO");
1657   EXPECT_TRUE(message1.has_foo_string());
1658   message1.Swap(&message2);
1659   EXPECT_FALSE(message1.has_foo_string());
1660   EXPECT_TRUE(message2.has_foo_string());
1661   EXPECT_EQ(message2.foo_string(), "FOO");
1662 }
1663 
TEST_F(OneofTest,SwapWithSelf)1664 TEST_F(OneofTest, SwapWithSelf) {
1665   unittest::TestOneof2 message;
1666   message.set_foo_string("FOO");
1667   EXPECT_TRUE(message.has_foo_string());
1668   message.Swap(&message);
1669   EXPECT_TRUE(message.has_foo_string());
1670   EXPECT_EQ(message.foo_string(), "FOO");
1671 }
1672 
TEST_F(OneofTest,SwapBothHasFields)1673 TEST_F(OneofTest, SwapBothHasFields) {
1674   unittest::TestOneof2 message1, message2;
1675 
1676   message1.set_foo_string("FOO");
1677   EXPECT_TRUE(message1.has_foo_string());
1678   message2.mutable_foo_message()->set_qux_int(1);
1679   EXPECT_TRUE(message2.has_foo_message());
1680 
1681   message1.Swap(&message2);
1682   EXPECT_FALSE(message1.has_foo_string());
1683   EXPECT_FALSE(message2.has_foo_message());
1684   EXPECT_TRUE(message1.has_foo_message());
1685   EXPECT_EQ(message1.foo_message().qux_int(), 1);
1686   EXPECT_TRUE(message2.has_foo_string());
1687   EXPECT_EQ(message2.foo_string(), "FOO");
1688 }
1689 
TEST_F(OneofTest,CopyContructor)1690 TEST_F(OneofTest, CopyContructor) {
1691   unittest::TestOneof2 message1;
1692   message1.set_foo_bytes("FOO");
1693 
1694   unittest::TestOneof2 message2(message1);
1695   EXPECT_TRUE(message2.has_foo_bytes());
1696   EXPECT_EQ(message2.foo_bytes(), "FOO");
1697 }
1698 
TEST_F(OneofTest,CopyFrom)1699 TEST_F(OneofTest, CopyFrom) {
1700   unittest::TestOneof2 message1, message2;
1701   message1.set_foo_enum(unittest::TestOneof2::BAR);
1702   EXPECT_TRUE(message1.has_foo_enum());
1703 
1704   message2.CopyFrom(message1);
1705   EXPECT_TRUE(message2.has_foo_enum());
1706   EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::BAR);
1707 
1708   // Copying from self should be a no-op.
1709   message2.CopyFrom(message2);
1710   EXPECT_TRUE(message2.has_foo_enum());
1711   EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::BAR);
1712 }
1713 
TEST_F(OneofTest,CopyAssignmentOperator)1714 TEST_F(OneofTest, CopyAssignmentOperator) {
1715   unittest::TestOneof2 message1;
1716   message1.mutable_foo_message()->set_qux_int(123);
1717   EXPECT_TRUE(message1.has_foo_message());
1718 
1719   unittest::TestOneof2 message2;
1720   message2 = message1;
1721   EXPECT_EQ(message2.foo_message().qux_int(), 123);
1722 
1723   // Make sure that self-assignment does something sane.
1724   message2 = message2;
1725   EXPECT_EQ(message2.foo_message().qux_int(), 123);
1726 }
1727 
TEST_F(OneofTest,UpcastCopyFrom)1728 TEST_F(OneofTest, UpcastCopyFrom) {
1729   // Test the CopyFrom method that takes in the generic const Message&
1730   // parameter.
1731   unittest::TestOneof2 message1, message2;
1732   message1.mutable_foogroup()->set_a(123);
1733   EXPECT_TRUE(message1.has_foogroup());
1734 
1735   const Message* source = implicit_cast<const Message*>(&message1);
1736   message2.CopyFrom(*source);
1737 
1738   EXPECT_TRUE(message2.has_foogroup());
1739   EXPECT_EQ(message2.foogroup().a(), 123);
1740 }
1741 
1742 // Test the generated SerializeWithCachedSizesToArray(),
1743 // This indirectly tests MergePartialFromCodedStream()
1744 // We have to test each field type separately because we cannot set them at the
1745 // same time
TEST_F(OneofTest,SerializationToArray)1746 TEST_F(OneofTest, SerializationToArray) {
1747   // Primitive type
1748   {
1749     unittest::TestOneof2 message1, message2;
1750     string data;
1751     message1.set_foo_int(123);
1752     int size = message1.ByteSize();
1753     data.resize(size);
1754     uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
1755     uint8* end = message1.SerializeWithCachedSizesToArray(start);
1756     EXPECT_EQ(size, end - start);
1757     EXPECT_TRUE(message2.ParseFromString(data));
1758     EXPECT_EQ(message2.foo_int(), 123);
1759   }
1760 
1761   // String
1762   {
1763     unittest::TestOneof2 message1, message2;
1764     string data;
1765     message1.set_foo_string("foo");
1766     int size = message1.ByteSize();
1767     data.resize(size);
1768     uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
1769     uint8* end = message1.SerializeWithCachedSizesToArray(start);
1770     EXPECT_EQ(size, end - start);
1771     EXPECT_TRUE(message2.ParseFromString(data));
1772     EXPECT_EQ(message2.foo_string(), "foo");
1773   }
1774 
1775 
1776   // Bytes
1777   {
1778     unittest::TestOneof2 message1, message2;
1779     string data;
1780     message1.set_foo_bytes("qux");
1781     int size = message1.ByteSize();
1782     data.resize(size);
1783     uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
1784     uint8* end = message1.SerializeWithCachedSizesToArray(start);
1785     EXPECT_EQ(size, end - start);
1786     EXPECT_TRUE(message2.ParseFromString(data));
1787     EXPECT_EQ(message2.foo_bytes(), "qux");
1788   }
1789 
1790   // Enum
1791   {
1792     unittest::TestOneof2 message1, message2;
1793     string data;
1794     message1.set_foo_enum(unittest::TestOneof2::FOO);
1795     int size = message1.ByteSize();
1796     data.resize(size);
1797     uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
1798     uint8* end = message1.SerializeWithCachedSizesToArray(start);
1799     EXPECT_EQ(size, end - start);
1800     EXPECT_TRUE(message2.ParseFromString(data));
1801     EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO);
1802   }
1803 
1804   // Message
1805   {
1806     unittest::TestOneof2 message1, message2;
1807     string data;
1808     message1.mutable_foo_message()->set_qux_int(234);
1809     int size = message1.ByteSize();
1810     data.resize(size);
1811     uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
1812     uint8* end = message1.SerializeWithCachedSizesToArray(start);
1813     EXPECT_EQ(size, end - start);
1814     EXPECT_TRUE(message2.ParseFromString(data));
1815     EXPECT_EQ(message2.foo_message().qux_int(), 234);
1816   }
1817 
1818   // Group
1819   {
1820     unittest::TestOneof2 message1, message2;
1821     string data;
1822     message1.mutable_foogroup()->set_a(345);
1823     int size = message1.ByteSize();
1824     data.resize(size);
1825     uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
1826     uint8* end = message1.SerializeWithCachedSizesToArray(start);
1827     EXPECT_EQ(size, end - start);
1828     EXPECT_TRUE(message2.ParseFromString(data));
1829     EXPECT_EQ(message2.foogroup().a(), 345);
1830   }
1831 
1832 }
1833 
1834 // Test the generated SerializeWithCachedSizes() by forcing the buffer to write
1835 // one byte at a time.
1836 // This indirectly tests MergePartialFromCodedStream()
1837 // We have to test each field type separately because we cannot set them at the
1838 // same time
TEST_F(OneofTest,SerializationToStream)1839 TEST_F(OneofTest, SerializationToStream) {
1840   // Primitive type
1841   {
1842     unittest::TestOneof2 message1, message2;
1843     string data;
1844     message1.set_foo_int(123);
1845     int size = message1.ByteSize();
1846     data.resize(size);
1847 
1848     {
1849       // Allow the output stream to buffer only one byte at a time.
1850       io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
1851       io::CodedOutputStream output_stream(&array_stream);
1852       message1.SerializeWithCachedSizes(&output_stream);
1853       EXPECT_FALSE(output_stream.HadError());
1854       EXPECT_EQ(size, output_stream.ByteCount());
1855     }
1856 
1857     EXPECT_TRUE(message2.ParseFromString(data));
1858     EXPECT_EQ(message2.foo_int(), 123);
1859   }
1860 
1861   // String
1862   {
1863     unittest::TestOneof2 message1, message2;
1864     string data;
1865     message1.set_foo_string("foo");
1866     int size = message1.ByteSize();
1867     data.resize(size);
1868 
1869     {
1870       // Allow the output stream to buffer only one byte at a time.
1871       io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
1872       io::CodedOutputStream output_stream(&array_stream);
1873       message1.SerializeWithCachedSizes(&output_stream);
1874       EXPECT_FALSE(output_stream.HadError());
1875       EXPECT_EQ(size, output_stream.ByteCount());
1876     }
1877 
1878     EXPECT_TRUE(message2.ParseFromString(data));
1879     EXPECT_EQ(message2.foo_string(), "foo");
1880   }
1881 
1882 
1883   // Bytes
1884   {
1885     unittest::TestOneof2 message1, message2;
1886     string data;
1887     message1.set_foo_bytes("qux");
1888     int size = message1.ByteSize();
1889     data.resize(size);
1890 
1891     {
1892       // Allow the output stream to buffer only one byte at a time.
1893       io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
1894       io::CodedOutputStream output_stream(&array_stream);
1895       message1.SerializeWithCachedSizes(&output_stream);
1896       EXPECT_FALSE(output_stream.HadError());
1897       EXPECT_EQ(size, output_stream.ByteCount());
1898     }
1899 
1900     EXPECT_TRUE(message2.ParseFromString(data));
1901     EXPECT_EQ(message2.foo_bytes(), "qux");
1902   }
1903 
1904   // Enum
1905   {
1906     unittest::TestOneof2 message1, message2;
1907     string data;
1908     message1.set_foo_enum(unittest::TestOneof2::FOO);
1909     int size = message1.ByteSize();
1910     data.resize(size);
1911 
1912     {
1913       // Allow the output stream to buffer only one byte at a time.
1914       io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
1915       io::CodedOutputStream output_stream(&array_stream);
1916       message1.SerializeWithCachedSizes(&output_stream);
1917       EXPECT_FALSE(output_stream.HadError());
1918       EXPECT_EQ(size, output_stream.ByteCount());
1919     }
1920 
1921     EXPECT_TRUE(message2.ParseFromString(data));
1922     EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO);
1923   }
1924 
1925   // Message
1926   {
1927     unittest::TestOneof2 message1, message2;
1928     string data;
1929     message1.mutable_foo_message()->set_qux_int(234);
1930     int size = message1.ByteSize();
1931     data.resize(size);
1932 
1933     {
1934       // Allow the output stream to buffer only one byte at a time.
1935       io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
1936       io::CodedOutputStream output_stream(&array_stream);
1937       message1.SerializeWithCachedSizes(&output_stream);
1938       EXPECT_FALSE(output_stream.HadError());
1939       EXPECT_EQ(size, output_stream.ByteCount());
1940     }
1941 
1942     EXPECT_TRUE(message2.ParseFromString(data));
1943     EXPECT_EQ(message2.foo_message().qux_int(), 234);
1944   }
1945 
1946   // Group
1947   {
1948     unittest::TestOneof2 message1, message2;
1949     string data;
1950     message1.mutable_foogroup()->set_a(345);
1951     int size = message1.ByteSize();
1952     data.resize(size);
1953 
1954     {
1955       // Allow the output stream to buffer only one byte at a time.
1956       io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
1957       io::CodedOutputStream output_stream(&array_stream);
1958       message1.SerializeWithCachedSizes(&output_stream);
1959       EXPECT_FALSE(output_stream.HadError());
1960       EXPECT_EQ(size, output_stream.ByteCount());
1961     }
1962 
1963     EXPECT_TRUE(message2.ParseFromString(data));
1964     EXPECT_EQ(message2.foogroup().a(), 345);
1965   }
1966 
1967 }
1968 
TEST_F(OneofTest,MergeFrom)1969 TEST_F(OneofTest, MergeFrom) {
1970   unittest::TestOneof2 message1, message2;
1971 
1972   message1.set_foo_int(123);
1973   message2.MergeFrom(message1);
1974   TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
1975   EXPECT_TRUE(message2.has_foo_int());
1976   EXPECT_EQ(message2.foo_int(), 123);
1977 
1978   message1.set_foo_string("foo");
1979   message2.MergeFrom(message1);
1980   TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
1981   EXPECT_TRUE(message2.has_foo_string());
1982   EXPECT_EQ(message2.foo_string(), "foo");
1983 
1984 
1985   message1.set_foo_bytes("qux");
1986   message2.MergeFrom(message1);
1987   TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
1988   EXPECT_TRUE(message2.has_foo_bytes());
1989   EXPECT_EQ(message2.foo_bytes(), "qux");
1990 
1991   message1.set_foo_enum(unittest::TestOneof2::FOO);
1992   message2.MergeFrom(message1);
1993   TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
1994   EXPECT_TRUE(message2.has_foo_enum());
1995   EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO);
1996 
1997   message1.mutable_foo_message()->set_qux_int(234);
1998   message2.MergeFrom(message1);
1999   TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
2000   EXPECT_TRUE(message2.has_foo_message());
2001   EXPECT_EQ(message2.foo_message().qux_int(), 234);
2002 
2003   message1.mutable_foogroup()->set_a(345);
2004   message2.MergeFrom(message1);
2005   TestUtil::ExpectAtMostOneFieldSetInOneof(message2);
2006   EXPECT_TRUE(message2.has_foogroup());
2007   EXPECT_EQ(message2.foogroup().a(), 345);
2008 
2009 }
2010 
2011 }  // namespace cpp_unittest
2012 }  // namespace cpp
2013 }  // namespace compiler
2014 
2015 namespace no_generic_services_test {
2016   // Verify that no class called "TestService" was defined in
2017   // unittest_no_generic_services.pb.h by defining a different type by the same
2018   // name.  If such a service was generated, this will not compile.
2019   struct TestService {
2020     int i;
2021   };
2022 }
2023 
2024 namespace compiler {
2025 namespace cpp {
2026 namespace cpp_unittest {
2027 
TEST_F(GeneratedServiceTest,NoGenericServices)2028 TEST_F(GeneratedServiceTest, NoGenericServices) {
2029   // Verify that non-services in unittest_no_generic_services.proto were
2030   // generated.
2031   no_generic_services_test::TestMessage message;
2032   message.set_a(1);
2033   message.SetExtension(no_generic_services_test::test_extension, 123);
2034   no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
2035   EXPECT_EQ(e, 1);
2036 
2037   // Verify that a ServiceDescriptor is generated for the service even if the
2038   // class itself is not.
2039   const FileDescriptor* file =
2040       no_generic_services_test::TestMessage::descriptor()->file();
2041 
2042   ASSERT_EQ(1, file->service_count());
2043   EXPECT_EQ("TestService", file->service(0)->name());
2044   ASSERT_EQ(1, file->service(0)->method_count());
2045   EXPECT_EQ("Foo", file->service(0)->method(0)->name());
2046 }
2047 
2048 #endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
2049 
2050 // ===================================================================
2051 
2052 // This test must run last.  It verifies that descriptors were or were not
2053 // initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined.
2054 // When this is defined, we skip all tests which are expected to trigger
2055 // descriptor initialization.  This verifies that everything else still works
2056 // if descriptors are not initialized.
TEST(DescriptorInitializationTest,Initialized)2057 TEST(DescriptorInitializationTest, Initialized) {
2058 #ifdef PROTOBUF_TEST_NO_DESCRIPTORS
2059   bool should_have_descriptors = false;
2060 #else
2061   bool should_have_descriptors = true;
2062 #endif
2063 
2064   EXPECT_EQ(should_have_descriptors,
2065     DescriptorPool::generated_pool()->InternalIsFileLoaded(
2066       "google/protobuf/unittest.proto"));
2067 }
2068 
2069 }  // namespace cpp_unittest
2070 
2071 }  // namespace cpp
2072 }  // namespace compiler
2073 }  // namespace protobuf
2074 }  // namespace google
2075