1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// http://code.google.com/p/protobuf/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9//     * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11//     * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15//     * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// Author: kenton@google.com (Kenton Varda)
32//  Based on original Protocol Buffers design by
33//  Sanjay Ghemawat, Jeff Dean, and others.
34//
35// To test the code generator, we actually use it to generate code for
36// google/protobuf/unittest.proto, then test that.  This means that we
37// are actually testing the parser and other parts of the system at the same
38// time, and that problems in the generator may show up as compile-time errors
39// rather than unittest failures, which may be surprising.  However, testing
40// the output of the C++ generator directly would be very hard.  We can't very
41// well just check it against golden files since those files would have to be
42// updated for any small change; such a test would be very brittle and probably
43// not very helpful.  What we really want to test is that the code compiles
44// correctly and produces the interfaces we expect, which is why this test
45// is written this way.
46
47#include <google/protobuf/compiler/cpp/cpp_unittest.h>
48
49#include <vector>
50
51#include <google/protobuf/unittest.pb.h>
52#include <google/protobuf/unittest_optimize_for.pb.h>
53#include <google/protobuf/unittest_embed_optimize_for.pb.h>
54#include <google/protobuf/unittest_no_generic_services.pb.h>
55#include <google/protobuf/test_util.h>
56#include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h>
57#include <google/protobuf/compiler/importer.h>
58#include <google/protobuf/io/coded_stream.h>
59#include <google/protobuf/io/zero_copy_stream_impl.h>
60#include <google/protobuf/descriptor.h>
61#include <google/protobuf/descriptor.pb.h>
62#include <google/protobuf/dynamic_message.h>
63
64#include <google/protobuf/stubs/common.h>
65#include <google/protobuf/stubs/strutil.h>
66#include <google/protobuf/stubs/substitute.h>
67#include <google/protobuf/testing/googletest.h>
68#include <gtest/gtest.h>
69#include <google/protobuf/stubs/stl_util.h>
70
71namespace google {
72namespace protobuf {
73namespace compiler {
74namespace cpp {
75
76// Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
77namespace cpp_unittest {
78
79namespace protobuf_unittest = ::protobuf_unittest;
80
81
82class MockErrorCollector : public MultiFileErrorCollector {
83 public:
84  MockErrorCollector() {}
85  ~MockErrorCollector() {}
86
87  string text_;
88
89  // implements ErrorCollector ---------------------------------------
90  void AddError(const string& filename, int line, int column,
91                const string& message) {
92    strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
93                                 filename, line, column, message);
94  }
95};
96
97#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
98
99// Test that generated code has proper descriptors:
100// Parse a descriptor directly (using google::protobuf::compiler::Importer) and
101// compare it to the one that was produced by generated code.
102TEST(GeneratedDescriptorTest, IdenticalDescriptors) {
103  const FileDescriptor* generated_descriptor =
104    unittest::TestAllTypes::descriptor()->file();
105
106  // Set up the Importer.
107  MockErrorCollector error_collector;
108  DiskSourceTree source_tree;
109  source_tree.MapPath("", TestSourceDir());
110  Importer importer(&source_tree, &error_collector);
111
112  // Import (parse) unittest.proto.
113  const FileDescriptor* parsed_descriptor =
114    importer.Import("google/protobuf/unittest.proto");
115  EXPECT_EQ("", error_collector.text_);
116  ASSERT_TRUE(parsed_descriptor != NULL);
117
118  // Test that descriptors are generated correctly by converting them to
119  // FileDescriptorProtos and comparing.
120  FileDescriptorProto generated_decsriptor_proto, parsed_descriptor_proto;
121  generated_descriptor->CopyTo(&generated_decsriptor_proto);
122  parsed_descriptor->CopyTo(&parsed_descriptor_proto);
123
124  EXPECT_EQ(parsed_descriptor_proto.DebugString(),
125            generated_decsriptor_proto.DebugString());
126}
127
128#endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
129
130// ===================================================================
131
132TEST(GeneratedMessageTest, Defaults) {
133  // Check that all default values are set correctly in the initial message.
134  unittest::TestAllTypes message;
135
136  TestUtil::ExpectClear(message);
137
138  // Messages should return pointers to default instances until first use.
139  // (This is not checked by ExpectClear() since it is not actually true after
140  // the fields have been set and then cleared.)
141  EXPECT_EQ(&unittest::TestAllTypes::OptionalGroup::default_instance(),
142            &message.optionalgroup());
143  EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
144            &message.optional_nested_message());
145  EXPECT_EQ(&unittest::ForeignMessage::default_instance(),
146            &message.optional_foreign_message());
147  EXPECT_EQ(&unittest_import::ImportMessage::default_instance(),
148            &message.optional_import_message());
149}
150
151TEST(GeneratedMessageTest, FloatingPointDefaults) {
152  const unittest::TestExtremeDefaultValues& extreme_default =
153      unittest::TestExtremeDefaultValues::default_instance();
154
155  EXPECT_EQ(0.0f, extreme_default.zero_float());
156  EXPECT_EQ(1.0f, extreme_default.one_float());
157  EXPECT_EQ(1.5f, extreme_default.small_float());
158  EXPECT_EQ(-1.0f, extreme_default.negative_one_float());
159  EXPECT_EQ(-1.5f, extreme_default.negative_float());
160  EXPECT_EQ(2.0e8f, extreme_default.large_float());
161  EXPECT_EQ(-8e-28f, extreme_default.small_negative_float());
162  EXPECT_EQ(numeric_limits<double>::infinity(),
163            extreme_default.inf_double());
164  EXPECT_EQ(-numeric_limits<double>::infinity(),
165            extreme_default.neg_inf_double());
166  EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double());
167  EXPECT_EQ(numeric_limits<float>::infinity(),
168            extreme_default.inf_float());
169  EXPECT_EQ(-numeric_limits<float>::infinity(),
170            extreme_default.neg_inf_float());
171  EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float());
172}
173
174TEST(GeneratedMessageTest, Trigraph) {
175  const unittest::TestExtremeDefaultValues& extreme_default =
176      unittest::TestExtremeDefaultValues::default_instance();
177
178  EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph());
179}
180
181TEST(GeneratedMessageTest, ExtremeSmallIntegerDefault) {
182  const unittest::TestExtremeDefaultValues& extreme_default =
183      unittest::TestExtremeDefaultValues::default_instance();
184  EXPECT_EQ(-0x80000000, kint32min);
185  EXPECT_EQ(GOOGLE_LONGLONG(-0x8000000000000000), kint64min);
186  EXPECT_EQ(kint32min, extreme_default.really_small_int32());
187  EXPECT_EQ(kint64min, extreme_default.really_small_int64());
188}
189
190TEST(GeneratedMessageTest, Accessors) {
191  // Set every field to a unique value then go back and check all those
192  // values.
193  unittest::TestAllTypes message;
194
195  TestUtil::SetAllFields(&message);
196  TestUtil::ExpectAllFieldsSet(message);
197
198  TestUtil::ModifyRepeatedFields(&message);
199  TestUtil::ExpectRepeatedFieldsModified(message);
200}
201
202TEST(GeneratedMessageTest, MutableStringDefault) {
203  // mutable_foo() for a string should return a string initialized to its
204  // default value.
205  unittest::TestAllTypes message;
206
207  EXPECT_EQ("hello", *message.mutable_default_string());
208
209  // Note that the first time we call mutable_foo(), we get a newly-allocated
210  // string, but if we clear it and call it again, we get the same object again.
211  // We should verify that it has its default value in both cases.
212  message.set_default_string("blah");
213  message.Clear();
214
215  EXPECT_EQ("hello", *message.mutable_default_string());
216}
217
218TEST(GeneratedMessageTest, StringDefaults) {
219  unittest::TestExtremeDefaultValues message;
220  // Check if '\000' can be used in default string value.
221  EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero());
222  EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero());
223}
224
225TEST(GeneratedMessageTest, ReleaseString) {
226  // Check that release_foo() starts out NULL, and gives us a value
227  // that we can delete after it's been set.
228  unittest::TestAllTypes message;
229
230  EXPECT_EQ(NULL, message.release_default_string());
231  EXPECT_FALSE(message.has_default_string());
232  EXPECT_EQ("hello", message.default_string());
233
234  message.set_default_string("blah");
235  EXPECT_TRUE(message.has_default_string());
236  string* str = message.release_default_string();
237  EXPECT_FALSE(message.has_default_string());
238  ASSERT_TRUE(str != NULL);
239  EXPECT_EQ("blah", *str);
240  delete str;
241
242  EXPECT_EQ(NULL, message.release_default_string());
243  EXPECT_FALSE(message.has_default_string());
244  EXPECT_EQ("hello", message.default_string());
245}
246
247TEST(GeneratedMessageTest, ReleaseMessage) {
248  // Check that release_foo() starts out NULL, and gives us a value
249  // that we can delete after it's been set.
250  unittest::TestAllTypes message;
251
252  EXPECT_EQ(NULL, message.release_optional_nested_message());
253  EXPECT_FALSE(message.has_optional_nested_message());
254
255  message.mutable_optional_nested_message()->set_bb(1);
256  unittest::TestAllTypes::NestedMessage* nest =
257      message.release_optional_nested_message();
258  EXPECT_FALSE(message.has_optional_nested_message());
259  ASSERT_TRUE(nest != NULL);
260  EXPECT_EQ(1, nest->bb());
261  delete nest;
262
263  EXPECT_EQ(NULL, message.release_optional_nested_message());
264  EXPECT_FALSE(message.has_optional_nested_message());
265}
266
267TEST(GeneratedMessageTest, SetAllocatedString) {
268  // Check that set_allocated_foo() works for strings.
269  unittest::TestAllTypes message;
270
271  EXPECT_FALSE(message.has_optional_string());
272  const string kHello("hello");
273  message.set_optional_string(kHello);
274  EXPECT_TRUE(message.has_optional_string());
275
276  message.set_allocated_optional_string(NULL);
277  EXPECT_FALSE(message.has_optional_string());
278  EXPECT_EQ("", message.optional_string());
279
280  message.set_allocated_optional_string(new string(kHello));
281  EXPECT_TRUE(message.has_optional_string());
282  EXPECT_EQ(kHello, message.optional_string());
283}
284
285TEST(GeneratedMessageTest, SetAllocatedMessage) {
286  // Check that set_allocated_foo() can be called in all cases.
287  unittest::TestAllTypes message;
288
289  EXPECT_FALSE(message.has_optional_nested_message());
290
291  message.mutable_optional_nested_message()->set_bb(1);
292  EXPECT_TRUE(message.has_optional_nested_message());
293
294  message.set_allocated_optional_nested_message(NULL);
295  EXPECT_FALSE(message.has_optional_nested_message());
296  EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(),
297            &message.optional_nested_message());
298
299  message.mutable_optional_nested_message()->set_bb(1);
300  unittest::TestAllTypes::NestedMessage* nest =
301      message.release_optional_nested_message();
302  ASSERT_TRUE(nest != NULL);
303  EXPECT_FALSE(message.has_optional_nested_message());
304
305  message.set_allocated_optional_nested_message(nest);
306  EXPECT_TRUE(message.has_optional_nested_message());
307  EXPECT_EQ(1, message.optional_nested_message().bb());
308}
309
310TEST(GeneratedMessageTest, Clear) {
311  // Set every field to a unique value, clear the message, then check that
312  // it is cleared.
313  unittest::TestAllTypes message;
314
315  TestUtil::SetAllFields(&message);
316  message.Clear();
317  TestUtil::ExpectClear(message);
318
319  // Unlike with the defaults test, we do NOT expect that requesting embedded
320  // messages will return a pointer to the default instance.  Instead, they
321  // should return the objects that were created when mutable_blah() was
322  // called.
323  EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(),
324            &message.optionalgroup());
325  EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(),
326            &message.optional_nested_message());
327  EXPECT_NE(&unittest::ForeignMessage::default_instance(),
328            &message.optional_foreign_message());
329  EXPECT_NE(&unittest_import::ImportMessage::default_instance(),
330            &message.optional_import_message());
331}
332
333TEST(GeneratedMessageTest, EmbeddedNullsInBytesCharStar) {
334  unittest::TestAllTypes message;
335
336  const char* value = "\0lalala\0\0";
337  message.set_optional_bytes(value, 9);
338  ASSERT_EQ(9, message.optional_bytes().size());
339  EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9));
340
341  message.add_repeated_bytes(value, 9);
342  ASSERT_EQ(9, message.repeated_bytes(0).size());
343  EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9));
344}
345
346TEST(GeneratedMessageTest, ClearOneField) {
347  // Set every field to a unique value, then clear one value and insure that
348  // only that one value is cleared.
349  unittest::TestAllTypes message;
350
351  TestUtil::SetAllFields(&message);
352  int64 original_value = message.optional_int64();
353
354  // Clear the field and make sure it shows up as cleared.
355  message.clear_optional_int64();
356  EXPECT_FALSE(message.has_optional_int64());
357  EXPECT_EQ(0, message.optional_int64());
358
359  // Other adjacent fields should not be cleared.
360  EXPECT_TRUE(message.has_optional_int32());
361  EXPECT_TRUE(message.has_optional_uint32());
362
363  // Make sure if we set it again, then all fields are set.
364  message.set_optional_int64(original_value);
365  TestUtil::ExpectAllFieldsSet(message);
366}
367
368TEST(GeneratedMessageTest, StringCharStarLength) {
369  // Verify that we can use a char*,length to set one of the string fields.
370  unittest::TestAllTypes message;
371  message.set_optional_string("abcdef", 3);
372  EXPECT_EQ("abc", message.optional_string());
373
374  // Verify that we can use a char*,length to add to a repeated string field.
375  message.add_repeated_string("abcdef", 3);
376  EXPECT_EQ(1, message.repeated_string_size());
377  EXPECT_EQ("abc", message.repeated_string(0));
378
379  // Verify that we can use a char*,length to set a repeated string field.
380  message.set_repeated_string(0, "wxyz", 2);
381  EXPECT_EQ("wx", message.repeated_string(0));
382}
383
384TEST(GeneratedMessageTest, CopyFrom) {
385  unittest::TestAllTypes message1, message2;
386
387  TestUtil::SetAllFields(&message1);
388  message2.CopyFrom(message1);
389  TestUtil::ExpectAllFieldsSet(message2);
390
391  // Copying from self should be a no-op.
392  message2.CopyFrom(message2);
393  TestUtil::ExpectAllFieldsSet(message2);
394}
395
396TEST(GeneratedMessageTest, SwapWithEmpty) {
397  unittest::TestAllTypes message1, message2;
398  TestUtil::SetAllFields(&message1);
399
400  TestUtil::ExpectAllFieldsSet(message1);
401  TestUtil::ExpectClear(message2);
402  message1.Swap(&message2);
403  TestUtil::ExpectAllFieldsSet(message2);
404  TestUtil::ExpectClear(message1);
405}
406
407TEST(GeneratedMessageTest, SwapWithSelf) {
408  unittest::TestAllTypes message;
409  TestUtil::SetAllFields(&message);
410  TestUtil::ExpectAllFieldsSet(message);
411  message.Swap(&message);
412  TestUtil::ExpectAllFieldsSet(message);
413}
414
415TEST(GeneratedMessageTest, SwapWithOther) {
416  unittest::TestAllTypes message1, message2;
417
418  message1.set_optional_int32(123);
419  message1.set_optional_string("abc");
420  message1.mutable_optional_nested_message()->set_bb(1);
421  message1.set_optional_nested_enum(unittest::TestAllTypes::FOO);
422  message1.add_repeated_int32(1);
423  message1.add_repeated_int32(2);
424  message1.add_repeated_string("a");
425  message1.add_repeated_string("b");
426  message1.add_repeated_nested_message()->set_bb(7);
427  message1.add_repeated_nested_message()->set_bb(8);
428  message1.add_repeated_nested_enum(unittest::TestAllTypes::FOO);
429  message1.add_repeated_nested_enum(unittest::TestAllTypes::BAR);
430
431  message2.set_optional_int32(456);
432  message2.set_optional_string("def");
433  message2.mutable_optional_nested_message()->set_bb(2);
434  message2.set_optional_nested_enum(unittest::TestAllTypes::BAR);
435  message2.add_repeated_int32(3);
436  message2.add_repeated_string("c");
437  message2.add_repeated_nested_message()->set_bb(9);
438  message2.add_repeated_nested_enum(unittest::TestAllTypes::BAZ);
439
440  message1.Swap(&message2);
441
442  EXPECT_EQ(456, message1.optional_int32());
443  EXPECT_EQ("def", message1.optional_string());
444  EXPECT_EQ(2, message1.optional_nested_message().bb());
445  EXPECT_EQ(unittest::TestAllTypes::BAR, message1.optional_nested_enum());
446  ASSERT_EQ(1, message1.repeated_int32_size());
447  EXPECT_EQ(3, message1.repeated_int32(0));
448  ASSERT_EQ(1, message1.repeated_string_size());
449  EXPECT_EQ("c", message1.repeated_string(0));
450  ASSERT_EQ(1, message1.repeated_nested_message_size());
451  EXPECT_EQ(9, message1.repeated_nested_message(0).bb());
452  ASSERT_EQ(1, message1.repeated_nested_enum_size());
453  EXPECT_EQ(unittest::TestAllTypes::BAZ, message1.repeated_nested_enum(0));
454
455  EXPECT_EQ(123, message2.optional_int32());
456  EXPECT_EQ("abc", message2.optional_string());
457  EXPECT_EQ(1, message2.optional_nested_message().bb());
458  EXPECT_EQ(unittest::TestAllTypes::FOO, message2.optional_nested_enum());
459  ASSERT_EQ(2, message2.repeated_int32_size());
460  EXPECT_EQ(1, message2.repeated_int32(0));
461  EXPECT_EQ(2, message2.repeated_int32(1));
462  ASSERT_EQ(2, message2.repeated_string_size());
463  EXPECT_EQ("a", message2.repeated_string(0));
464  EXPECT_EQ("b", message2.repeated_string(1));
465  ASSERT_EQ(2, message2.repeated_nested_message_size());
466  EXPECT_EQ(7, message2.repeated_nested_message(0).bb());
467  EXPECT_EQ(8, message2.repeated_nested_message(1).bb());
468  ASSERT_EQ(2, message2.repeated_nested_enum_size());
469  EXPECT_EQ(unittest::TestAllTypes::FOO, message2.repeated_nested_enum(0));
470  EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1));
471}
472
473TEST(GeneratedMessageTest, CopyConstructor) {
474  unittest::TestAllTypes message1;
475  TestUtil::SetAllFields(&message1);
476
477  unittest::TestAllTypes message2(message1);
478  TestUtil::ExpectAllFieldsSet(message2);
479}
480
481TEST(GeneratedMessageTest, CopyAssignmentOperator) {
482  unittest::TestAllTypes message1;
483  TestUtil::SetAllFields(&message1);
484
485  unittest::TestAllTypes message2;
486  message2 = message1;
487  TestUtil::ExpectAllFieldsSet(message2);
488
489  // Make sure that self-assignment does something sane.
490  message2.operator=(message2);
491  TestUtil::ExpectAllFieldsSet(message2);
492}
493
494#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
495    !defined(GOOGLE_PROTOBUF_NO_RTTI)
496TEST(GeneratedMessageTest, UpcastCopyFrom) {
497  // Test the CopyFrom method that takes in the generic const Message&
498  // parameter.
499  unittest::TestAllTypes message1, message2;
500
501  TestUtil::SetAllFields(&message1);
502
503  const Message* source = implicit_cast<const Message*>(&message1);
504  message2.CopyFrom(*source);
505
506  TestUtil::ExpectAllFieldsSet(message2);
507}
508#endif
509
510#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
511
512TEST(GeneratedMessageTest, DynamicMessageCopyFrom) {
513  // Test copying from a DynamicMessage, which must fall back to using
514  // reflection.
515  unittest::TestAllTypes message2;
516
517  // Construct a new version of the dynamic message via the factory.
518  DynamicMessageFactory factory;
519  scoped_ptr<Message> message1;
520  message1.reset(factory.GetPrototype(
521                     unittest::TestAllTypes::descriptor())->New());
522
523  TestUtil::ReflectionTester reflection_tester(
524    unittest::TestAllTypes::descriptor());
525  reflection_tester.SetAllFieldsViaReflection(message1.get());
526
527  message2.CopyFrom(*message1);
528
529  TestUtil::ExpectAllFieldsSet(message2);
530}
531
532#endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
533
534TEST(GeneratedMessageTest, NonEmptyMergeFrom) {
535  // Test merging with a non-empty message. Code is a modified form
536  // of that found in google/protobuf/reflection_ops_unittest.cc.
537  unittest::TestAllTypes message1, message2;
538
539  TestUtil::SetAllFields(&message1);
540
541  // This field will test merging into an empty spot.
542  message2.set_optional_int32(message1.optional_int32());
543  message1.clear_optional_int32();
544
545  // This tests overwriting.
546  message2.set_optional_string(message1.optional_string());
547  message1.set_optional_string("something else");
548
549  // This tests concatenating.
550  message2.add_repeated_int32(message1.repeated_int32(1));
551  int32 i = message1.repeated_int32(0);
552  message1.clear_repeated_int32();
553  message1.add_repeated_int32(i);
554
555  message1.MergeFrom(message2);
556
557  TestUtil::ExpectAllFieldsSet(message1);
558}
559
560#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
561    !defined(GOOGLE_PROTOBUF_NO_RTTI)
562#ifdef PROTOBUF_HAS_DEATH_TEST
563
564TEST(GeneratedMessageTest, MergeFromSelf) {
565  unittest::TestAllTypes message;
566  EXPECT_DEATH(message.MergeFrom(message), "&from");
567  EXPECT_DEATH(message.MergeFrom(implicit_cast<const Message&>(message)),
568               "&from");
569}
570
571#endif  // PROTOBUF_HAS_DEATH_TEST
572#endif  // !PROTOBUF_TEST_NO_DESCRIPTORS || !GOOGLE_PROTOBUF_NO_RTTI
573
574// Test the generated SerializeWithCachedSizesToArray(),
575TEST(GeneratedMessageTest, SerializationToArray) {
576  unittest::TestAllTypes message1, message2;
577  string data;
578  TestUtil::SetAllFields(&message1);
579  int size = message1.ByteSize();
580  data.resize(size);
581  uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
582  uint8* end = message1.SerializeWithCachedSizesToArray(start);
583  EXPECT_EQ(size, end - start);
584  EXPECT_TRUE(message2.ParseFromString(data));
585  TestUtil::ExpectAllFieldsSet(message2);
586
587}
588
589TEST(GeneratedMessageTest, PackedFieldsSerializationToArray) {
590  unittest::TestPackedTypes packed_message1, packed_message2;
591  string packed_data;
592  TestUtil::SetPackedFields(&packed_message1);
593  int packed_size = packed_message1.ByteSize();
594  packed_data.resize(packed_size);
595  uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data));
596  uint8* end = packed_message1.SerializeWithCachedSizesToArray(start);
597  EXPECT_EQ(packed_size, end - start);
598  EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
599  TestUtil::ExpectPackedFieldsSet(packed_message2);
600}
601
602// Test the generated SerializeWithCachedSizes() by forcing the buffer to write
603// one byte at a time.
604TEST(GeneratedMessageTest, SerializationToStream) {
605  unittest::TestAllTypes message1, message2;
606  TestUtil::SetAllFields(&message1);
607  int size = message1.ByteSize();
608  string data;
609  data.resize(size);
610  {
611    // Allow the output stream to buffer only one byte at a time.
612    io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
613    io::CodedOutputStream output_stream(&array_stream);
614    message1.SerializeWithCachedSizes(&output_stream);
615    EXPECT_FALSE(output_stream.HadError());
616    EXPECT_EQ(size, output_stream.ByteCount());
617  }
618  EXPECT_TRUE(message2.ParseFromString(data));
619  TestUtil::ExpectAllFieldsSet(message2);
620
621}
622
623TEST(GeneratedMessageTest, PackedFieldsSerializationToStream) {
624  unittest::TestPackedTypes message1, message2;
625  TestUtil::SetPackedFields(&message1);
626  int size = message1.ByteSize();
627  string data;
628  data.resize(size);
629  {
630    // Allow the output stream to buffer only one byte at a time.
631    io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
632    io::CodedOutputStream output_stream(&array_stream);
633    message1.SerializeWithCachedSizes(&output_stream);
634    EXPECT_FALSE(output_stream.HadError());
635    EXPECT_EQ(size, output_stream.ByteCount());
636  }
637  EXPECT_TRUE(message2.ParseFromString(data));
638  TestUtil::ExpectPackedFieldsSet(message2);
639}
640
641
642TEST(GeneratedMessageTest, Required) {
643  // Test that IsInitialized() returns false if required fields are missing.
644  unittest::TestRequired message;
645
646  EXPECT_FALSE(message.IsInitialized());
647  message.set_a(1);
648  EXPECT_FALSE(message.IsInitialized());
649  message.set_b(2);
650  EXPECT_FALSE(message.IsInitialized());
651  message.set_c(3);
652  EXPECT_TRUE(message.IsInitialized());
653}
654
655TEST(GeneratedMessageTest, RequiredForeign) {
656  // Test that IsInitialized() returns false if required fields in nested
657  // messages are missing.
658  unittest::TestRequiredForeign message;
659
660  EXPECT_TRUE(message.IsInitialized());
661
662  message.mutable_optional_message();
663  EXPECT_FALSE(message.IsInitialized());
664
665  message.mutable_optional_message()->set_a(1);
666  message.mutable_optional_message()->set_b(2);
667  message.mutable_optional_message()->set_c(3);
668  EXPECT_TRUE(message.IsInitialized());
669
670  message.add_repeated_message();
671  EXPECT_FALSE(message.IsInitialized());
672
673  message.mutable_repeated_message(0)->set_a(1);
674  message.mutable_repeated_message(0)->set_b(2);
675  message.mutable_repeated_message(0)->set_c(3);
676  EXPECT_TRUE(message.IsInitialized());
677}
678
679TEST(GeneratedMessageTest, ForeignNested) {
680  // Test that TestAllTypes::NestedMessage can be embedded directly into
681  // another message.
682  unittest::TestForeignNested message;
683
684  // If this compiles and runs without crashing, it must work.  We have
685  // nothing more to test.
686  unittest::TestAllTypes::NestedMessage* nested =
687    message.mutable_foreign_nested();
688  nested->set_bb(1);
689}
690
691TEST(GeneratedMessageTest, ReallyLargeTagNumber) {
692  // Test that really large tag numbers don't break anything.
693  unittest::TestReallyLargeTagNumber message1, message2;
694  string data;
695
696  // For the most part, if this compiles and runs then we're probably good.
697  // (The most likely cause for failure would be if something were attempting
698  // to allocate a lookup table of some sort using tag numbers as the index.)
699  // We'll try serializing just for fun.
700  message1.set_a(1234);
701  message1.set_bb(5678);
702  message1.SerializeToString(&data);
703  EXPECT_TRUE(message2.ParseFromString(data));
704  EXPECT_EQ(1234, message2.a());
705  EXPECT_EQ(5678, message2.bb());
706}
707
708TEST(GeneratedMessageTest, MutualRecursion) {
709  // Test that mutually-recursive message types work.
710  unittest::TestMutualRecursionA message;
711  unittest::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a();
712  unittest::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a();
713
714  // Again, if the above compiles and runs, that's all we really have to
715  // test, but just for run we'll check that the system didn't somehow come
716  // up with a pointer loop...
717  EXPECT_NE(&message, nested);
718  EXPECT_NE(&message, nested2);
719  EXPECT_NE(nested, nested2);
720}
721
722TEST(GeneratedMessageTest, CamelCaseFieldNames) {
723  // This test is mainly checking that the following compiles, which verifies
724  // that the field names were coerced to lower-case.
725  //
726  // Protocol buffers standard style is to use lowercase-with-underscores for
727  // field names.  Some old proto1 .protos unfortunately used camel-case field
728  // names.  In proto1, these names were forced to lower-case.  So, we do the
729  // same thing in proto2.
730
731  unittest::TestCamelCaseFieldNames message;
732
733  message.set_primitivefield(2);
734  message.set_stringfield("foo");
735  message.set_enumfield(unittest::FOREIGN_FOO);
736  message.mutable_messagefield()->set_c(6);
737
738  message.add_repeatedprimitivefield(8);
739  message.add_repeatedstringfield("qux");
740  message.add_repeatedenumfield(unittest::FOREIGN_BAR);
741  message.add_repeatedmessagefield()->set_c(15);
742
743  EXPECT_EQ(2, message.primitivefield());
744  EXPECT_EQ("foo", message.stringfield());
745  EXPECT_EQ(unittest::FOREIGN_FOO, message.enumfield());
746  EXPECT_EQ(6, message.messagefield().c());
747
748  EXPECT_EQ(8, message.repeatedprimitivefield(0));
749  EXPECT_EQ("qux", message.repeatedstringfield(0));
750  EXPECT_EQ(unittest::FOREIGN_BAR, message.repeatedenumfield(0));
751  EXPECT_EQ(15, message.repeatedmessagefield(0).c());
752}
753
754TEST(GeneratedMessageTest, TestConflictingSymbolNames) {
755  // test_bad_identifiers.proto successfully compiled, then it works.  The
756  // following is just a token usage to insure that the code is, in fact,
757  // being compiled and linked.
758
759  protobuf_unittest::TestConflictingSymbolNames message;
760  message.set_uint32(1);
761  EXPECT_EQ(3, message.ByteSize());
762
763  message.set_friend_(5);
764  EXPECT_EQ(5, message.friend_());
765
766  // Instantiate extension template functions to test conflicting template
767  // parameter names.
768  typedef protobuf_unittest::TestConflictingSymbolNamesExtension ExtensionMessage;
769  message.AddExtension(ExtensionMessage::repeated_int32_ext, 123);
770  EXPECT_EQ(123,
771            message.GetExtension(ExtensionMessage::repeated_int32_ext, 0));
772}
773
774#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
775
776TEST(GeneratedMessageTest, TestOptimizedForSize) {
777  // We rely on the tests in reflection_ops_unittest and wire_format_unittest
778  // to really test that reflection-based methods work.  Here we are mostly
779  // just making sure that TestOptimizedForSize actually builds and seems to
780  // function.
781
782  protobuf_unittest::TestOptimizedForSize message, message2;
783  message.set_i(1);
784  message.mutable_msg()->set_c(2);
785  message2.CopyFrom(message);
786  EXPECT_EQ(1, message2.i());
787  EXPECT_EQ(2, message2.msg().c());
788}
789
790TEST(GeneratedMessageTest, TestEmbedOptimizedForSize) {
791  // Verifies that something optimized for speed can contain something optimized
792  // for size.
793
794  protobuf_unittest::TestEmbedOptimizedForSize message, message2;
795  message.mutable_optional_message()->set_i(1);
796  message.add_repeated_message()->mutable_msg()->set_c(2);
797  string data;
798  message.SerializeToString(&data);
799  ASSERT_TRUE(message2.ParseFromString(data));
800  EXPECT_EQ(1, message2.optional_message().i());
801  EXPECT_EQ(2, message2.repeated_message(0).msg().c());
802}
803
804TEST(GeneratedMessageTest, TestSpaceUsed) {
805  unittest::TestAllTypes message1;
806  // sizeof provides a lower bound on SpaceUsed().
807  EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsed());
808  const int empty_message_size = message1.SpaceUsed();
809
810  // Setting primitive types shouldn't affect the space used.
811  message1.set_optional_int32(123);
812  message1.set_optional_int64(12345);
813  message1.set_optional_uint32(123);
814  message1.set_optional_uint64(12345);
815  EXPECT_EQ(empty_message_size, message1.SpaceUsed());
816
817  // On some STL implementations, setting the string to a small value should
818  // only increase SpaceUsed() by the size of a string object, though this is
819  // not true everywhere.
820  message1.set_optional_string("abc");
821  EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsed());
822
823  // Setting a string to a value larger than the string object itself should
824  // increase SpaceUsed(), because it cannot store the value internally.
825  message1.set_optional_string(string(sizeof(string) + 1, 'x'));
826  int min_expected_increase = message1.optional_string().capacity() +
827      sizeof(string);
828  EXPECT_LE(empty_message_size + min_expected_increase,
829            message1.SpaceUsed());
830
831  int previous_size = message1.SpaceUsed();
832  // Adding an optional message should increase the size by the size of the
833  // nested message type. NestedMessage is simple enough (1 int field) that it
834  // is equal to sizeof(NestedMessage)
835  message1.mutable_optional_nested_message();
836  ASSERT_EQ(sizeof(unittest::TestAllTypes::NestedMessage),
837            message1.optional_nested_message().SpaceUsed());
838  EXPECT_EQ(previous_size +
839            sizeof(unittest::TestAllTypes::NestedMessage),
840            message1.SpaceUsed());
841}
842
843#endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
844
845
846TEST(GeneratedMessageTest, FieldConstantValues) {
847  unittest::TestRequired message;
848  EXPECT_EQ(unittest::TestAllTypes_NestedMessage::kBbFieldNumber, 1);
849  EXPECT_EQ(unittest::TestAllTypes::kOptionalInt32FieldNumber, 1);
850  EXPECT_EQ(unittest::TestAllTypes::kOptionalgroupFieldNumber, 16);
851  EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedMessageFieldNumber, 18);
852  EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedEnumFieldNumber, 21);
853  EXPECT_EQ(unittest::TestAllTypes::kRepeatedInt32FieldNumber, 31);
854  EXPECT_EQ(unittest::TestAllTypes::kRepeatedgroupFieldNumber, 46);
855  EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48);
856  EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51);
857}
858
859TEST(GeneratedMessageTest, ExtensionConstantValues) {
860  EXPECT_EQ(unittest::TestRequired::kSingleFieldNumber, 1000);
861  EXPECT_EQ(unittest::TestRequired::kMultiFieldNumber, 1001);
862  EXPECT_EQ(unittest::kOptionalInt32ExtensionFieldNumber, 1);
863  EXPECT_EQ(unittest::kOptionalgroupExtensionFieldNumber, 16);
864  EXPECT_EQ(unittest::kOptionalNestedMessageExtensionFieldNumber, 18);
865  EXPECT_EQ(unittest::kOptionalNestedEnumExtensionFieldNumber, 21);
866  EXPECT_EQ(unittest::kRepeatedInt32ExtensionFieldNumber, 31);
867  EXPECT_EQ(unittest::kRepeatedgroupExtensionFieldNumber, 46);
868  EXPECT_EQ(unittest::kRepeatedNestedMessageExtensionFieldNumber, 48);
869  EXPECT_EQ(unittest::kRepeatedNestedEnumExtensionFieldNumber, 51);
870}
871
872// ===================================================================
873
874TEST(GeneratedEnumTest, EnumValuesAsSwitchCases) {
875  // Test that our nested enum values can be used as switch cases.  This test
876  // doesn't actually do anything, the proof that it works is that it
877  // compiles.
878  int i =0;
879  unittest::TestAllTypes::NestedEnum a = unittest::TestAllTypes::BAR;
880  switch (a) {
881    case unittest::TestAllTypes::FOO:
882      i = 1;
883      break;
884    case unittest::TestAllTypes::BAR:
885      i = 2;
886      break;
887    case unittest::TestAllTypes::BAZ:
888      i = 3;
889      break;
890    // no default case:  We want to make sure the compiler recognizes that
891    //   all cases are covered.  (GCC warns if you do not cover all cases of
892    //   an enum in a switch.)
893  }
894
895  // Token check just for fun.
896  EXPECT_EQ(2, i);
897}
898
899TEST(GeneratedEnumTest, IsValidValue) {
900  // Test enum IsValidValue.
901  EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(1));
902  EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(2));
903  EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(3));
904
905  EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(0));
906  EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(4));
907
908  // Make sure it also works when there are dups.
909  EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(1));
910  EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(2));
911  EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(3));
912
913  EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(0));
914  EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(4));
915}
916
917TEST(GeneratedEnumTest, MinAndMax) {
918  EXPECT_EQ(unittest::TestAllTypes::FOO,
919            unittest::TestAllTypes::NestedEnum_MIN);
920  EXPECT_EQ(unittest::TestAllTypes::BAZ,
921            unittest::TestAllTypes::NestedEnum_MAX);
922  EXPECT_EQ(4, unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
923
924  EXPECT_EQ(unittest::FOREIGN_FOO, unittest::ForeignEnum_MIN);
925  EXPECT_EQ(unittest::FOREIGN_BAZ, unittest::ForeignEnum_MAX);
926  EXPECT_EQ(7, unittest::ForeignEnum_ARRAYSIZE);
927
928  EXPECT_EQ(1, unittest::TestEnumWithDupValue_MIN);
929  EXPECT_EQ(3, unittest::TestEnumWithDupValue_MAX);
930  EXPECT_EQ(4, unittest::TestEnumWithDupValue_ARRAYSIZE);
931
932  EXPECT_EQ(unittest::SPARSE_E, unittest::TestSparseEnum_MIN);
933  EXPECT_EQ(unittest::SPARSE_C, unittest::TestSparseEnum_MAX);
934  EXPECT_EQ(12589235, unittest::TestSparseEnum_ARRAYSIZE);
935
936  // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE.
937  void* null_pointer = 0;  // NULL may be integer-type, not pointer-type.
938  EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MIN);
939  EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MAX);
940  EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_ARRAYSIZE);
941
942  EXPECT_NE(null_pointer, &unittest::ForeignEnum_MIN);
943  EXPECT_NE(null_pointer, &unittest::ForeignEnum_MAX);
944  EXPECT_NE(null_pointer, &unittest::ForeignEnum_ARRAYSIZE);
945
946  // Make sure we can use _MIN and _MAX as switch cases.
947  switch (unittest::SPARSE_A) {
948    case unittest::TestSparseEnum_MIN:
949    case unittest::TestSparseEnum_MAX:
950      break;
951    default:
952      break;
953  }
954}
955
956#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
957
958TEST(GeneratedEnumTest, Name) {
959  // "Names" in the presence of dup values are a bit arbitrary.
960  EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO1));
961  EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO2));
962
963  EXPECT_EQ("SPARSE_A", unittest::TestSparseEnum_Name(unittest::SPARSE_A));
964  EXPECT_EQ("SPARSE_B", unittest::TestSparseEnum_Name(unittest::SPARSE_B));
965  EXPECT_EQ("SPARSE_C", unittest::TestSparseEnum_Name(unittest::SPARSE_C));
966  EXPECT_EQ("SPARSE_D", unittest::TestSparseEnum_Name(unittest::SPARSE_D));
967  EXPECT_EQ("SPARSE_E", unittest::TestSparseEnum_Name(unittest::SPARSE_E));
968  EXPECT_EQ("SPARSE_F", unittest::TestSparseEnum_Name(unittest::SPARSE_F));
969  EXPECT_EQ("SPARSE_G", unittest::TestSparseEnum_Name(unittest::SPARSE_G));
970}
971
972TEST(GeneratedEnumTest, Parse) {
973  unittest::TestEnumWithDupValue dup_value = unittest::FOO1;
974  EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO1", &dup_value));
975  EXPECT_EQ(unittest::FOO1, dup_value);
976  EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO2", &dup_value));
977  EXPECT_EQ(unittest::FOO2, dup_value);
978  EXPECT_FALSE(unittest::TestEnumWithDupValue_Parse("FOO", &dup_value));
979}
980
981TEST(GeneratedEnumTest, GetEnumDescriptor) {
982  EXPECT_EQ(unittest::TestAllTypes::NestedEnum_descriptor(),
983            GetEnumDescriptor<unittest::TestAllTypes::NestedEnum>());
984  EXPECT_EQ(unittest::ForeignEnum_descriptor(),
985            GetEnumDescriptor<unittest::ForeignEnum>());
986  EXPECT_EQ(unittest::TestEnumWithDupValue_descriptor(),
987            GetEnumDescriptor<unittest::TestEnumWithDupValue>());
988  EXPECT_EQ(unittest::TestSparseEnum_descriptor(),
989            GetEnumDescriptor<unittest::TestSparseEnum>());
990}
991
992#endif  // PROTOBUF_TEST_NO_DESCRIPTORS
993
994// ===================================================================
995
996#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
997
998// Support code for testing services.
999class GeneratedServiceTest : public testing::Test {
1000 protected:
1001  class MockTestService : public unittest::TestService {
1002   public:
1003    MockTestService()
1004      : called_(false),
1005        method_(""),
1006        controller_(NULL),
1007        request_(NULL),
1008        response_(NULL),
1009        done_(NULL) {}
1010
1011    ~MockTestService() {}
1012
1013    void Reset() { called_ = false; }
1014
1015    // implements TestService ----------------------------------------
1016
1017    void Foo(RpcController* controller,
1018             const unittest::FooRequest* request,
1019             unittest::FooResponse* response,
1020             Closure* done) {
1021      ASSERT_FALSE(called_);
1022      called_ = true;
1023      method_ = "Foo";
1024      controller_ = controller;
1025      request_ = request;
1026      response_ = response;
1027      done_ = done;
1028    }
1029
1030    void Bar(RpcController* controller,
1031             const unittest::BarRequest* request,
1032             unittest::BarResponse* response,
1033             Closure* done) {
1034      ASSERT_FALSE(called_);
1035      called_ = true;
1036      method_ = "Bar";
1037      controller_ = controller;
1038      request_ = request;
1039      response_ = response;
1040      done_ = done;
1041    }
1042
1043    // ---------------------------------------------------------------
1044
1045    bool called_;
1046    string method_;
1047    RpcController* controller_;
1048    const Message* request_;
1049    Message* response_;
1050    Closure* done_;
1051  };
1052
1053  class MockRpcChannel : public RpcChannel {
1054   public:
1055    MockRpcChannel()
1056      : called_(false),
1057        method_(NULL),
1058        controller_(NULL),
1059        request_(NULL),
1060        response_(NULL),
1061        done_(NULL),
1062        destroyed_(NULL) {}
1063
1064    ~MockRpcChannel() {
1065      if (destroyed_ != NULL) *destroyed_ = true;
1066    }
1067
1068    void Reset() { called_ = false; }
1069
1070    // implements TestService ----------------------------------------
1071
1072    void CallMethod(const MethodDescriptor* method,
1073                    RpcController* controller,
1074                    const Message* request,
1075                    Message* response,
1076                    Closure* done) {
1077      ASSERT_FALSE(called_);
1078      called_ = true;
1079      method_ = method;
1080      controller_ = controller;
1081      request_ = request;
1082      response_ = response;
1083      done_ = done;
1084    }
1085
1086    // ---------------------------------------------------------------
1087
1088    bool called_;
1089    const MethodDescriptor* method_;
1090    RpcController* controller_;
1091    const Message* request_;
1092    Message* response_;
1093    Closure* done_;
1094    bool* destroyed_;
1095  };
1096
1097  class MockController : public RpcController {
1098   public:
1099    void Reset() {
1100      ADD_FAILURE() << "Reset() not expected during this test.";
1101    }
1102    bool Failed() const {
1103      ADD_FAILURE() << "Failed() not expected during this test.";
1104      return false;
1105    }
1106    string ErrorText() const {
1107      ADD_FAILURE() << "ErrorText() not expected during this test.";
1108      return "";
1109    }
1110    void StartCancel() {
1111      ADD_FAILURE() << "StartCancel() not expected during this test.";
1112    }
1113    void SetFailed(const string& reason) {
1114      ADD_FAILURE() << "SetFailed() not expected during this test.";
1115    }
1116    bool IsCanceled() const {
1117      ADD_FAILURE() << "IsCanceled() not expected during this test.";
1118      return false;
1119    }
1120    void NotifyOnCancel(Closure* callback) {
1121      ADD_FAILURE() << "NotifyOnCancel() not expected during this test.";
1122    }
1123  };
1124
1125  GeneratedServiceTest()
1126    : descriptor_(unittest::TestService::descriptor()),
1127      foo_(descriptor_->FindMethodByName("Foo")),
1128      bar_(descriptor_->FindMethodByName("Bar")),
1129      stub_(&mock_channel_),
1130      done_(NewPermanentCallback(&DoNothing)) {}
1131
1132  virtual void SetUp() {
1133    ASSERT_TRUE(foo_ != NULL);
1134    ASSERT_TRUE(bar_ != NULL);
1135  }
1136
1137  const ServiceDescriptor* descriptor_;
1138  const MethodDescriptor* foo_;
1139  const MethodDescriptor* bar_;
1140
1141  MockTestService mock_service_;
1142  MockController mock_controller_;
1143
1144  MockRpcChannel mock_channel_;
1145  unittest::TestService::Stub stub_;
1146
1147  // Just so we don't have to re-define these with every test.
1148  unittest::FooRequest foo_request_;
1149  unittest::FooResponse foo_response_;
1150  unittest::BarRequest bar_request_;
1151  unittest::BarResponse bar_response_;
1152  scoped_ptr<Closure> done_;
1153};
1154
1155TEST_F(GeneratedServiceTest, GetDescriptor) {
1156  // Test that GetDescriptor() works.
1157
1158  EXPECT_EQ(descriptor_, mock_service_.GetDescriptor());
1159}
1160
1161TEST_F(GeneratedServiceTest, GetChannel) {
1162  EXPECT_EQ(&mock_channel_, stub_.channel());
1163}
1164
1165TEST_F(GeneratedServiceTest, OwnsChannel) {
1166  MockRpcChannel* channel = new MockRpcChannel;
1167  bool destroyed = false;
1168  channel->destroyed_ = &destroyed;
1169
1170  {
1171    unittest::TestService::Stub owning_stub(channel,
1172                                            Service::STUB_OWNS_CHANNEL);
1173    EXPECT_FALSE(destroyed);
1174  }
1175
1176  EXPECT_TRUE(destroyed);
1177}
1178
1179TEST_F(GeneratedServiceTest, CallMethod) {
1180  // Test that CallMethod() works.
1181
1182  // Call Foo() via CallMethod().
1183  mock_service_.CallMethod(foo_, &mock_controller_,
1184                           &foo_request_, &foo_response_, done_.get());
1185
1186  ASSERT_TRUE(mock_service_.called_);
1187
1188  EXPECT_EQ("Foo"            , mock_service_.method_    );
1189  EXPECT_EQ(&mock_controller_, mock_service_.controller_);
1190  EXPECT_EQ(&foo_request_    , mock_service_.request_   );
1191  EXPECT_EQ(&foo_response_   , mock_service_.response_  );
1192  EXPECT_EQ(done_.get()      , mock_service_.done_      );
1193
1194  // Try again, but call Bar() instead.
1195  mock_service_.Reset();
1196  mock_service_.CallMethod(bar_, &mock_controller_,
1197                           &bar_request_, &bar_response_, done_.get());
1198
1199  ASSERT_TRUE(mock_service_.called_);
1200  EXPECT_EQ("Bar", mock_service_.method_);
1201}
1202
1203TEST_F(GeneratedServiceTest, CallMethodTypeFailure) {
1204  // Verify death if we call Foo() with Bar's message types.
1205
1206#ifdef PROTOBUF_HAS_DEATH_TEST  // death tests do not work on Windows yet
1207  EXPECT_DEBUG_DEATH(
1208    mock_service_.CallMethod(foo_, &mock_controller_,
1209                             &foo_request_, &bar_response_, done_.get()),
1210    "dynamic_cast");
1211
1212  mock_service_.Reset();
1213  EXPECT_DEBUG_DEATH(
1214    mock_service_.CallMethod(foo_, &mock_controller_,
1215                             &bar_request_, &foo_response_, done_.get()),
1216    "dynamic_cast");
1217#endif  // PROTOBUF_HAS_DEATH_TEST
1218}
1219
1220TEST_F(GeneratedServiceTest, GetPrototypes) {
1221  // Test Get{Request,Response}Prototype() methods.
1222
1223  EXPECT_EQ(&unittest::FooRequest::default_instance(),
1224            &mock_service_.GetRequestPrototype(foo_));
1225  EXPECT_EQ(&unittest::BarRequest::default_instance(),
1226            &mock_service_.GetRequestPrototype(bar_));
1227
1228  EXPECT_EQ(&unittest::FooResponse::default_instance(),
1229            &mock_service_.GetResponsePrototype(foo_));
1230  EXPECT_EQ(&unittest::BarResponse::default_instance(),
1231            &mock_service_.GetResponsePrototype(bar_));
1232}
1233
1234TEST_F(GeneratedServiceTest, Stub) {
1235  // Test that the stub class works.
1236
1237  // Call Foo() via the stub.
1238  stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get());
1239
1240  ASSERT_TRUE(mock_channel_.called_);
1241
1242  EXPECT_EQ(foo_             , mock_channel_.method_    );
1243  EXPECT_EQ(&mock_controller_, mock_channel_.controller_);
1244  EXPECT_EQ(&foo_request_    , mock_channel_.request_   );
1245  EXPECT_EQ(&foo_response_   , mock_channel_.response_  );
1246  EXPECT_EQ(done_.get()      , mock_channel_.done_      );
1247
1248  // Call Bar() via the stub.
1249  mock_channel_.Reset();
1250  stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get());
1251
1252  ASSERT_TRUE(mock_channel_.called_);
1253  EXPECT_EQ(bar_, mock_channel_.method_);
1254}
1255
1256TEST_F(GeneratedServiceTest, NotImplemented) {
1257  // Test that failing to implement a method of a service causes it to fail
1258  // with a "not implemented" error message.
1259
1260  // A service which doesn't implement any methods.
1261  class UnimplementedService : public unittest::TestService {
1262   public:
1263    UnimplementedService() {}
1264  };
1265
1266  UnimplementedService unimplemented_service;
1267
1268  // And a controller which expects to get a "not implemented" error.
1269  class ExpectUnimplementedController : public MockController {
1270   public:
1271    ExpectUnimplementedController() : called_(false) {}
1272
1273    void SetFailed(const string& reason) {
1274      EXPECT_FALSE(called_);
1275      called_ = true;
1276      EXPECT_EQ("Method Foo() not implemented.", reason);
1277    }
1278
1279    bool called_;
1280  };
1281
1282  ExpectUnimplementedController controller;
1283
1284  // Call Foo.
1285  unimplemented_service.Foo(&controller, &foo_request_, &foo_response_,
1286                            done_.get());
1287
1288  EXPECT_TRUE(controller.called_);
1289}
1290
1291}  // namespace cpp_unittest
1292}  // namespace cpp
1293}  // namespace compiler
1294
1295namespace no_generic_services_test {
1296  // Verify that no class called "TestService" was defined in
1297  // unittest_no_generic_services.pb.h by defining a different type by the same
1298  // name.  If such a service was generated, this will not compile.
1299  struct TestService {
1300    int i;
1301  };
1302}
1303
1304namespace compiler {
1305namespace cpp {
1306namespace cpp_unittest {
1307
1308TEST_F(GeneratedServiceTest, NoGenericServices) {
1309  // Verify that non-services in unittest_no_generic_services.proto were
1310  // generated.
1311  no_generic_services_test::TestMessage message;
1312  message.set_a(1);
1313  message.SetExtension(no_generic_services_test::test_extension, 123);
1314  no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
1315  EXPECT_EQ(e, 1);
1316
1317  // Verify that a ServiceDescriptor is generated for the service even if the
1318  // class itself is not.
1319  const FileDescriptor* file =
1320      no_generic_services_test::TestMessage::descriptor()->file();
1321
1322  ASSERT_EQ(1, file->service_count());
1323  EXPECT_EQ("TestService", file->service(0)->name());
1324  ASSERT_EQ(1, file->service(0)->method_count());
1325  EXPECT_EQ("Foo", file->service(0)->method(0)->name());
1326}
1327
1328#endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
1329
1330// ===================================================================
1331
1332// This test must run last.  It verifies that descriptors were or were not
1333// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined.
1334// When this is defined, we skip all tests which are expected to trigger
1335// descriptor initialization.  This verifies that everything else still works
1336// if descriptors are not initialized.
1337TEST(DescriptorInitializationTest, Initialized) {
1338#ifdef PROTOBUF_TEST_NO_DESCRIPTORS
1339  bool should_have_descriptors = false;
1340#else
1341  bool should_have_descriptors = true;
1342#endif
1343
1344  EXPECT_EQ(should_have_descriptors,
1345    DescriptorPool::generated_pool()->InternalIsFileLoaded(
1346      "google/protobuf/unittest.proto"));
1347}
1348
1349}  // namespace cpp_unittest
1350
1351}  // namespace cpp
1352}  // namespace compiler
1353}  // namespace protobuf
1354}  // namespace google
1355