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