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