PageRenderTime 104ms CodeModel.GetById 10ms app.highlight 83ms RepoModel.GetById 1ms app.codeStats 1ms

/thirdparty/breakpad/third_party/protobuf/protobuf/src/google/protobuf/compiler/cpp/cpp_unittest.cc

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