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