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