1 // Copyright 2005, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 30 // 31 // Tests for Google Test itself. This verifies that the basic constructs of 32 // Google Test work. 33 34 #include "gtest/gtest.h" 35 36 // Verifies that the command line flag variables can be accessed in 37 // code once "gtest.h" has been #included. 38 // Do not move it after other gtest #includes. 39 TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { 40 bool dummy = 41 GTEST_FLAG_GET(also_run_disabled_tests) || 42 GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) || 43 GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) || 44 GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) || 45 GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) || 46 GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) || 47 GTEST_FLAG_GET(repeat) > 0 || 48 GTEST_FLAG_GET(recreate_environments_when_repeating) || 49 GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) || 50 GTEST_FLAG_GET(stack_trace_depth) > 0 || 51 GTEST_FLAG_GET(stream_result_to) != "unknown" || 52 GTEST_FLAG_GET(throw_on_failure); 53 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused. 54 } 55 56 #include <limits.h> // For INT_MAX. 57 #include <stdlib.h> 58 #include <string.h> 59 #include <time.h> 60 61 #include <cstdint> 62 #include <map> 63 #include <memory> 64 #include <ostream> 65 #include <set> 66 #include <stdexcept> 67 #include <string> 68 #include <type_traits> 69 #include <unordered_set> 70 #include <utility> 71 #include <vector> 72 73 #include "gtest/gtest-spi.h" 74 #include "src/gtest-internal-inl.h" 75 76 struct ConvertibleGlobalType { 77 // The inner enable_if is to ensure invoking is_constructible doesn't fail. 78 // The outer enable_if is to ensure the overload resolution doesn't encounter 79 // an ambiguity. 80 template < 81 class T, 82 std::enable_if_t< 83 false, std::enable_if_t<std::is_constructible<T>::value, int>> = 0> 84 operator T() const; // NOLINT(google-explicit-constructor) 85 }; 86 void operator<<(ConvertibleGlobalType&, int); 87 static_assert(sizeof(decltype(std::declval<ConvertibleGlobalType&>() 88 << 1)(*)()) > 0, 89 "error in operator<< overload resolution"); 90 91 namespace testing { 92 namespace internal { 93 94 #if GTEST_CAN_STREAM_RESULTS_ 95 96 class StreamingListenerTest : public Test { 97 public: 98 class FakeSocketWriter : public StreamingListener::AbstractSocketWriter { 99 public: 100 // Sends a string to the socket. 101 void Send(const std::string& message) override { output_ += message; } 102 103 std::string output_; 104 }; 105 106 StreamingListenerTest() 107 : fake_sock_writer_(new FakeSocketWriter), 108 streamer_(fake_sock_writer_), 109 test_info_obj_("FooTest", "Bar", nullptr, nullptr, 110 CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {} 111 112 protected: 113 std::string* output() { return &(fake_sock_writer_->output_); } 114 115 FakeSocketWriter* const fake_sock_writer_; 116 StreamingListener streamer_; 117 UnitTest unit_test_; 118 TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test. 119 }; 120 121 TEST_F(StreamingListenerTest, OnTestProgramEnd) { 122 *output() = ""; 123 streamer_.OnTestProgramEnd(unit_test_); 124 EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output()); 125 } 126 127 TEST_F(StreamingListenerTest, OnTestIterationEnd) { 128 *output() = ""; 129 streamer_.OnTestIterationEnd(unit_test_, 42); 130 EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output()); 131 } 132 133 TEST_F(StreamingListenerTest, OnTestSuiteStart) { 134 *output() = ""; 135 streamer_.OnTestSuiteStart(TestSuite("FooTest", "Bar", nullptr, nullptr)); 136 EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output()); 137 } 138 139 TEST_F(StreamingListenerTest, OnTestSuiteEnd) { 140 *output() = ""; 141 streamer_.OnTestSuiteEnd(TestSuite("FooTest", "Bar", nullptr, nullptr)); 142 EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output()); 143 } 144 145 TEST_F(StreamingListenerTest, OnTestStart) { 146 *output() = ""; 147 streamer_.OnTestStart(test_info_obj_); 148 EXPECT_EQ("event=TestStart&name=Bar\n", *output()); 149 } 150 151 TEST_F(StreamingListenerTest, OnTestEnd) { 152 *output() = ""; 153 streamer_.OnTestEnd(test_info_obj_); 154 EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output()); 155 } 156 157 TEST_F(StreamingListenerTest, OnTestPartResult) { 158 *output() = ""; 159 streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure, 160 "foo.cc", 42, "failed=\n&%")); 161 162 // Meta characters in the failure message should be properly escaped. 163 EXPECT_EQ( 164 "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n", 165 *output()); 166 } 167 168 #endif // GTEST_CAN_STREAM_RESULTS_ 169 170 // Provides access to otherwise private parts of the TestEventListeners class 171 // that are needed to test it. 172 class TestEventListenersAccessor { 173 public: 174 static TestEventListener* GetRepeater(TestEventListeners* listeners) { 175 return listeners->repeater(); 176 } 177 178 static void SetDefaultResultPrinter(TestEventListeners* listeners, 179 TestEventListener* listener) { 180 listeners->SetDefaultResultPrinter(listener); 181 } 182 static void SetDefaultXmlGenerator(TestEventListeners* listeners, 183 TestEventListener* listener) { 184 listeners->SetDefaultXmlGenerator(listener); 185 } 186 187 static bool EventForwardingEnabled(const TestEventListeners& listeners) { 188 return listeners.EventForwardingEnabled(); 189 } 190 191 static void SuppressEventForwarding(TestEventListeners* listeners) { 192 listeners->SuppressEventForwarding(true); 193 } 194 }; 195 196 class UnitTestRecordPropertyTestHelper : public Test { 197 protected: 198 UnitTestRecordPropertyTestHelper() {} 199 200 // Forwards to UnitTest::RecordProperty() to bypass access controls. 201 void UnitTestRecordProperty(const char* key, const std::string& value) { 202 unit_test_.RecordProperty(key, value); 203 } 204 205 UnitTest unit_test_; 206 }; 207 208 } // namespace internal 209 } // namespace testing 210 211 using testing::AssertionFailure; 212 using testing::AssertionResult; 213 using testing::AssertionSuccess; 214 using testing::DoubleLE; 215 using testing::EmptyTestEventListener; 216 using testing::Environment; 217 using testing::FloatLE; 218 using testing::IsNotSubstring; 219 using testing::IsSubstring; 220 using testing::kMaxStackTraceDepth; 221 using testing::Message; 222 using testing::ScopedFakeTestPartResultReporter; 223 using testing::StaticAssertTypeEq; 224 using testing::Test; 225 using testing::TestEventListeners; 226 using testing::TestInfo; 227 using testing::TestPartResult; 228 using testing::TestPartResultArray; 229 using testing::TestProperty; 230 using testing::TestResult; 231 using testing::TimeInMillis; 232 using testing::UnitTest; 233 using testing::internal::AlwaysFalse; 234 using testing::internal::AlwaysTrue; 235 using testing::internal::AppendUserMessage; 236 using testing::internal::ArrayAwareFind; 237 using testing::internal::ArrayEq; 238 using testing::internal::CodePointToUtf8; 239 using testing::internal::CopyArray; 240 using testing::internal::CountIf; 241 using testing::internal::EqFailure; 242 using testing::internal::FloatingPoint; 243 using testing::internal::ForEach; 244 using testing::internal::FormatEpochTimeInMillisAsIso8601; 245 using testing::internal::FormatTimeInMillisAsSeconds; 246 using testing::internal::GetElementOr; 247 using testing::internal::GetNextRandomSeed; 248 using testing::internal::GetRandomSeedFromFlag; 249 using testing::internal::GetTestTypeId; 250 using testing::internal::GetTimeInMillis; 251 using testing::internal::GetTypeId; 252 using testing::internal::GetUnitTestImpl; 253 using testing::internal::GTestFlagSaver; 254 using testing::internal::HasDebugStringAndShortDebugString; 255 using testing::internal::Int32FromEnvOrDie; 256 using testing::internal::IsContainer; 257 using testing::internal::IsContainerTest; 258 using testing::internal::IsNotContainer; 259 using testing::internal::kMaxRandomSeed; 260 using testing::internal::kTestTypeIdInGoogleTest; 261 using testing::internal::NativeArray; 262 using testing::internal::ParseFlag; 263 using testing::internal::RelationToSourceCopy; 264 using testing::internal::RelationToSourceReference; 265 using testing::internal::ShouldRunTestOnShard; 266 using testing::internal::ShouldShard; 267 using testing::internal::ShouldUseColor; 268 using testing::internal::Shuffle; 269 using testing::internal::ShuffleRange; 270 using testing::internal::SkipPrefix; 271 using testing::internal::StreamableToString; 272 using testing::internal::String; 273 using testing::internal::TestEventListenersAccessor; 274 using testing::internal::TestResultAccessor; 275 using testing::internal::WideStringToUtf8; 276 using testing::internal::edit_distance::CalculateOptimalEdits; 277 using testing::internal::edit_distance::CreateUnifiedDiff; 278 using testing::internal::edit_distance::EditType; 279 280 #if GTEST_HAS_STREAM_REDIRECTION 281 using testing::internal::CaptureStdout; 282 using testing::internal::GetCapturedStdout; 283 #endif 284 285 #ifdef GTEST_IS_THREADSAFE 286 using testing::internal::ThreadWithParam; 287 #endif 288 289 class TestingVector : public std::vector<int> {}; 290 291 ::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) { 292 os << "{ "; 293 for (size_t i = 0; i < vector.size(); i++) { 294 os << vector[i] << " "; 295 } 296 os << "}"; 297 return os; 298 } 299 300 // This line tests that we can define tests in an unnamed namespace. 301 namespace { 302 303 TEST(GetRandomSeedFromFlagTest, HandlesZero) { 304 const int seed = GetRandomSeedFromFlag(0); 305 EXPECT_LE(1, seed); 306 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed)); 307 } 308 309 TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) { 310 EXPECT_EQ(1, GetRandomSeedFromFlag(1)); 311 EXPECT_EQ(2, GetRandomSeedFromFlag(2)); 312 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1)); 313 EXPECT_EQ(static_cast<int>(kMaxRandomSeed), 314 GetRandomSeedFromFlag(kMaxRandomSeed)); 315 } 316 317 TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) { 318 const int seed1 = GetRandomSeedFromFlag(-1); 319 EXPECT_LE(1, seed1); 320 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed)); 321 322 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1); 323 EXPECT_LE(1, seed2); 324 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed)); 325 } 326 327 TEST(GetNextRandomSeedTest, WorksForValidInput) { 328 EXPECT_EQ(2, GetNextRandomSeed(1)); 329 EXPECT_EQ(3, GetNextRandomSeed(2)); 330 EXPECT_EQ(static_cast<int>(kMaxRandomSeed), 331 GetNextRandomSeed(kMaxRandomSeed - 1)); 332 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed)); 333 334 // We deliberately don't test GetNextRandomSeed() with invalid 335 // inputs, as that requires death tests, which are expensive. This 336 // is fine as GetNextRandomSeed() is internal and has a 337 // straightforward definition. 338 } 339 340 static void ClearCurrentTestPartResults() { 341 TestResultAccessor::ClearTestPartResults( 342 GetUnitTestImpl()->current_test_result()); 343 } 344 345 // Tests GetTypeId. 346 347 TEST(GetTypeIdTest, ReturnsSameValueForSameType) { 348 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>()); 349 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>()); 350 } 351 352 class SubClassOfTest : public Test {}; 353 class AnotherSubClassOfTest : public Test {}; 354 355 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) { 356 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>()); 357 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>()); 358 EXPECT_NE(GetTypeId<int>(), GetTestTypeId()); 359 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId()); 360 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId()); 361 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>()); 362 } 363 364 // Verifies that GetTestTypeId() returns the same value, no matter it 365 // is called from inside Google Test or outside of it. 366 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { 367 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); 368 } 369 370 // Tests CanonicalizeForStdLibVersioning. 371 372 using ::testing::internal::CanonicalizeForStdLibVersioning; 373 374 TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) { 375 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind")); 376 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_")); 377 EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo")); 378 EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x")); 379 EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x")); 380 EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x")); 381 } 382 383 TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) { 384 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind")); 385 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_")); 386 387 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind")); 388 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_")); 389 390 EXPECT_EQ("std::bind", 391 CanonicalizeForStdLibVersioning("std::__google::bind")); 392 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_")); 393 } 394 395 // Tests FormatTimeInMillisAsSeconds(). 396 397 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { 398 EXPECT_EQ("0.", FormatTimeInMillisAsSeconds(0)); 399 } 400 401 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) { 402 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3)); 403 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10)); 404 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200)); 405 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200)); 406 EXPECT_EQ("3.", FormatTimeInMillisAsSeconds(3000)); 407 EXPECT_EQ("10.", FormatTimeInMillisAsSeconds(10000)); 408 EXPECT_EQ("100.", FormatTimeInMillisAsSeconds(100000)); 409 EXPECT_EQ("123.456", FormatTimeInMillisAsSeconds(123456)); 410 EXPECT_EQ("1234567.89", FormatTimeInMillisAsSeconds(1234567890)); 411 } 412 413 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) { 414 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3)); 415 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10)); 416 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200)); 417 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200)); 418 EXPECT_EQ("-3.", FormatTimeInMillisAsSeconds(-3000)); 419 EXPECT_EQ("-10.", FormatTimeInMillisAsSeconds(-10000)); 420 EXPECT_EQ("-100.", FormatTimeInMillisAsSeconds(-100000)); 421 EXPECT_EQ("-123.456", FormatTimeInMillisAsSeconds(-123456)); 422 EXPECT_EQ("-1234567.89", FormatTimeInMillisAsSeconds(-1234567890)); 423 } 424 425 // TODO: b/287046337 - In emscripten, local time zone modification is not 426 // supported. 427 #if !defined(__EMSCRIPTEN__) 428 // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion 429 // for particular dates below was verified in Python using 430 // datetime.datetime.fromutctimestamp(<timestamp>/1000). 431 432 // FormatEpochTimeInMillisAsIso8601 depends on the local timezone, so we 433 // have to set up a particular timezone to obtain predictable results. 434 class FormatEpochTimeInMillisAsIso8601Test : public Test { 435 public: 436 // On Cygwin, GCC doesn't allow unqualified integer literals to exceed 437 // 32 bits, even when 64-bit integer types are available. We have to 438 // force the constants to have a 64-bit type here. 439 static const TimeInMillis kMillisPerSec = 1000; 440 441 private: 442 void SetUp() override { 443 saved_tz_.reset(); 444 445 GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv: deprecated */) 446 if (const char* tz = getenv("TZ")) { 447 saved_tz_ = std::make_unique<std::string>(tz); 448 } 449 GTEST_DISABLE_MSC_DEPRECATED_POP_() 450 451 // Set the local time zone for FormatEpochTimeInMillisAsIso8601 to be 452 // a fixed time zone for reproducibility purposes. 453 SetTimeZone("UTC+00"); 454 } 455 456 void TearDown() override { 457 SetTimeZone(saved_tz_ != nullptr ? saved_tz_->c_str() : nullptr); 458 saved_tz_.reset(); 459 } 460 461 static void SetTimeZone(const char* time_zone) { 462 // tzset() distinguishes between the TZ variable being present and empty 463 // and not being present, so we have to consider the case of time_zone 464 // being NULL. 465 #if defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW) 466 // ...Unless it's MSVC, whose standard library's _putenv doesn't 467 // distinguish between an empty and a missing variable. 468 const std::string env_var = 469 std::string("TZ=") + (time_zone ? time_zone : ""); 470 _putenv(env_var.c_str()); 471 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) 472 tzset(); 473 GTEST_DISABLE_MSC_WARNINGS_POP_() 474 #else 475 #if defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ < 21 476 // Work around KitKat bug in tzset by setting "UTC" before setting "UTC+00". 477 // See https://github.com/android/ndk/issues/1604. 478 setenv("TZ", "UTC", 1); 479 tzset(); 480 #endif 481 if (time_zone) { 482 setenv(("TZ"), time_zone, 1); 483 } else { 484 unsetenv("TZ"); 485 } 486 tzset(); 487 #endif 488 } 489 490 std::unique_ptr<std::string> saved_tz_; // Empty and null are different here 491 }; 492 493 const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec; 494 495 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) { 496 EXPECT_EQ("2011-10-31T18:52:42.000", 497 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec)); 498 } 499 500 TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) { 501 EXPECT_EQ("2011-10-31T18:52:42.234", 502 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); 503 } 504 505 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) { 506 EXPECT_EQ("2011-09-03T05:07:02.000", 507 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec)); 508 } 509 510 TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) { 511 EXPECT_EQ("2011-09-28T17:08:22.000", 512 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec)); 513 } 514 515 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { 516 EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0)); 517 } 518 519 #endif // __EMSCRIPTEN__ 520 521 #ifdef __BORLANDC__ 522 // Silences warnings: "Condition is always true", "Unreachable code" 523 #pragma option push -w-ccc -w-rch 524 #endif 525 526 // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal 527 // when the RHS is a pointer type. 528 TEST(NullLiteralTest, LHSAllowsNullLiterals) { 529 EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT 530 ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT 531 EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT 532 ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT 533 EXPECT_EQ(nullptr, static_cast<void*>(nullptr)); 534 ASSERT_EQ(nullptr, static_cast<void*>(nullptr)); 535 536 const int* const p = nullptr; 537 EXPECT_EQ(0, p); // NOLINT 538 ASSERT_EQ(0, p); // NOLINT 539 EXPECT_EQ(NULL, p); // NOLINT 540 ASSERT_EQ(NULL, p); // NOLINT 541 EXPECT_EQ(nullptr, p); 542 ASSERT_EQ(nullptr, p); 543 } 544 545 struct ConvertToAll { 546 template <typename T> 547 operator T() const { // NOLINT 548 return T(); 549 } 550 }; 551 552 struct ConvertToPointer { 553 template <class T> 554 operator T*() const { // NOLINT 555 return nullptr; 556 } 557 }; 558 559 struct ConvertToAllButNoPointers { 560 template <typename T, 561 typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0> 562 operator T() const { // NOLINT 563 return T(); 564 } 565 }; 566 567 struct MyType {}; 568 inline bool operator==(MyType const&, MyType const&) { return true; } 569 570 TEST(NullLiteralTest, ImplicitConversion) { 571 EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr)); 572 #if !defined(__GNUC__) || defined(__clang__) 573 // Disabled due to GCC bug gcc.gnu.org/PR89580 574 EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr)); 575 #endif 576 EXPECT_EQ(ConvertToAll{}, MyType{}); 577 EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{}); 578 } 579 580 #ifdef __clang__ 581 #pragma clang diagnostic push 582 #if __has_warning("-Wzero-as-null-pointer-constant") 583 #pragma clang diagnostic error "-Wzero-as-null-pointer-constant" 584 #endif 585 #endif 586 587 TEST(NullLiteralTest, NoConversionNoWarning) { 588 // Test that gtests detection and handling of null pointer constants 589 // doesn't trigger a warning when '0' isn't actually used as null. 590 EXPECT_EQ(0, 0); 591 ASSERT_EQ(0, 0); 592 } 593 594 #ifdef __clang__ 595 #pragma clang diagnostic pop 596 #endif 597 598 #ifdef __BORLANDC__ 599 // Restores warnings after previous "#pragma option push" suppressed them. 600 #pragma option pop 601 #endif 602 603 // 604 // Tests CodePointToUtf8(). 605 606 // Tests that the NUL character L'\0' is encoded correctly. 607 TEST(CodePointToUtf8Test, CanEncodeNul) { 608 EXPECT_EQ("", CodePointToUtf8(L'\0')); 609 } 610 611 // Tests that ASCII characters are encoded correctly. 612 TEST(CodePointToUtf8Test, CanEncodeAscii) { 613 EXPECT_EQ("a", CodePointToUtf8(L'a')); 614 EXPECT_EQ("Z", CodePointToUtf8(L'Z')); 615 EXPECT_EQ("&", CodePointToUtf8(L'&')); 616 EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F')); 617 } 618 619 // Tests that Unicode code-points that have 8 to 11 bits are encoded 620 // as 110xxxxx 10xxxxxx. 621 TEST(CodePointToUtf8Test, CanEncode8To11Bits) { 622 // 000 1101 0011 => 110-00011 10-010011 623 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3')); 624 625 // 101 0111 0110 => 110-10101 10-110110 626 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints 627 // in wide strings and wide chars. In order to accommodate them, we have to 628 // introduce such character constants as integers. 629 EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576))); 630 } 631 632 // Tests that Unicode code-points that have 12 to 16 bits are encoded 633 // as 1110xxxx 10xxxxxx 10xxxxxx. 634 TEST(CodePointToUtf8Test, CanEncode12To16Bits) { 635 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 636 EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3))); 637 638 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 639 EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D))); 640 } 641 642 #if !GTEST_WIDE_STRING_USES_UTF16_ 643 // Tests in this group require a wchar_t to hold > 16 bits, and thus 644 // are skipped on Windows, and Cygwin, where a wchar_t is 645 // 16-bit wide. This code may not compile on those systems. 646 647 // Tests that Unicode code-points that have 17 to 21 bits are encoded 648 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. 649 TEST(CodePointToUtf8Test, CanEncode17To21Bits) { 650 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 651 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3')); 652 653 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000 654 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400')); 655 656 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 657 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634')); 658 } 659 660 // Tests that encoding an invalid code-point generates the expected result. 661 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) { 662 EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD')); 663 } 664 665 #endif // !GTEST_WIDE_STRING_USES_UTF16_ 666 667 // Tests WideStringToUtf8(). 668 669 // Tests that the NUL character L'\0' is encoded correctly. 670 TEST(WideStringToUtf8Test, CanEncodeNul) { 671 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str()); 672 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str()); 673 } 674 675 // Tests that ASCII strings are encoded correctly. 676 TEST(WideStringToUtf8Test, CanEncodeAscii) { 677 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str()); 678 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str()); 679 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str()); 680 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str()); 681 } 682 683 // Tests that Unicode code-points that have 8 to 11 bits are encoded 684 // as 110xxxxx 10xxxxxx. 685 TEST(WideStringToUtf8Test, CanEncode8To11Bits) { 686 // 000 1101 0011 => 110-00011 10-010011 687 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str()); 688 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); 689 690 // 101 0111 0110 => 110-10101 10-110110 691 const wchar_t s[] = {0x576, '\0'}; 692 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); 693 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); 694 } 695 696 // Tests that Unicode code-points that have 12 to 16 bits are encoded 697 // as 1110xxxx 10xxxxxx 10xxxxxx. 698 TEST(WideStringToUtf8Test, CanEncode12To16Bits) { 699 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 700 const wchar_t s1[] = {0x8D3, '\0'}; 701 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); 702 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); 703 704 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 705 const wchar_t s2[] = {0xC74D, '\0'}; 706 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); 707 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); 708 } 709 710 // Tests that the conversion stops when the function encounters \0 character. 711 TEST(WideStringToUtf8Test, StopsOnNulCharacter) { 712 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str()); 713 } 714 715 // Tests that the conversion stops when the function reaches the limit 716 // specified by the 'length' parameter. 717 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) { 718 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str()); 719 } 720 721 #if !GTEST_WIDE_STRING_USES_UTF16_ 722 // Tests that Unicode code-points that have 17 to 21 bits are encoded 723 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile 724 // on the systems using UTF-16 encoding. 725 TEST(WideStringToUtf8Test, CanEncode17To21Bits) { 726 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 727 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str()); 728 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str()); 729 730 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 731 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str()); 732 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str()); 733 } 734 735 // Tests that encoding an invalid code-point generates the expected result. 736 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { 737 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", 738 WideStringToUtf8(L"\xABCDFF", -1).c_str()); 739 } 740 #else // !GTEST_WIDE_STRING_USES_UTF16_ 741 // Tests that surrogate pairs are encoded correctly on the systems using 742 // UTF-16 encoding in the wide strings. 743 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { 744 const wchar_t s[] = {0xD801, 0xDC00, '\0'}; 745 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); 746 } 747 748 // Tests that encoding an invalid UTF-16 surrogate pair 749 // generates the expected result. 750 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { 751 // Leading surrogate is at the end of the string. 752 const wchar_t s1[] = {0xD800, '\0'}; 753 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); 754 // Leading surrogate is not followed by the trailing surrogate. 755 const wchar_t s2[] = {0xD800, 'M', '\0'}; 756 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); 757 // Trailing surrogate appearas without a leading surrogate. 758 const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'}; 759 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); 760 } 761 #endif // !GTEST_WIDE_STRING_USES_UTF16_ 762 763 // Tests that codepoint concatenation works correctly. 764 #if !GTEST_WIDE_STRING_USES_UTF16_ 765 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { 766 const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; 767 EXPECT_STREQ( 768 "\xF4\x88\x98\xB4" 769 "\xEC\x9D\x8D" 770 "\n" 771 "\xD5\xB6" 772 "\xE0\xA3\x93" 773 "\xF4\x88\x98\xB4", 774 WideStringToUtf8(s, -1).c_str()); 775 } 776 #else 777 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { 778 const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'}; 779 EXPECT_STREQ( 780 "\xEC\x9D\x8D" 781 "\n" 782 "\xD5\xB6" 783 "\xE0\xA3\x93", 784 WideStringToUtf8(s, -1).c_str()); 785 } 786 #endif // !GTEST_WIDE_STRING_USES_UTF16_ 787 788 // Tests the Random class. 789 790 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { 791 testing::internal::Random random(42); 792 EXPECT_DEATH_IF_SUPPORTED(random.Generate(0), 793 "Cannot generate a number in the range \\[0, 0\\)"); 794 EXPECT_DEATH_IF_SUPPORTED( 795 random.Generate(testing::internal::Random::kMaxRange + 1), 796 "Generation of a number in \\[0, 2147483649\\) was requested, " 797 "but this can only generate numbers in \\[0, 2147483648\\)"); 798 } 799 800 TEST(RandomTest, GeneratesNumbersWithinRange) { 801 constexpr uint32_t kRange = 10000; 802 testing::internal::Random random(12345); 803 for (int i = 0; i < 10; i++) { 804 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i; 805 } 806 807 testing::internal::Random random2(testing::internal::Random::kMaxRange); 808 for (int i = 0; i < 10; i++) { 809 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i; 810 } 811 } 812 813 TEST(RandomTest, RepeatsWhenReseeded) { 814 constexpr int kSeed = 123; 815 constexpr int kArraySize = 10; 816 constexpr uint32_t kRange = 10000; 817 uint32_t values[kArraySize]; 818 819 testing::internal::Random random(kSeed); 820 for (int i = 0; i < kArraySize; i++) { 821 values[i] = random.Generate(kRange); 822 } 823 824 random.Reseed(kSeed); 825 for (int i = 0; i < kArraySize; i++) { 826 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i; 827 } 828 } 829 830 // Tests STL container utilities. 831 832 // Tests CountIf(). 833 834 static bool IsPositive(int n) { return n > 0; } 835 836 TEST(ContainerUtilityTest, CountIf) { 837 std::vector<int> v; 838 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container. 839 840 v.push_back(-1); 841 v.push_back(0); 842 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies. 843 844 v.push_back(2); 845 v.push_back(-10); 846 v.push_back(10); 847 EXPECT_EQ(2, CountIf(v, IsPositive)); 848 } 849 850 // Tests ForEach(). 851 852 static int g_sum = 0; 853 static void Accumulate(int n) { g_sum += n; } 854 855 TEST(ContainerUtilityTest, ForEach) { 856 std::vector<int> v; 857 g_sum = 0; 858 ForEach(v, Accumulate); 859 EXPECT_EQ(0, g_sum); // Works for an empty container; 860 861 g_sum = 0; 862 v.push_back(1); 863 ForEach(v, Accumulate); 864 EXPECT_EQ(1, g_sum); // Works for a container with one element. 865 866 g_sum = 0; 867 v.push_back(20); 868 v.push_back(300); 869 ForEach(v, Accumulate); 870 EXPECT_EQ(321, g_sum); 871 } 872 873 // Tests GetElementOr(). 874 TEST(ContainerUtilityTest, GetElementOr) { 875 std::vector<char> a; 876 EXPECT_EQ('x', GetElementOr(a, 0, 'x')); 877 878 a.push_back('a'); 879 a.push_back('b'); 880 EXPECT_EQ('a', GetElementOr(a, 0, 'x')); 881 EXPECT_EQ('b', GetElementOr(a, 1, 'x')); 882 EXPECT_EQ('x', GetElementOr(a, -2, 'x')); 883 EXPECT_EQ('x', GetElementOr(a, 2, 'x')); 884 } 885 886 TEST(ContainerUtilityDeathTest, ShuffleRange) { 887 std::vector<int> a; 888 a.push_back(0); 889 a.push_back(1); 890 a.push_back(2); 891 testing::internal::Random random(1); 892 893 EXPECT_DEATH_IF_SUPPORTED( 894 ShuffleRange(&random, -1, 1, &a), 895 "Invalid shuffle range start -1: must be in range \\[0, 3\\]"); 896 EXPECT_DEATH_IF_SUPPORTED( 897 ShuffleRange(&random, 4, 4, &a), 898 "Invalid shuffle range start 4: must be in range \\[0, 3\\]"); 899 EXPECT_DEATH_IF_SUPPORTED( 900 ShuffleRange(&random, 3, 2, &a), 901 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]"); 902 EXPECT_DEATH_IF_SUPPORTED( 903 ShuffleRange(&random, 3, 4, &a), 904 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]"); 905 } 906 907 class VectorShuffleTest : public Test { 908 protected: 909 static const size_t kVectorSize = 20; 910 911 VectorShuffleTest() : random_(1) { 912 for (int i = 0; i < static_cast<int>(kVectorSize); i++) { 913 vector_.push_back(i); 914 } 915 } 916 917 static bool VectorIsCorrupt(const TestingVector& vector) { 918 if (kVectorSize != vector.size()) { 919 return true; 920 } 921 922 bool found_in_vector[kVectorSize] = {false}; 923 for (size_t i = 0; i < vector.size(); i++) { 924 const int e = vector[i]; 925 if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) { 926 return true; 927 } 928 found_in_vector[e] = true; 929 } 930 931 // Vector size is correct, elements' range is correct, no 932 // duplicate elements. Therefore no corruption has occurred. 933 return false; 934 } 935 936 static bool VectorIsNotCorrupt(const TestingVector& vector) { 937 return !VectorIsCorrupt(vector); 938 } 939 940 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) { 941 for (int i = begin; i < end; i++) { 942 if (i != vector[static_cast<size_t>(i)]) { 943 return true; 944 } 945 } 946 return false; 947 } 948 949 static bool RangeIsUnshuffled(const TestingVector& vector, int begin, 950 int end) { 951 return !RangeIsShuffled(vector, begin, end); 952 } 953 954 static bool VectorIsShuffled(const TestingVector& vector) { 955 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size())); 956 } 957 958 static bool VectorIsUnshuffled(const TestingVector& vector) { 959 return !VectorIsShuffled(vector); 960 } 961 962 testing::internal::Random random_; 963 TestingVector vector_; 964 }; // class VectorShuffleTest 965 966 const size_t VectorShuffleTest::kVectorSize; 967 968 TEST_F(VectorShuffleTest, HandlesEmptyRange) { 969 // Tests an empty range at the beginning... 970 ShuffleRange(&random_, 0, 0, &vector_); 971 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 972 ASSERT_PRED1(VectorIsUnshuffled, vector_); 973 974 // ...in the middle... 975 ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2, &vector_); 976 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 977 ASSERT_PRED1(VectorIsUnshuffled, vector_); 978 979 // ...at the end... 980 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_); 981 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 982 ASSERT_PRED1(VectorIsUnshuffled, vector_); 983 984 // ...and past the end. 985 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_); 986 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 987 ASSERT_PRED1(VectorIsUnshuffled, vector_); 988 } 989 990 TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) { 991 // Tests a size one range at the beginning... 992 ShuffleRange(&random_, 0, 1, &vector_); 993 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 994 ASSERT_PRED1(VectorIsUnshuffled, vector_); 995 996 // ...in the middle... 997 ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_); 998 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 999 ASSERT_PRED1(VectorIsUnshuffled, vector_); 1000 1001 // ...and at the end. 1002 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_); 1003 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 1004 ASSERT_PRED1(VectorIsUnshuffled, vector_); 1005 } 1006 1007 // Because we use our own random number generator and a fixed seed, 1008 // we can guarantee that the following "random" tests will succeed. 1009 1010 TEST_F(VectorShuffleTest, ShufflesEntireVector) { 1011 Shuffle(&random_, &vector_); 1012 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 1013 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_; 1014 1015 // Tests the first and last elements in particular to ensure that 1016 // there are no off-by-one problems in our shuffle algorithm. 1017 EXPECT_NE(0, vector_[0]); 1018 EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]); 1019 } 1020 1021 TEST_F(VectorShuffleTest, ShufflesStartOfVector) { 1022 const int kRangeSize = kVectorSize / 2; 1023 1024 ShuffleRange(&random_, 0, kRangeSize, &vector_); 1025 1026 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 1027 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize); 1028 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, 1029 static_cast<int>(kVectorSize)); 1030 } 1031 1032 TEST_F(VectorShuffleTest, ShufflesEndOfVector) { 1033 const int kRangeSize = kVectorSize / 2; 1034 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_); 1035 1036 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 1037 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); 1038 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 1039 static_cast<int>(kVectorSize)); 1040 } 1041 1042 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) { 1043 const int kRangeSize = static_cast<int>(kVectorSize) / 3; 1044 ShuffleRange(&random_, kRangeSize, 2 * kRangeSize, &vector_); 1045 1046 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 1047 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); 1048 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2 * kRangeSize); 1049 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize, 1050 static_cast<int>(kVectorSize)); 1051 } 1052 1053 TEST_F(VectorShuffleTest, ShufflesRepeatably) { 1054 TestingVector vector2; 1055 for (size_t i = 0; i < kVectorSize; i++) { 1056 vector2.push_back(static_cast<int>(i)); 1057 } 1058 1059 random_.Reseed(1234); 1060 Shuffle(&random_, &vector_); 1061 random_.Reseed(1234); 1062 Shuffle(&random_, &vector2); 1063 1064 ASSERT_PRED1(VectorIsNotCorrupt, vector_); 1065 ASSERT_PRED1(VectorIsNotCorrupt, vector2); 1066 1067 for (size_t i = 0; i < kVectorSize; i++) { 1068 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i; 1069 } 1070 } 1071 1072 // Tests the size of the AssertHelper class. 1073 1074 TEST(AssertHelperTest, AssertHelperIsSmall) { 1075 // To avoid breaking clients that use lots of assertions in one 1076 // function, we cannot grow the size of AssertHelper. 1077 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*)); 1078 } 1079 1080 // Tests String::EndsWithCaseInsensitive(). 1081 TEST(StringTest, EndsWithCaseInsensitive) { 1082 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR")); 1083 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar")); 1084 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "")); 1085 EXPECT_TRUE(String::EndsWithCaseInsensitive("", "")); 1086 1087 EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo")); 1088 EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo")); 1089 EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo")); 1090 } 1091 1092 // C++Builder's preprocessor is buggy; it fails to expand macros that 1093 // appear in macro parameters after wide char literals. Provide an alias 1094 // for NULL as a workaround. 1095 static const wchar_t* const kNull = nullptr; 1096 1097 // Tests String::CaseInsensitiveWideCStringEquals 1098 TEST(StringTest, CaseInsensitiveWideCStringEquals) { 1099 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr)); 1100 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"")); 1101 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull)); 1102 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar")); 1103 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull)); 1104 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar")); 1105 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR")); 1106 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar")); 1107 } 1108 1109 #ifdef GTEST_OS_WINDOWS 1110 1111 // Tests String::ShowWideCString(). 1112 TEST(StringTest, ShowWideCString) { 1113 EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str()); 1114 EXPECT_STREQ("", String::ShowWideCString(L"").c_str()); 1115 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str()); 1116 } 1117 1118 #ifdef GTEST_OS_WINDOWS_MOBILE 1119 TEST(StringTest, AnsiAndUtf16Null) { 1120 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL)); 1121 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL)); 1122 } 1123 1124 TEST(StringTest, AnsiAndUtf16ConvertBasic) { 1125 const char* ansi = String::Utf16ToAnsi(L"str"); 1126 EXPECT_STREQ("str", ansi); 1127 delete[] ansi; 1128 const WCHAR* utf16 = String::AnsiToUtf16("str"); 1129 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3)); 1130 delete[] utf16; 1131 } 1132 1133 TEST(StringTest, AnsiAndUtf16ConvertPathChars) { 1134 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?"); 1135 EXPECT_STREQ(".:\\ \"*?", ansi); 1136 delete[] ansi; 1137 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?"); 1138 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3)); 1139 delete[] utf16; 1140 } 1141 #endif // GTEST_OS_WINDOWS_MOBILE 1142 1143 #endif // GTEST_OS_WINDOWS 1144 1145 // Tests TestProperty construction. 1146 TEST(TestPropertyTest, StringValue) { 1147 TestProperty property("key", "1"); 1148 EXPECT_STREQ("key", property.key()); 1149 EXPECT_STREQ("1", property.value()); 1150 } 1151 1152 // Tests TestProperty replacing a value. 1153 TEST(TestPropertyTest, ReplaceStringValue) { 1154 TestProperty property("key", "1"); 1155 EXPECT_STREQ("1", property.value()); 1156 property.SetValue("2"); 1157 EXPECT_STREQ("2", property.value()); 1158 } 1159 1160 // AddFatalFailure() and AddNonfatalFailure() must be stand-alone 1161 // functions (i.e. their definitions cannot be inlined at the call 1162 // sites), or C++Builder won't compile the code. 1163 static void AddFatalFailure() { FAIL() << "Expected fatal failure."; } 1164 1165 static void AddNonfatalFailure() { 1166 ADD_FAILURE() << "Expected non-fatal failure."; 1167 } 1168 1169 class ScopedFakeTestPartResultReporterTest : public Test { 1170 public: // Must be public and not protected due to a bug in g++ 3.4.2. 1171 enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE }; 1172 static void AddFailure(FailureMode failure) { 1173 if (failure == FATAL_FAILURE) { 1174 AddFatalFailure(); 1175 } else { 1176 AddNonfatalFailure(); 1177 } 1178 } 1179 }; 1180 1181 // Tests that ScopedFakeTestPartResultReporter intercepts test 1182 // failures. 1183 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) { 1184 TestPartResultArray results; 1185 { 1186 ScopedFakeTestPartResultReporter reporter( 1187 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, 1188 &results); 1189 AddFailure(NONFATAL_FAILURE); 1190 AddFailure(FATAL_FAILURE); 1191 } 1192 1193 EXPECT_EQ(2, results.size()); 1194 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); 1195 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); 1196 } 1197 1198 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) { 1199 TestPartResultArray results; 1200 { 1201 // Tests, that the deprecated constructor still works. 1202 ScopedFakeTestPartResultReporter reporter(&results); 1203 AddFailure(NONFATAL_FAILURE); 1204 } 1205 EXPECT_EQ(1, results.size()); 1206 } 1207 1208 #ifdef GTEST_IS_THREADSAFE 1209 1210 class ScopedFakeTestPartResultReporterWithThreadsTest 1211 : public ScopedFakeTestPartResultReporterTest { 1212 protected: 1213 static void AddFailureInOtherThread(FailureMode failure) { 1214 ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr); 1215 thread.Join(); 1216 } 1217 }; 1218 1219 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest, 1220 InterceptsTestFailuresInAllThreads) { 1221 TestPartResultArray results; 1222 { 1223 ScopedFakeTestPartResultReporter reporter( 1224 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results); 1225 AddFailure(NONFATAL_FAILURE); 1226 AddFailure(FATAL_FAILURE); 1227 AddFailureInOtherThread(NONFATAL_FAILURE); 1228 AddFailureInOtherThread(FATAL_FAILURE); 1229 } 1230 1231 EXPECT_EQ(4, results.size()); 1232 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); 1233 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); 1234 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed()); 1235 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed()); 1236 } 1237 1238 #endif // GTEST_IS_THREADSAFE 1239 1240 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they 1241 // work even if the failure is generated in a called function rather than 1242 // the current context. 1243 1244 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest; 1245 1246 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) { 1247 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure."); 1248 } 1249 1250 TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) { 1251 EXPECT_FATAL_FAILURE(AddFatalFailure(), 1252 ::std::string("Expected fatal failure.")); 1253 } 1254 1255 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) { 1256 // We have another test below to verify that the macro catches fatal 1257 // failures generated on another thread. 1258 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(), 1259 "Expected fatal failure."); 1260 } 1261 1262 #ifdef __BORLANDC__ 1263 // Silences warnings: "Condition is always true" 1264 #pragma option push -w-ccc 1265 #endif 1266 1267 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void 1268 // function even when the statement in it contains ASSERT_*. 1269 1270 int NonVoidFunction() { 1271 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); 1272 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); 1273 return 0; 1274 } 1275 1276 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) { 1277 NonVoidFunction(); 1278 } 1279 1280 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the 1281 // current function even though 'statement' generates a fatal failure. 1282 1283 void DoesNotAbortHelper(bool* aborted) { 1284 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); 1285 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); 1286 1287 *aborted = false; 1288 } 1289 1290 #ifdef __BORLANDC__ 1291 // Restores warnings after previous "#pragma option push" suppressed them. 1292 #pragma option pop 1293 #endif 1294 1295 TEST_F(ExpectFatalFailureTest, DoesNotAbort) { 1296 bool aborted = true; 1297 DoesNotAbortHelper(&aborted); 1298 EXPECT_FALSE(aborted); 1299 } 1300 1301 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a 1302 // statement that contains a macro which expands to code containing an 1303 // unprotected comma. 1304 1305 static int global_var = 0; 1306 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++ 1307 1308 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { 1309 #ifndef __BORLANDC__ 1310 // ICE's in C++Builder. 1311 EXPECT_FATAL_FAILURE( 1312 { 1313 GTEST_USE_UNPROTECTED_COMMA_; 1314 AddFatalFailure(); 1315 }, 1316 ""); 1317 #endif 1318 1319 EXPECT_FATAL_FAILURE_ON_ALL_THREADS( 1320 { 1321 GTEST_USE_UNPROTECTED_COMMA_; 1322 AddFatalFailure(); 1323 }, 1324 ""); 1325 } 1326 1327 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}. 1328 1329 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest; 1330 1331 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { 1332 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure."); 1333 } 1334 1335 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) { 1336 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), 1337 ::std::string("Expected non-fatal failure.")); 1338 } 1339 1340 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { 1341 // We have another test below to verify that the macro catches 1342 // non-fatal failures generated on another thread. 1343 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(), 1344 "Expected non-fatal failure."); 1345 } 1346 1347 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a 1348 // statement that contains a macro which expands to code containing an 1349 // unprotected comma. 1350 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { 1351 EXPECT_NONFATAL_FAILURE( 1352 { 1353 GTEST_USE_UNPROTECTED_COMMA_; 1354 AddNonfatalFailure(); 1355 }, 1356 ""); 1357 1358 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( 1359 { 1360 GTEST_USE_UNPROTECTED_COMMA_; 1361 AddNonfatalFailure(); 1362 }, 1363 ""); 1364 } 1365 1366 #ifdef GTEST_IS_THREADSAFE 1367 1368 typedef ScopedFakeTestPartResultReporterWithThreadsTest 1369 ExpectFailureWithThreadsTest; 1370 1371 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) { 1372 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE), 1373 "Expected fatal failure."); 1374 } 1375 1376 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) { 1377 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( 1378 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure."); 1379 } 1380 1381 #endif // GTEST_IS_THREADSAFE 1382 1383 // Tests the TestProperty class. 1384 1385 TEST(TestPropertyTest, ConstructorWorks) { 1386 const TestProperty property("key", "value"); 1387 EXPECT_STREQ("key", property.key()); 1388 EXPECT_STREQ("value", property.value()); 1389 } 1390 1391 TEST(TestPropertyTest, SetValue) { 1392 TestProperty property("key", "value_1"); 1393 EXPECT_STREQ("key", property.key()); 1394 property.SetValue("value_2"); 1395 EXPECT_STREQ("key", property.key()); 1396 EXPECT_STREQ("value_2", property.value()); 1397 } 1398 1399 // Tests the TestResult class 1400 1401 // The test fixture for testing TestResult. 1402 class TestResultTest : public Test { 1403 protected: 1404 typedef std::vector<TestPartResult> TPRVector; 1405 1406 // We make use of 2 TestPartResult objects, 1407 TestPartResult *pr1, *pr2; 1408 1409 // ... and 3 TestResult objects. 1410 TestResult *r0, *r1, *r2; 1411 1412 void SetUp() override { 1413 // pr1 is for success. 1414 pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10, 1415 "Success!"); 1416 1417 // pr2 is for fatal failure. 1418 pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc", 1419 -1, // This line number means "unknown" 1420 "Failure!"); 1421 1422 // Creates the TestResult objects. 1423 r0 = new TestResult(); 1424 r1 = new TestResult(); 1425 r2 = new TestResult(); 1426 1427 // In order to test TestResult, we need to modify its internal 1428 // state, in particular the TestPartResult vector it holds. 1429 // test_part_results() returns a const reference to this vector. 1430 // We cast it to a non-const object s.t. it can be modified 1431 TPRVector* results1 = 1432 const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r1)); 1433 TPRVector* results2 = 1434 const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r2)); 1435 1436 // r0 is an empty TestResult. 1437 1438 // r1 contains a single SUCCESS TestPartResult. 1439 results1->push_back(*pr1); 1440 1441 // r2 contains a SUCCESS, and a FAILURE. 1442 results2->push_back(*pr1); 1443 results2->push_back(*pr2); 1444 } 1445 1446 void TearDown() override { 1447 delete pr1; 1448 delete pr2; 1449 1450 delete r0; 1451 delete r1; 1452 delete r2; 1453 } 1454 1455 // Helper that compares two TestPartResults. 1456 static void CompareTestPartResult(const TestPartResult& expected, 1457 const TestPartResult& actual) { 1458 EXPECT_EQ(expected.type(), actual.type()); 1459 EXPECT_STREQ(expected.file_name(), actual.file_name()); 1460 EXPECT_EQ(expected.line_number(), actual.line_number()); 1461 EXPECT_STREQ(expected.summary(), actual.summary()); 1462 EXPECT_STREQ(expected.message(), actual.message()); 1463 EXPECT_EQ(expected.passed(), actual.passed()); 1464 EXPECT_EQ(expected.failed(), actual.failed()); 1465 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed()); 1466 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed()); 1467 } 1468 }; 1469 1470 // Tests TestResult::total_part_count(). 1471 TEST_F(TestResultTest, total_part_count) { 1472 ASSERT_EQ(0, r0->total_part_count()); 1473 ASSERT_EQ(1, r1->total_part_count()); 1474 ASSERT_EQ(2, r2->total_part_count()); 1475 } 1476 1477 // Tests TestResult::Passed(). 1478 TEST_F(TestResultTest, Passed) { 1479 ASSERT_TRUE(r0->Passed()); 1480 ASSERT_TRUE(r1->Passed()); 1481 ASSERT_FALSE(r2->Passed()); 1482 } 1483 1484 // Tests TestResult::Failed(). 1485 TEST_F(TestResultTest, Failed) { 1486 ASSERT_FALSE(r0->Failed()); 1487 ASSERT_FALSE(r1->Failed()); 1488 ASSERT_TRUE(r2->Failed()); 1489 } 1490 1491 // Tests TestResult::GetTestPartResult(). 1492 1493 typedef TestResultTest TestResultDeathTest; 1494 1495 TEST_F(TestResultDeathTest, GetTestPartResult) { 1496 CompareTestPartResult(*pr1, r2->GetTestPartResult(0)); 1497 CompareTestPartResult(*pr2, r2->GetTestPartResult(1)); 1498 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), ""); 1499 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), ""); 1500 } 1501 1502 // Tests TestResult has no properties when none are added. 1503 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) { 1504 TestResult test_result; 1505 ASSERT_EQ(0, test_result.test_property_count()); 1506 } 1507 1508 // Tests TestResult has the expected property when added. 1509 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) { 1510 TestResult test_result; 1511 TestProperty property("key_1", "1"); 1512 TestResultAccessor::RecordProperty(&test_result, "testcase", property); 1513 ASSERT_EQ(1, test_result.test_property_count()); 1514 const TestProperty& actual_property = test_result.GetTestProperty(0); 1515 EXPECT_STREQ("key_1", actual_property.key()); 1516 EXPECT_STREQ("1", actual_property.value()); 1517 } 1518 1519 // Tests TestResult has multiple properties when added. 1520 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) { 1521 TestResult test_result; 1522 TestProperty property_1("key_1", "1"); 1523 TestProperty property_2("key_2", "2"); 1524 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1); 1525 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2); 1526 ASSERT_EQ(2, test_result.test_property_count()); 1527 const TestProperty& actual_property_1 = test_result.GetTestProperty(0); 1528 EXPECT_STREQ("key_1", actual_property_1.key()); 1529 EXPECT_STREQ("1", actual_property_1.value()); 1530 1531 const TestProperty& actual_property_2 = test_result.GetTestProperty(1); 1532 EXPECT_STREQ("key_2", actual_property_2.key()); 1533 EXPECT_STREQ("2", actual_property_2.value()); 1534 } 1535 1536 // Tests TestResult::RecordProperty() overrides values for duplicate keys. 1537 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) { 1538 TestResult test_result; 1539 TestProperty property_1_1("key_1", "1"); 1540 TestProperty property_2_1("key_2", "2"); 1541 TestProperty property_1_2("key_1", "12"); 1542 TestProperty property_2_2("key_2", "22"); 1543 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1); 1544 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1); 1545 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2); 1546 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2); 1547 1548 ASSERT_EQ(2, test_result.test_property_count()); 1549 const TestProperty& actual_property_1 = test_result.GetTestProperty(0); 1550 EXPECT_STREQ("key_1", actual_property_1.key()); 1551 EXPECT_STREQ("12", actual_property_1.value()); 1552 1553 const TestProperty& actual_property_2 = test_result.GetTestProperty(1); 1554 EXPECT_STREQ("key_2", actual_property_2.key()); 1555 EXPECT_STREQ("22", actual_property_2.value()); 1556 } 1557 1558 // Tests TestResult::GetTestProperty(). 1559 TEST(TestResultPropertyTest, GetTestProperty) { 1560 TestResult test_result; 1561 TestProperty property_1("key_1", "1"); 1562 TestProperty property_2("key_2", "2"); 1563 TestProperty property_3("key_3", "3"); 1564 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1); 1565 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2); 1566 TestResultAccessor::RecordProperty(&test_result, "testcase", property_3); 1567 1568 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0); 1569 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1); 1570 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2); 1571 1572 EXPECT_STREQ("key_1", fetched_property_1.key()); 1573 EXPECT_STREQ("1", fetched_property_1.value()); 1574 1575 EXPECT_STREQ("key_2", fetched_property_2.key()); 1576 EXPECT_STREQ("2", fetched_property_2.value()); 1577 1578 EXPECT_STREQ("key_3", fetched_property_3.key()); 1579 EXPECT_STREQ("3", fetched_property_3.value()); 1580 1581 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), ""); 1582 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), ""); 1583 } 1584 1585 // Tests the Test class. 1586 // 1587 // It's difficult to test every public method of this class (we are 1588 // already stretching the limit of Google Test by using it to test itself!). 1589 // Fortunately, we don't have to do that, as we are already testing 1590 // the functionalities of the Test class extensively by using Google Test 1591 // alone. 1592 // 1593 // Therefore, this section only contains one test. 1594 1595 // Tests that GTestFlagSaver works on Windows and Mac. 1596 1597 class GTestFlagSaverTest : public Test { 1598 protected: 1599 // Saves the Google Test flags such that we can restore them later, and 1600 // then sets them to their default values. This will be called 1601 // before the first test in this test case is run. 1602 static void SetUpTestSuite() { 1603 saver_ = new GTestFlagSaver; 1604 1605 GTEST_FLAG_SET(also_run_disabled_tests, false); 1606 GTEST_FLAG_SET(break_on_failure, false); 1607 GTEST_FLAG_SET(catch_exceptions, false); 1608 GTEST_FLAG_SET(death_test_use_fork, false); 1609 GTEST_FLAG_SET(color, "auto"); 1610 GTEST_FLAG_SET(fail_fast, false); 1611 GTEST_FLAG_SET(filter, ""); 1612 GTEST_FLAG_SET(list_tests, false); 1613 GTEST_FLAG_SET(output, ""); 1614 GTEST_FLAG_SET(brief, false); 1615 GTEST_FLAG_SET(print_time, true); 1616 GTEST_FLAG_SET(random_seed, 0); 1617 GTEST_FLAG_SET(repeat, 1); 1618 GTEST_FLAG_SET(recreate_environments_when_repeating, true); 1619 GTEST_FLAG_SET(shuffle, false); 1620 GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth); 1621 GTEST_FLAG_SET(stream_result_to, ""); 1622 GTEST_FLAG_SET(throw_on_failure, false); 1623 } 1624 1625 // Restores the Google Test flags that the tests have modified. This will 1626 // be called after the last test in this test case is run. 1627 static void TearDownTestSuite() { 1628 delete saver_; 1629 saver_ = nullptr; 1630 } 1631 1632 // Verifies that the Google Test flags have their default values, and then 1633 // modifies each of them. 1634 void VerifyAndModifyFlags() { 1635 EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests)); 1636 EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure)); 1637 EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions)); 1638 EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str()); 1639 EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork)); 1640 EXPECT_FALSE(GTEST_FLAG_GET(fail_fast)); 1641 EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str()); 1642 EXPECT_FALSE(GTEST_FLAG_GET(list_tests)); 1643 EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str()); 1644 EXPECT_FALSE(GTEST_FLAG_GET(brief)); 1645 EXPECT_TRUE(GTEST_FLAG_GET(print_time)); 1646 EXPECT_EQ(0, GTEST_FLAG_GET(random_seed)); 1647 EXPECT_EQ(1, GTEST_FLAG_GET(repeat)); 1648 EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating)); 1649 EXPECT_FALSE(GTEST_FLAG_GET(shuffle)); 1650 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth)); 1651 EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str()); 1652 EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure)); 1653 1654 GTEST_FLAG_SET(also_run_disabled_tests, true); 1655 GTEST_FLAG_SET(break_on_failure, true); 1656 GTEST_FLAG_SET(catch_exceptions, true); 1657 GTEST_FLAG_SET(color, "no"); 1658 GTEST_FLAG_SET(death_test_use_fork, true); 1659 GTEST_FLAG_SET(fail_fast, true); 1660 GTEST_FLAG_SET(filter, "abc"); 1661 GTEST_FLAG_SET(list_tests, true); 1662 GTEST_FLAG_SET(output, "xml:foo.xml"); 1663 GTEST_FLAG_SET(brief, true); 1664 GTEST_FLAG_SET(print_time, false); 1665 GTEST_FLAG_SET(random_seed, 1); 1666 GTEST_FLAG_SET(repeat, 100); 1667 GTEST_FLAG_SET(recreate_environments_when_repeating, false); 1668 GTEST_FLAG_SET(shuffle, true); 1669 GTEST_FLAG_SET(stack_trace_depth, 1); 1670 GTEST_FLAG_SET(stream_result_to, "localhost:1234"); 1671 GTEST_FLAG_SET(throw_on_failure, true); 1672 } 1673 1674 private: 1675 // For saving Google Test flags during this test case. 1676 static GTestFlagSaver* saver_; 1677 }; 1678 1679 GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr; 1680 1681 // Google Test doesn't guarantee the order of tests. The following two 1682 // tests are designed to work regardless of their order. 1683 1684 // Modifies the Google Test flags in the test body. 1685 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); } 1686 1687 // Verifies that the Google Test flags in the body of the previous test were 1688 // restored to their original values. 1689 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); } 1690 1691 // Sets an environment variable with the given name to the given 1692 // value. If the value argument is "", unsets the environment 1693 // variable. The caller must ensure that both arguments are not NULL. 1694 static void SetEnv(const char* name, const char* value) { 1695 #ifdef GTEST_OS_WINDOWS_MOBILE 1696 // Environment variables are not supported on Windows CE. 1697 return; 1698 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) 1699 // C++Builder's putenv only stores a pointer to its parameter; we have to 1700 // ensure that the string remains valid as long as it might be needed. 1701 // We use an std::map to do so. 1702 static std::map<std::string, std::string*> added_env; 1703 1704 // Because putenv stores a pointer to the string buffer, we can't delete the 1705 // previous string (if present) until after it's replaced. 1706 std::string* prev_env = NULL; 1707 if (added_env.find(name) != added_env.end()) { 1708 prev_env = added_env[name]; 1709 } 1710 added_env[name] = 1711 new std::string((Message() << name << "=" << value).GetString()); 1712 1713 // The standard signature of putenv accepts a 'char*' argument. Other 1714 // implementations, like C++Builder's, accept a 'const char*'. 1715 // We cast away the 'const' since that would work for both variants. 1716 putenv(const_cast<char*>(added_env[name]->c_str())); 1717 delete prev_env; 1718 #elif defined(GTEST_OS_WINDOWS) // If we are on Windows proper. 1719 _putenv((Message() << name << "=" << value).GetString().c_str()); 1720 #else 1721 if (*value == '\0') { 1722 unsetenv(name); 1723 } else { 1724 setenv(name, value, 1); 1725 } 1726 #endif // GTEST_OS_WINDOWS_MOBILE 1727 } 1728 1729 #ifndef GTEST_OS_WINDOWS_MOBILE 1730 // Environment variables are not supported on Windows CE. 1731 1732 using testing::internal::Int32FromGTestEnv; 1733 1734 // Tests Int32FromGTestEnv(). 1735 1736 // Tests that Int32FromGTestEnv() returns the default value when the 1737 // environment variable is not set. 1738 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) { 1739 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", ""); 1740 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10)); 1741 } 1742 1743 #if !defined(GTEST_GET_INT32_FROM_ENV_) 1744 1745 // Tests that Int32FromGTestEnv() returns the default value when the 1746 // environment variable overflows as an Int32. 1747 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) { 1748 printf("(expecting 2 warnings)\n"); 1749 1750 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321"); 1751 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20)); 1752 1753 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321"); 1754 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30)); 1755 } 1756 1757 // Tests that Int32FromGTestEnv() returns the default value when the 1758 // environment variable does not represent a valid decimal integer. 1759 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) { 1760 printf("(expecting 2 warnings)\n"); 1761 1762 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1"); 1763 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40)); 1764 1765 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X"); 1766 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50)); 1767 } 1768 1769 #endif // !defined(GTEST_GET_INT32_FROM_ENV_) 1770 1771 // Tests that Int32FromGTestEnv() parses and returns the value of the 1772 // environment variable when it represents a valid decimal integer in 1773 // the range of an Int32. 1774 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) { 1775 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123"); 1776 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0)); 1777 1778 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321"); 1779 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0)); 1780 } 1781 #endif // !GTEST_OS_WINDOWS_MOBILE 1782 1783 // Tests ParseFlag(). 1784 1785 // Tests that ParseInt32Flag() returns false and doesn't change the 1786 // output value when the flag has wrong format 1787 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { 1788 int32_t value = 123; 1789 EXPECT_FALSE(ParseFlag("--a=100", "b", &value)); 1790 EXPECT_EQ(123, value); 1791 1792 EXPECT_FALSE(ParseFlag("a=100", "a", &value)); 1793 EXPECT_EQ(123, value); 1794 } 1795 1796 // Tests that ParseFlag() returns false and doesn't change the 1797 // output value when the flag overflows as an Int32. 1798 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { 1799 printf("(expecting 2 warnings)\n"); 1800 1801 int32_t value = 123; 1802 EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value)); 1803 EXPECT_EQ(123, value); 1804 1805 EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value)); 1806 EXPECT_EQ(123, value); 1807 } 1808 1809 // Tests that ParseInt32Flag() returns false and doesn't change the 1810 // output value when the flag does not represent a valid decimal 1811 // integer. 1812 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { 1813 printf("(expecting 2 warnings)\n"); 1814 1815 int32_t value = 123; 1816 EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value)); 1817 EXPECT_EQ(123, value); 1818 1819 EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value)); 1820 EXPECT_EQ(123, value); 1821 } 1822 1823 // Tests that ParseInt32Flag() parses the value of the flag and 1824 // returns true when the flag represents a valid decimal integer in 1825 // the range of an Int32. 1826 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) { 1827 int32_t value = 123; 1828 EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); 1829 EXPECT_EQ(456, value); 1830 1831 EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value)); 1832 EXPECT_EQ(-789, value); 1833 } 1834 1835 // Tests that Int32FromEnvOrDie() parses the value of the var or 1836 // returns the correct default. 1837 // Environment variables are not supported on Windows CE. 1838 #ifndef GTEST_OS_WINDOWS_MOBILE 1839 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { 1840 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); 1841 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123"); 1842 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); 1843 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123"); 1844 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); 1845 } 1846 #endif // !GTEST_OS_WINDOWS_MOBILE 1847 1848 // Tests that Int32FromEnvOrDie() aborts with an error message 1849 // if the variable is not an int32_t. 1850 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { 1851 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); 1852 EXPECT_DEATH_IF_SUPPORTED( 1853 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); 1854 } 1855 1856 // Tests that Int32FromEnvOrDie() aborts with an error message 1857 // if the variable cannot be represented by an int32_t. 1858 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { 1859 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); 1860 EXPECT_DEATH_IF_SUPPORTED( 1861 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); 1862 } 1863 1864 // Tests that ShouldRunTestOnShard() selects all tests 1865 // where there is 1 shard. 1866 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) { 1867 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0)); 1868 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1)); 1869 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2)); 1870 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3)); 1871 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4)); 1872 } 1873 1874 class ShouldShardTest : public testing::Test { 1875 protected: 1876 void SetUp() override { 1877 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX"; 1878 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL"; 1879 } 1880 1881 void TearDown() override { 1882 SetEnv(index_var_, ""); 1883 SetEnv(total_var_, ""); 1884 } 1885 1886 const char* index_var_; 1887 const char* total_var_; 1888 }; 1889 1890 // Tests that sharding is disabled if neither of the environment variables 1891 // are set. 1892 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) { 1893 SetEnv(index_var_, ""); 1894 SetEnv(total_var_, ""); 1895 1896 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); 1897 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1898 } 1899 1900 // Tests that sharding is not enabled if total_shards == 1. 1901 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) { 1902 SetEnv(index_var_, "0"); 1903 SetEnv(total_var_, "1"); 1904 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); 1905 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1906 } 1907 1908 // Tests that sharding is enabled if total_shards > 1 and 1909 // we are not in a death test subprocess. 1910 // Environment variables are not supported on Windows CE. 1911 #ifndef GTEST_OS_WINDOWS_MOBILE 1912 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) { 1913 SetEnv(index_var_, "4"); 1914 SetEnv(total_var_, "22"); 1915 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); 1916 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1917 1918 SetEnv(index_var_, "8"); 1919 SetEnv(total_var_, "9"); 1920 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); 1921 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1922 1923 SetEnv(index_var_, "0"); 1924 SetEnv(total_var_, "9"); 1925 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); 1926 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1927 } 1928 #endif // !GTEST_OS_WINDOWS_MOBILE 1929 1930 // Tests that we exit in error if the sharding values are not valid. 1931 1932 typedef ShouldShardTest ShouldShardDeathTest; 1933 1934 TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) { 1935 SetEnv(index_var_, "4"); 1936 SetEnv(total_var_, "4"); 1937 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); 1938 1939 SetEnv(index_var_, "4"); 1940 SetEnv(total_var_, "-2"); 1941 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); 1942 1943 SetEnv(index_var_, "5"); 1944 SetEnv(total_var_, ""); 1945 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); 1946 1947 SetEnv(index_var_, ""); 1948 SetEnv(total_var_, "5"); 1949 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); 1950 } 1951 1952 // Tests that ShouldRunTestOnShard is a partition when 5 1953 // shards are used. 1954 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) { 1955 // Choose an arbitrary number of tests and shards. 1956 const int num_tests = 17; 1957 const int num_shards = 5; 1958 1959 // Check partitioning: each test should be on exactly 1 shard. 1960 for (int test_id = 0; test_id < num_tests; test_id++) { 1961 int prev_selected_shard_index = -1; 1962 for (int shard_index = 0; shard_index < num_shards; shard_index++) { 1963 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) { 1964 if (prev_selected_shard_index < 0) { 1965 prev_selected_shard_index = shard_index; 1966 } else { 1967 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and " 1968 << shard_index << " are both selected to run test " 1969 << test_id; 1970 } 1971 } 1972 } 1973 } 1974 1975 // Check balance: This is not required by the sharding protocol, but is a 1976 // desirable property for performance. 1977 for (int shard_index = 0; shard_index < num_shards; shard_index++) { 1978 int num_tests_on_shard = 0; 1979 for (int test_id = 0; test_id < num_tests; test_id++) { 1980 num_tests_on_shard += 1981 ShouldRunTestOnShard(num_shards, shard_index, test_id); 1982 } 1983 EXPECT_GE(num_tests_on_shard, num_tests / num_shards); 1984 } 1985 } 1986 1987 // For the same reason we are not explicitly testing everything in the 1988 // Test class, there are no separate tests for the following classes 1989 // (except for some trivial cases): 1990 // 1991 // TestSuite, UnitTest, UnitTestResultPrinter. 1992 // 1993 // Similarly, there are no separate tests for the following macros: 1994 // 1995 // TEST, TEST_F, RUN_ALL_TESTS 1996 1997 TEST(UnitTestTest, CanGetOriginalWorkingDir) { 1998 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr); 1999 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), ""); 2000 } 2001 2002 TEST(UnitTestTest, ReturnsPlausibleTimestamp) { 2003 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp()); 2004 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis()); 2005 } 2006 2007 // When a property using a reserved key is supplied to this function, it 2008 // tests that a non-fatal failure is added, a fatal failure is not added, 2009 // and that the property is not recorded. 2010 void ExpectNonFatalFailureRecordingPropertyWithReservedKey( 2011 const TestResult& test_result, const char* key) { 2012 EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key"); 2013 ASSERT_EQ(0, test_result.test_property_count()) 2014 << "Property for key '" << key << "' recorded unexpectedly."; 2015 } 2016 2017 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( 2018 const char* key) { 2019 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); 2020 ASSERT_TRUE(test_info != nullptr); 2021 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(), 2022 key); 2023 } 2024 2025 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( 2026 const char* key) { 2027 const testing::TestSuite* test_suite = 2028 UnitTest::GetInstance()->current_test_suite(); 2029 ASSERT_TRUE(test_suite != nullptr); 2030 ExpectNonFatalFailureRecordingPropertyWithReservedKey( 2031 test_suite->ad_hoc_test_result(), key); 2032 } 2033 2034 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( 2035 const char* key) { 2036 ExpectNonFatalFailureRecordingPropertyWithReservedKey( 2037 UnitTest::GetInstance()->ad_hoc_test_result(), key); 2038 } 2039 2040 // Tests that property recording functions in UnitTest outside of tests 2041 // functions correctly. Creating a separate instance of UnitTest ensures it 2042 // is in a state similar to the UnitTest's singleton's between tests. 2043 class UnitTestRecordPropertyTest 2044 : public testing::internal::UnitTestRecordPropertyTestHelper { 2045 public: 2046 static void SetUpTestSuite() { 2047 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( 2048 "disabled"); 2049 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( 2050 "errors"); 2051 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( 2052 "failures"); 2053 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( 2054 "name"); 2055 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( 2056 "tests"); 2057 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( 2058 "time"); 2059 2060 Test::RecordProperty("test_case_key_1", "1"); 2061 2062 const testing::TestSuite* test_suite = 2063 UnitTest::GetInstance()->current_test_suite(); 2064 2065 ASSERT_TRUE(test_suite != nullptr); 2066 2067 ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count()); 2068 EXPECT_STREQ("test_case_key_1", 2069 test_suite->ad_hoc_test_result().GetTestProperty(0).key()); 2070 EXPECT_STREQ("1", 2071 test_suite->ad_hoc_test_result().GetTestProperty(0).value()); 2072 } 2073 }; 2074 2075 // Tests TestResult has the expected property when added. 2076 TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) { 2077 UnitTestRecordProperty("key_1", "1"); 2078 2079 ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count()); 2080 2081 EXPECT_STREQ("key_1", 2082 unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); 2083 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); 2084 } 2085 2086 // Tests TestResult has multiple properties when added. 2087 TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) { 2088 UnitTestRecordProperty("key_1", "1"); 2089 UnitTestRecordProperty("key_2", "2"); 2090 2091 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count()); 2092 2093 EXPECT_STREQ("key_1", 2094 unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); 2095 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); 2096 2097 EXPECT_STREQ("key_2", 2098 unit_test_.ad_hoc_test_result().GetTestProperty(1).key()); 2099 EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value()); 2100 } 2101 2102 // Tests TestResult::RecordProperty() overrides values for duplicate keys. 2103 TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) { 2104 UnitTestRecordProperty("key_1", "1"); 2105 UnitTestRecordProperty("key_2", "2"); 2106 UnitTestRecordProperty("key_1", "12"); 2107 UnitTestRecordProperty("key_2", "22"); 2108 2109 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count()); 2110 2111 EXPECT_STREQ("key_1", 2112 unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); 2113 EXPECT_STREQ("12", 2114 unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); 2115 2116 EXPECT_STREQ("key_2", 2117 unit_test_.ad_hoc_test_result().GetTestProperty(1).key()); 2118 EXPECT_STREQ("22", 2119 unit_test_.ad_hoc_test_result().GetTestProperty(1).value()); 2120 } 2121 2122 TEST_F(UnitTestRecordPropertyTest, 2123 AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) { 2124 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("name"); 2125 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( 2126 "value_param"); 2127 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( 2128 "type_param"); 2129 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("status"); 2130 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("time"); 2131 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( 2132 "classname"); 2133 } 2134 2135 TEST_F(UnitTestRecordPropertyTest, 2136 AddRecordWithReservedKeysGeneratesCorrectPropertyList) { 2137 EXPECT_NONFATAL_FAILURE( 2138 Test::RecordProperty("name", "1"), 2139 "'classname', 'name', 'status', 'time', 'type_param', 'value_param'," 2140 " 'file', and 'line' are reserved"); 2141 } 2142 2143 class UnitTestRecordPropertyTestEnvironment : public Environment { 2144 public: 2145 void TearDown() override { 2146 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( 2147 "tests"); 2148 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( 2149 "failures"); 2150 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( 2151 "disabled"); 2152 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( 2153 "errors"); 2154 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( 2155 "name"); 2156 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( 2157 "timestamp"); 2158 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( 2159 "time"); 2160 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( 2161 "random_seed"); 2162 } 2163 }; 2164 2165 // This will test property recording outside of any test or test case. 2166 GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static Environment* record_property_env = 2167 AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment); 2168 2169 // This group of tests is for predicate assertions (ASSERT_PRED*, etc) 2170 // of various arities. They do not attempt to be exhaustive. Rather, 2171 // view them as smoke tests that can be easily reviewed and verified. 2172 // A more complete set of tests for predicate assertions can be found 2173 // in gtest_pred_impl_unittest.cc. 2174 2175 // First, some predicates and predicate-formatters needed by the tests. 2176 2177 // Returns true if and only if the argument is an even number. 2178 bool IsEven(int n) { return (n % 2) == 0; } 2179 2180 // A functor that returns true if and only if the argument is an even number. 2181 struct IsEvenFunctor { 2182 bool operator()(int n) { return IsEven(n); } 2183 }; 2184 2185 // A predicate-formatter function that asserts the argument is an even 2186 // number. 2187 AssertionResult AssertIsEven(const char* expr, int n) { 2188 if (IsEven(n)) { 2189 return AssertionSuccess(); 2190 } 2191 2192 Message msg; 2193 msg << expr << " evaluates to " << n << ", which is not even."; 2194 return AssertionFailure(msg); 2195 } 2196 2197 // A predicate function that returns AssertionResult for use in 2198 // EXPECT/ASSERT_TRUE/FALSE. 2199 AssertionResult ResultIsEven(int n) { 2200 if (IsEven(n)) 2201 return AssertionSuccess() << n << " is even"; 2202 else 2203 return AssertionFailure() << n << " is odd"; 2204 } 2205 2206 // A predicate function that returns AssertionResult but gives no 2207 // explanation why it succeeds. Needed for testing that 2208 // EXPECT/ASSERT_FALSE handles such functions correctly. 2209 AssertionResult ResultIsEvenNoExplanation(int n) { 2210 if (IsEven(n)) 2211 return AssertionSuccess(); 2212 else 2213 return AssertionFailure() << n << " is odd"; 2214 } 2215 2216 // A predicate-formatter functor that asserts the argument is an even 2217 // number. 2218 struct AssertIsEvenFunctor { 2219 AssertionResult operator()(const char* expr, int n) { 2220 return AssertIsEven(expr, n); 2221 } 2222 }; 2223 2224 // Returns true if and only if the sum of the arguments is an even number. 2225 bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); } 2226 2227 // A functor that returns true if and only if the sum of the arguments is an 2228 // even number. 2229 struct SumIsEven3Functor { 2230 bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); } 2231 }; 2232 2233 // A predicate-formatter function that asserts the sum of the 2234 // arguments is an even number. 2235 AssertionResult AssertSumIsEven4(const char* e1, const char* e2, const char* e3, 2236 const char* e4, int n1, int n2, int n3, 2237 int n4) { 2238 const int sum = n1 + n2 + n3 + n4; 2239 if (IsEven(sum)) { 2240 return AssertionSuccess(); 2241 } 2242 2243 Message msg; 2244 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + " 2245 << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum 2246 << ", which is not even."; 2247 return AssertionFailure(msg); 2248 } 2249 2250 // A predicate-formatter functor that asserts the sum of the arguments 2251 // is an even number. 2252 struct AssertSumIsEven5Functor { 2253 AssertionResult operator()(const char* e1, const char* e2, const char* e3, 2254 const char* e4, const char* e5, int n1, int n2, 2255 int n3, int n4, int n5) { 2256 const int sum = n1 + n2 + n3 + n4 + n5; 2257 if (IsEven(sum)) { 2258 return AssertionSuccess(); 2259 } 2260 2261 Message msg; 2262 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 2263 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " 2264 << n5 << ") evaluates to " << sum << ", which is not even."; 2265 return AssertionFailure(msg); 2266 } 2267 }; 2268 2269 // Tests unary predicate assertions. 2270 2271 // Tests unary predicate assertions that don't use a custom formatter. 2272 TEST(Pred1Test, WithoutFormat) { 2273 // Success cases. 2274 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!"; 2275 ASSERT_PRED1(IsEven, 4); 2276 2277 // Failure cases. 2278 EXPECT_NONFATAL_FAILURE( 2279 { // NOLINT 2280 EXPECT_PRED1(IsEven, 5) << "This failure is expected."; 2281 }, 2282 "This failure is expected."); 2283 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false"); 2284 } 2285 2286 // Tests unary predicate assertions that use a custom formatter. 2287 TEST(Pred1Test, WithFormat) { 2288 // Success cases. 2289 EXPECT_PRED_FORMAT1(AssertIsEven, 2); 2290 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4) 2291 << "This failure is UNEXPECTED!"; 2292 2293 // Failure cases. 2294 const int n = 5; 2295 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n), 2296 "n evaluates to 5, which is not even."); 2297 EXPECT_FATAL_FAILURE( 2298 { // NOLINT 2299 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected."; 2300 }, 2301 "This failure is expected."); 2302 } 2303 2304 // Tests that unary predicate assertions evaluates their arguments 2305 // exactly once. 2306 TEST(Pred1Test, SingleEvaluationOnFailure) { 2307 // A success case. 2308 static int n = 0; 2309 EXPECT_PRED1(IsEven, n++); 2310 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once."; 2311 2312 // A failure case. 2313 EXPECT_FATAL_FAILURE( 2314 { // NOLINT 2315 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++) 2316 << "This failure is expected."; 2317 }, 2318 "This failure is expected."); 2319 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once."; 2320 } 2321 2322 // Tests predicate assertions whose arity is >= 2. 2323 2324 // Tests predicate assertions that don't use a custom formatter. 2325 TEST(PredTest, WithoutFormat) { 2326 // Success cases. 2327 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!"; 2328 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8); 2329 2330 // Failure cases. 2331 const int n1 = 1; 2332 const int n2 = 2; 2333 EXPECT_NONFATAL_FAILURE( 2334 { // NOLINT 2335 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected."; 2336 }, 2337 "This failure is expected."); 2338 EXPECT_FATAL_FAILURE( 2339 { // NOLINT 2340 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4); 2341 }, 2342 "evaluates to false"); 2343 } 2344 2345 // Tests predicate assertions that use a custom formatter. 2346 TEST(PredTest, WithFormat) { 2347 // Success cases. 2348 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) 2349 << "This failure is UNEXPECTED!"; 2350 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10); 2351 2352 // Failure cases. 2353 const int n1 = 1; 2354 const int n2 = 2; 2355 const int n3 = 4; 2356 const int n4 = 6; 2357 EXPECT_NONFATAL_FAILURE( 2358 { // NOLINT 2359 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4); 2360 }, 2361 "evaluates to 13, which is not even."); 2362 EXPECT_FATAL_FAILURE( 2363 { // NOLINT 2364 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8) 2365 << "This failure is expected."; 2366 }, 2367 "This failure is expected."); 2368 } 2369 2370 // Tests that predicate assertions evaluates their arguments 2371 // exactly once. 2372 TEST(PredTest, SingleEvaluationOnFailure) { 2373 // A success case. 2374 int n1 = 0; 2375 int n2 = 0; 2376 EXPECT_PRED2(SumIsEven2, n1++, n2++); 2377 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; 2378 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; 2379 2380 // Another success case. 2381 n1 = n2 = 0; 2382 int n3 = 0; 2383 int n4 = 0; 2384 int n5 = 0; 2385 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++) 2386 << "This failure is UNEXPECTED!"; 2387 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; 2388 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; 2389 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; 2390 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; 2391 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once."; 2392 2393 // A failure case. 2394 n1 = n2 = n3 = 0; 2395 EXPECT_NONFATAL_FAILURE( 2396 { // NOLINT 2397 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++) 2398 << "This failure is expected."; 2399 }, 2400 "This failure is expected."); 2401 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; 2402 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; 2403 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; 2404 2405 // Another failure case. 2406 n1 = n2 = n3 = n4 = 0; 2407 EXPECT_NONFATAL_FAILURE( 2408 { // NOLINT 2409 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++); 2410 }, 2411 "evaluates to 1, which is not even."); 2412 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; 2413 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; 2414 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; 2415 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; 2416 } 2417 2418 // Test predicate assertions for sets 2419 TEST(PredTest, ExpectPredEvalFailure) { 2420 std::set<int> set_a = {2, 1, 3, 4, 5}; 2421 std::set<int> set_b = {0, 4, 8}; 2422 const auto compare_sets = [](std::set<int>, std::set<int>) { return false; }; 2423 EXPECT_NONFATAL_FAILURE( 2424 EXPECT_PRED2(compare_sets, set_a, set_b), 2425 "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates " 2426 "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }"); 2427 } 2428 2429 // Some helper functions for testing using overloaded/template 2430 // functions with ASSERT_PREDn and EXPECT_PREDn. 2431 2432 bool IsPositive(double x) { return x > 0; } 2433 2434 template <typename T> 2435 bool IsNegative(T x) { 2436 return x < 0; 2437 } 2438 2439 template <typename T1, typename T2> 2440 bool GreaterThan(T1 x1, T2 x2) { 2441 return x1 > x2; 2442 } 2443 2444 // Tests that overloaded functions can be used in *_PRED* as long as 2445 // their types are explicitly specified. 2446 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) { 2447 // C++Builder requires C-style casts rather than static_cast. 2448 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT 2449 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT 2450 } 2451 2452 // Tests that template functions can be used in *_PRED* as long as 2453 // their types are explicitly specified. 2454 TEST(PredicateAssertionTest, AcceptsTemplateFunction) { 2455 EXPECT_PRED1(IsNegative<int>, -5); 2456 // Makes sure that we can handle templates with more than one 2457 // parameter. 2458 ASSERT_PRED2((GreaterThan<int, int>), 5, 0); 2459 } 2460 2461 // Some helper functions for testing using overloaded/template 2462 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn. 2463 2464 AssertionResult IsPositiveFormat(const char* /* expr */, int n) { 2465 return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); 2466 } 2467 2468 AssertionResult IsPositiveFormat(const char* /* expr */, double x) { 2469 return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); 2470 } 2471 2472 template <typename T> 2473 AssertionResult IsNegativeFormat(const char* /* expr */, T x) { 2474 return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); 2475 } 2476 2477 template <typename T1, typename T2> 2478 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */, 2479 const T1& x1, const T2& x2) { 2480 return x1 == x2 ? AssertionSuccess() 2481 : AssertionFailure(Message() << "Failure"); 2482 } 2483 2484 // Tests that overloaded functions can be used in *_PRED_FORMAT* 2485 // without explicitly specifying their types. 2486 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) { 2487 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5); 2488 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0); 2489 } 2490 2491 // Tests that template functions can be used in *_PRED_FORMAT* without 2492 // explicitly specifying their types. 2493 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) { 2494 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5); 2495 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3); 2496 } 2497 2498 // Tests string assertions. 2499 2500 // Tests ASSERT_STREQ with non-NULL arguments. 2501 TEST(StringAssertionTest, ASSERT_STREQ) { 2502 const char* const p1 = "good"; 2503 ASSERT_STREQ(p1, p1); 2504 2505 // Let p2 have the same content as p1, but be at a different address. 2506 const char p2[] = "good"; 2507 ASSERT_STREQ(p1, p2); 2508 2509 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), " \"bad\"\n \"good\""); 2510 } 2511 2512 // Tests ASSERT_STREQ with NULL arguments. 2513 TEST(StringAssertionTest, ASSERT_STREQ_Null) { 2514 ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr); 2515 EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null"); 2516 } 2517 2518 // Tests ASSERT_STREQ with NULL arguments. 2519 TEST(StringAssertionTest, ASSERT_STREQ_Null2) { 2520 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null"); 2521 } 2522 2523 // Tests ASSERT_STRNE. 2524 TEST(StringAssertionTest, ASSERT_STRNE) { 2525 ASSERT_STRNE("hi", "Hi"); 2526 ASSERT_STRNE("Hi", nullptr); 2527 ASSERT_STRNE(nullptr, "Hi"); 2528 ASSERT_STRNE("", nullptr); 2529 ASSERT_STRNE(nullptr, ""); 2530 ASSERT_STRNE("", "Hi"); 2531 ASSERT_STRNE("Hi", ""); 2532 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\""); 2533 } 2534 2535 // Tests ASSERT_STRCASEEQ. 2536 TEST(StringAssertionTest, ASSERT_STRCASEEQ) { 2537 ASSERT_STRCASEEQ("hi", "Hi"); 2538 ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr); 2539 2540 ASSERT_STRCASEEQ("", ""); 2541 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "Ignoring case"); 2542 } 2543 2544 // Tests ASSERT_STRCASENE. 2545 TEST(StringAssertionTest, ASSERT_STRCASENE) { 2546 ASSERT_STRCASENE("hi1", "Hi2"); 2547 ASSERT_STRCASENE("Hi", nullptr); 2548 ASSERT_STRCASENE(nullptr, "Hi"); 2549 ASSERT_STRCASENE("", nullptr); 2550 ASSERT_STRCASENE(nullptr, ""); 2551 ASSERT_STRCASENE("", "Hi"); 2552 ASSERT_STRCASENE("Hi", ""); 2553 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)"); 2554 } 2555 2556 // Tests *_STREQ on wide strings. 2557 TEST(StringAssertionTest, STREQ_Wide) { 2558 // NULL strings. 2559 ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr); 2560 2561 // Empty strings. 2562 ASSERT_STREQ(L"", L""); 2563 2564 // Non-null vs NULL. 2565 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null"); 2566 2567 // Equal strings. 2568 EXPECT_STREQ(L"Hi", L"Hi"); 2569 2570 // Unequal strings. 2571 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc"); 2572 2573 // Strings containing wide characters. 2574 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc"); 2575 2576 // The streaming variation. 2577 EXPECT_NONFATAL_FAILURE( 2578 { // NOLINT 2579 EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure"; 2580 }, 2581 "Expected failure"); 2582 } 2583 2584 // Tests *_STRNE on wide strings. 2585 TEST(StringAssertionTest, STRNE_Wide) { 2586 // NULL strings. 2587 EXPECT_NONFATAL_FAILURE( 2588 { // NOLINT 2589 EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr); 2590 }, 2591 ""); 2592 2593 // Empty strings. 2594 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\""); 2595 2596 // Non-null vs NULL. 2597 ASSERT_STRNE(L"non-null", nullptr); 2598 2599 // Equal strings. 2600 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\""); 2601 2602 // Unequal strings. 2603 EXPECT_STRNE(L"abc", L"Abc"); 2604 2605 // Strings containing wide characters. 2606 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc"); 2607 2608 // The streaming variation. 2609 ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen"; 2610 } 2611 2612 // Tests for ::testing::IsSubstring(). 2613 2614 // Tests that IsSubstring() returns the correct result when the input 2615 // argument type is const char*. 2616 TEST(IsSubstringTest, ReturnsCorrectResultForCString) { 2617 EXPECT_FALSE(IsSubstring("", "", nullptr, "a")); 2618 EXPECT_FALSE(IsSubstring("", "", "b", nullptr)); 2619 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack")); 2620 2621 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr)); 2622 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles")); 2623 } 2624 2625 // Tests that IsSubstring() returns the correct result when the input 2626 // argument type is const wchar_t*. 2627 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) { 2628 EXPECT_FALSE(IsSubstring("", "", kNull, L"a")); 2629 EXPECT_FALSE(IsSubstring("", "", L"b", kNull)); 2630 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack")); 2631 2632 EXPECT_TRUE( 2633 IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr)); 2634 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles")); 2635 } 2636 2637 // Tests that IsSubstring() generates the correct message when the input 2638 // argument type is const char*. 2639 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) { 2640 EXPECT_STREQ( 2641 "Value of: needle_expr\n" 2642 " Actual: \"needle\"\n" 2643 "Expected: a substring of haystack_expr\n" 2644 "Which is: \"haystack\"", 2645 IsSubstring("needle_expr", "haystack_expr", "needle", "haystack") 2646 .failure_message()); 2647 } 2648 2649 // Tests that IsSubstring returns the correct result when the input 2650 // argument type is ::std::string. 2651 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) { 2652 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob")); 2653 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world"))); 2654 } 2655 2656 #if GTEST_HAS_STD_WSTRING 2657 // Tests that IsSubstring returns the correct result when the input 2658 // argument type is ::std::wstring. 2659 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) { 2660 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles")); 2661 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack"))); 2662 } 2663 2664 // Tests that IsSubstring() generates the correct message when the input 2665 // argument type is ::std::wstring. 2666 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) { 2667 EXPECT_STREQ( 2668 "Value of: needle_expr\n" 2669 " Actual: L\"needle\"\n" 2670 "Expected: a substring of haystack_expr\n" 2671 "Which is: L\"haystack\"", 2672 IsSubstring("needle_expr", "haystack_expr", ::std::wstring(L"needle"), 2673 L"haystack") 2674 .failure_message()); 2675 } 2676 2677 #endif // GTEST_HAS_STD_WSTRING 2678 2679 // Tests for ::testing::IsNotSubstring(). 2680 2681 // Tests that IsNotSubstring() returns the correct result when the input 2682 // argument type is const char*. 2683 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) { 2684 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack")); 2685 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles")); 2686 } 2687 2688 // Tests that IsNotSubstring() returns the correct result when the input 2689 // argument type is const wchar_t*. 2690 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) { 2691 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack")); 2692 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles")); 2693 } 2694 2695 // Tests that IsNotSubstring() generates the correct message when the input 2696 // argument type is const wchar_t*. 2697 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) { 2698 EXPECT_STREQ( 2699 "Value of: needle_expr\n" 2700 " Actual: L\"needle\"\n" 2701 "Expected: not a substring of haystack_expr\n" 2702 "Which is: L\"two needles\"", 2703 IsNotSubstring("needle_expr", "haystack_expr", L"needle", L"two needles") 2704 .failure_message()); 2705 } 2706 2707 // Tests that IsNotSubstring returns the correct result when the input 2708 // argument type is ::std::string. 2709 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) { 2710 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob")); 2711 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world"))); 2712 } 2713 2714 // Tests that IsNotSubstring() generates the correct message when the input 2715 // argument type is ::std::string. 2716 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) { 2717 EXPECT_STREQ( 2718 "Value of: needle_expr\n" 2719 " Actual: \"needle\"\n" 2720 "Expected: not a substring of haystack_expr\n" 2721 "Which is: \"two needles\"", 2722 IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"), 2723 "two needles") 2724 .failure_message()); 2725 } 2726 2727 #if GTEST_HAS_STD_WSTRING 2728 2729 // Tests that IsNotSubstring returns the correct result when the input 2730 // argument type is ::std::wstring. 2731 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) { 2732 EXPECT_FALSE( 2733 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles")); 2734 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack"))); 2735 } 2736 2737 #endif // GTEST_HAS_STD_WSTRING 2738 2739 // Tests floating-point assertions. 2740 2741 template <typename RawType> 2742 class FloatingPointTest : public Test { 2743 protected: 2744 // Pre-calculated numbers to be used by the tests. 2745 struct TestValues { 2746 RawType close_to_positive_zero; 2747 RawType close_to_negative_zero; 2748 RawType further_from_negative_zero; 2749 2750 RawType close_to_one; 2751 RawType further_from_one; 2752 2753 RawType infinity; 2754 RawType close_to_infinity; 2755 RawType further_from_infinity; 2756 2757 RawType nan1; 2758 RawType nan2; 2759 }; 2760 2761 typedef typename testing::internal::FloatingPoint<RawType> Floating; 2762 typedef typename Floating::Bits Bits; 2763 2764 void SetUp() override { 2765 const uint32_t max_ulps = Floating::kMaxUlps; 2766 2767 // The bits that represent 0.0. 2768 const Bits zero_bits = Floating(0).bits(); 2769 2770 // Makes some numbers close to 0.0. 2771 values_.close_to_positive_zero = 2772 Floating::ReinterpretBits(zero_bits + max_ulps / 2); 2773 values_.close_to_negative_zero = 2774 -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2); 2775 values_.further_from_negative_zero = 2776 -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2); 2777 2778 // The bits that represent 1.0. 2779 const Bits one_bits = Floating(1).bits(); 2780 2781 // Makes some numbers close to 1.0. 2782 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps); 2783 values_.further_from_one = 2784 Floating::ReinterpretBits(one_bits + max_ulps + 1); 2785 2786 // +infinity. 2787 values_.infinity = Floating::Infinity(); 2788 2789 // The bits that represent +infinity. 2790 const Bits infinity_bits = Floating(values_.infinity).bits(); 2791 2792 // Makes some numbers close to infinity. 2793 values_.close_to_infinity = 2794 Floating::ReinterpretBits(infinity_bits - max_ulps); 2795 values_.further_from_infinity = 2796 Floating::ReinterpretBits(infinity_bits - max_ulps - 1); 2797 2798 // Makes some NAN's. Sets the most significant bit of the fraction so that 2799 // our NaN's are quiet; trying to process a signaling NaN would raise an 2800 // exception if our environment enables floating point exceptions. 2801 values_.nan1 = Floating::ReinterpretBits( 2802 Floating::kExponentBitMask | 2803 (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1); 2804 values_.nan2 = Floating::ReinterpretBits( 2805 Floating::kExponentBitMask | 2806 (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200); 2807 } 2808 2809 void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); } 2810 2811 static TestValues values_; 2812 }; 2813 2814 template <typename RawType> 2815 typename FloatingPointTest<RawType>::TestValues 2816 FloatingPointTest<RawType>::values_; 2817 2818 // Instantiates FloatingPointTest for testing *_FLOAT_EQ. 2819 typedef FloatingPointTest<float> FloatTest; 2820 2821 // Tests that the size of Float::Bits matches the size of float. 2822 TEST_F(FloatTest, Size) { TestSize(); } 2823 2824 // Tests comparing with +0 and -0. 2825 TEST_F(FloatTest, Zeros) { 2826 EXPECT_FLOAT_EQ(0.0, -0.0); 2827 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0"); 2828 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5"); 2829 } 2830 2831 // Tests comparing numbers close to 0. 2832 // 2833 // This ensures that *_FLOAT_EQ handles the sign correctly and no 2834 // overflow occurs when comparing numbers whose absolute value is very 2835 // small. 2836 TEST_F(FloatTest, AlmostZeros) { 2837 // In C++Builder, names within local classes (such as used by 2838 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the 2839 // scoping class. Use a static local alias as a workaround. 2840 // We use the assignment syntax since some compilers, like Sun Studio, 2841 // don't allow initializing references using construction syntax 2842 // (parentheses). 2843 static const FloatTest::TestValues& v = this->values_; 2844 2845 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero); 2846 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero); 2847 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero); 2848 2849 EXPECT_FATAL_FAILURE( 2850 { // NOLINT 2851 ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero); 2852 }, 2853 "v.further_from_negative_zero"); 2854 } 2855 2856 // Tests comparing numbers close to each other. 2857 TEST_F(FloatTest, SmallDiff) { 2858 EXPECT_FLOAT_EQ(1.0, values_.close_to_one); 2859 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one), 2860 "values_.further_from_one"); 2861 } 2862 2863 // Tests comparing numbers far apart. 2864 TEST_F(FloatTest, LargeDiff) { 2865 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0"); 2866 } 2867 2868 // Tests comparing with infinity. 2869 // 2870 // This ensures that no overflow occurs when comparing numbers whose 2871 // absolute value is very large. 2872 TEST_F(FloatTest, Infinity) { 2873 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity); 2874 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity); 2875 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity), 2876 "-values_.infinity"); 2877 2878 // This is interesting as the representations of infinity and nan1 2879 // are only 1 DLP apart. 2880 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1), 2881 "values_.nan1"); 2882 } 2883 2884 // Tests that comparing with NAN always returns false. 2885 TEST_F(FloatTest, NaN) { 2886 // In C++Builder, names within local classes (such as used by 2887 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the 2888 // scoping class. Use a static local alias as a workaround. 2889 // We use the assignment syntax since some compilers, like Sun Studio, 2890 // don't allow initializing references using construction syntax 2891 // (parentheses). 2892 static const FloatTest::TestValues& v = this->values_; 2893 2894 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1"); 2895 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2"); 2896 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1"); 2897 2898 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity"); 2899 } 2900 2901 // Tests that *_FLOAT_EQ are reflexive. 2902 TEST_F(FloatTest, Reflexive) { 2903 EXPECT_FLOAT_EQ(0.0, 0.0); 2904 EXPECT_FLOAT_EQ(1.0, 1.0); 2905 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity); 2906 } 2907 2908 // Tests that *_FLOAT_EQ are commutative. 2909 TEST_F(FloatTest, Commutative) { 2910 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one). 2911 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0); 2912 2913 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one). 2914 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0), 2915 "1.0"); 2916 } 2917 2918 // Tests EXPECT_NEAR. 2919 TEST_F(FloatTest, EXPECT_NEAR) { 2920 EXPECT_NEAR(-1.0f, -1.1f, 0.2f); 2921 EXPECT_NEAR(2.0f, 3.0f, 1.0f); 2922 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT 2923 "The difference between 1.0f and 1.5f is 0.5, " 2924 "which exceeds 0.25f"); 2925 } 2926 2927 // Tests ASSERT_NEAR. 2928 TEST_F(FloatTest, ASSERT_NEAR) { 2929 ASSERT_NEAR(-1.0f, -1.1f, 0.2f); 2930 ASSERT_NEAR(2.0f, 3.0f, 1.0f); 2931 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT 2932 "The difference between 1.0f and 1.5f is 0.5, " 2933 "which exceeds 0.25f"); 2934 } 2935 2936 // Tests the cases where FloatLE() should succeed. 2937 TEST_F(FloatTest, FloatLESucceeds) { 2938 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2, 2939 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2, 2940 2941 // or when val1 is greater than, but almost equals to, val2. 2942 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f); 2943 } 2944 2945 // Tests the cases where FloatLE() should fail. 2946 TEST_F(FloatTest, FloatLEFails) { 2947 // When val1 is greater than val2 by a large margin, 2948 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f), 2949 "(2.0f) <= (1.0f)"); 2950 2951 // or by a small yet non-negligible margin, 2952 EXPECT_NONFATAL_FAILURE( 2953 { // NOLINT 2954 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); 2955 }, 2956 "(values_.further_from_one) <= (1.0f)"); 2957 2958 EXPECT_NONFATAL_FAILURE( 2959 { // NOLINT 2960 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity); 2961 }, 2962 "(values_.nan1) <= (values_.infinity)"); 2963 EXPECT_NONFATAL_FAILURE( 2964 { // NOLINT 2965 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1); 2966 }, 2967 "(-values_.infinity) <= (values_.nan1)"); 2968 EXPECT_FATAL_FAILURE( 2969 { // NOLINT 2970 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); 2971 }, 2972 "(values_.nan1) <= (values_.nan1)"); 2973 } 2974 2975 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ. 2976 typedef FloatingPointTest<double> DoubleTest; 2977 2978 // Tests that the size of Double::Bits matches the size of double. 2979 TEST_F(DoubleTest, Size) { TestSize(); } 2980 2981 // Tests comparing with +0 and -0. 2982 TEST_F(DoubleTest, Zeros) { 2983 EXPECT_DOUBLE_EQ(0.0, -0.0); 2984 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0"); 2985 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0"); 2986 } 2987 2988 // Tests comparing numbers close to 0. 2989 // 2990 // This ensures that *_DOUBLE_EQ handles the sign correctly and no 2991 // overflow occurs when comparing numbers whose absolute value is very 2992 // small. 2993 TEST_F(DoubleTest, AlmostZeros) { 2994 // In C++Builder, names within local classes (such as used by 2995 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the 2996 // scoping class. Use a static local alias as a workaround. 2997 // We use the assignment syntax since some compilers, like Sun Studio, 2998 // don't allow initializing references using construction syntax 2999 // (parentheses). 3000 static const DoubleTest::TestValues& v = this->values_; 3001 3002 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero); 3003 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero); 3004 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero); 3005 3006 EXPECT_FATAL_FAILURE( 3007 { // NOLINT 3008 ASSERT_DOUBLE_EQ(v.close_to_positive_zero, 3009 v.further_from_negative_zero); 3010 }, 3011 "v.further_from_negative_zero"); 3012 } 3013 3014 // Tests comparing numbers close to each other. 3015 TEST_F(DoubleTest, SmallDiff) { 3016 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one); 3017 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one), 3018 "values_.further_from_one"); 3019 } 3020 3021 // Tests comparing numbers far apart. 3022 TEST_F(DoubleTest, LargeDiff) { 3023 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0"); 3024 } 3025 3026 // Tests comparing with infinity. 3027 // 3028 // This ensures that no overflow occurs when comparing numbers whose 3029 // absolute value is very large. 3030 TEST_F(DoubleTest, Infinity) { 3031 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity); 3032 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity); 3033 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity), 3034 "-values_.infinity"); 3035 3036 // This is interesting as the representations of infinity_ and nan1_ 3037 // are only 1 DLP apart. 3038 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1), 3039 "values_.nan1"); 3040 } 3041 3042 // Tests that comparing with NAN always returns false. 3043 TEST_F(DoubleTest, NaN) { 3044 static const DoubleTest::TestValues& v = this->values_; 3045 3046 // Nokia's STLport crashes if we try to output infinity or NaN. 3047 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1"); 3048 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2"); 3049 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1"); 3050 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity"); 3051 } 3052 3053 // Tests that *_DOUBLE_EQ are reflexive. 3054 TEST_F(DoubleTest, Reflexive) { 3055 EXPECT_DOUBLE_EQ(0.0, 0.0); 3056 EXPECT_DOUBLE_EQ(1.0, 1.0); 3057 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity); 3058 } 3059 3060 // Tests that *_DOUBLE_EQ are commutative. 3061 TEST_F(DoubleTest, Commutative) { 3062 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one). 3063 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0); 3064 3065 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one). 3066 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0), 3067 "1.0"); 3068 } 3069 3070 // Tests EXPECT_NEAR. 3071 TEST_F(DoubleTest, EXPECT_NEAR) { 3072 EXPECT_NEAR(-1.0, -1.1, 0.2); 3073 EXPECT_NEAR(2.0, 3.0, 1.0); 3074 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT 3075 "The difference between 1.0 and 1.5 is 0.5, " 3076 "which exceeds 0.25"); 3077 // At this magnitude adjacent doubles are 512.0 apart, so this triggers a 3078 // slightly different failure reporting path. 3079 EXPECT_NONFATAL_FAILURE( 3080 EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0), 3081 "The abs_error parameter 1.0 evaluates to 1 which is smaller than the " 3082 "minimum distance between doubles for numbers of this magnitude which is " 3083 "512"); 3084 } 3085 3086 // Tests ASSERT_NEAR. 3087 TEST_F(DoubleTest, ASSERT_NEAR) { 3088 ASSERT_NEAR(-1.0, -1.1, 0.2); 3089 ASSERT_NEAR(2.0, 3.0, 1.0); 3090 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT 3091 "The difference between 1.0 and 1.5 is 0.5, " 3092 "which exceeds 0.25"); 3093 } 3094 3095 // Tests the cases where DoubleLE() should succeed. 3096 TEST_F(DoubleTest, DoubleLESucceeds) { 3097 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2, 3098 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2, 3099 3100 // or when val1 is greater than, but almost equals to, val2. 3101 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0); 3102 } 3103 3104 // Tests the cases where DoubleLE() should fail. 3105 TEST_F(DoubleTest, DoubleLEFails) { 3106 // When val1 is greater than val2 by a large margin, 3107 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0), 3108 "(2.0) <= (1.0)"); 3109 3110 // or by a small yet non-negligible margin, 3111 EXPECT_NONFATAL_FAILURE( 3112 { // NOLINT 3113 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); 3114 }, 3115 "(values_.further_from_one) <= (1.0)"); 3116 3117 EXPECT_NONFATAL_FAILURE( 3118 { // NOLINT 3119 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity); 3120 }, 3121 "(values_.nan1) <= (values_.infinity)"); 3122 EXPECT_NONFATAL_FAILURE( 3123 { // NOLINT 3124 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1); 3125 }, 3126 " (-values_.infinity) <= (values_.nan1)"); 3127 EXPECT_FATAL_FAILURE( 3128 { // NOLINT 3129 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); 3130 }, 3131 "(values_.nan1) <= (values_.nan1)"); 3132 } 3133 3134 // Verifies that a test or test case whose name starts with DISABLED_ is 3135 // not run. 3136 3137 // A test whose name starts with DISABLED_. 3138 // Should not run. 3139 TEST(DisabledTest, DISABLED_TestShouldNotRun) { 3140 FAIL() << "Unexpected failure: Disabled test should not be run."; 3141 } 3142 3143 // A test whose name does not start with DISABLED_. 3144 // Should run. 3145 TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); } 3146 3147 // A test case whose name starts with DISABLED_. 3148 // Should not run. 3149 TEST(DISABLED_TestSuite, TestShouldNotRun) { 3150 FAIL() << "Unexpected failure: Test in disabled test case should not be run."; 3151 } 3152 3153 // A test case and test whose names start with DISABLED_. 3154 // Should not run. 3155 TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) { 3156 FAIL() << "Unexpected failure: Test in disabled test case should not be run."; 3157 } 3158 3159 // Check that when all tests in a test case are disabled, SetUpTestSuite() and 3160 // TearDownTestSuite() are not called. 3161 class DisabledTestsTest : public Test { 3162 protected: 3163 static void SetUpTestSuite() { 3164 FAIL() << "Unexpected failure: All tests disabled in test case. " 3165 "SetUpTestSuite() should not be called."; 3166 } 3167 3168 static void TearDownTestSuite() { 3169 FAIL() << "Unexpected failure: All tests disabled in test case. " 3170 "TearDownTestSuite() should not be called."; 3171 } 3172 }; 3173 3174 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) { 3175 FAIL() << "Unexpected failure: Disabled test should not be run."; 3176 } 3177 3178 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) { 3179 FAIL() << "Unexpected failure: Disabled test should not be run."; 3180 } 3181 3182 // Tests that disabled typed tests aren't run. 3183 3184 template <typename T> 3185 class TypedTest : public Test {}; 3186 3187 typedef testing::Types<int, double> NumericTypes; 3188 TYPED_TEST_SUITE(TypedTest, NumericTypes); 3189 3190 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { 3191 FAIL() << "Unexpected failure: Disabled typed test should not run."; 3192 } 3193 3194 template <typename T> 3195 class DISABLED_TypedTest : public Test {}; 3196 3197 TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes); 3198 3199 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { 3200 FAIL() << "Unexpected failure: Disabled typed test should not run."; 3201 } 3202 3203 // Tests that disabled type-parameterized tests aren't run. 3204 3205 template <typename T> 3206 class TypedTestP : public Test {}; 3207 3208 TYPED_TEST_SUITE_P(TypedTestP); 3209 3210 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) { 3211 FAIL() << "Unexpected failure: " 3212 << "Disabled type-parameterized test should not run."; 3213 } 3214 3215 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun); 3216 3217 INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes); 3218 3219 template <typename T> 3220 class DISABLED_TypedTestP : public Test {}; 3221 3222 TYPED_TEST_SUITE_P(DISABLED_TypedTestP); 3223 3224 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) { 3225 FAIL() << "Unexpected failure: " 3226 << "Disabled type-parameterized test should not run."; 3227 } 3228 3229 REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun); 3230 3231 INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes); 3232 3233 // Tests that assertion macros evaluate their arguments exactly once. 3234 3235 class SingleEvaluationTest : public Test { 3236 public: // Must be public and not protected due to a bug in g++ 3.4.2. 3237 // This helper function is needed by the FailedASSERT_STREQ test 3238 // below. It's public to work around C++Builder's bug with scoping local 3239 // classes. 3240 static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); } 3241 3242 // This helper function is needed by the FailedASSERT_NE test below. It's 3243 // public to work around C++Builder's bug with scoping local classes. 3244 static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); } 3245 3246 protected: 3247 SingleEvaluationTest() { 3248 p1_ = s1_; 3249 p2_ = s2_; 3250 a_ = 0; 3251 b_ = 0; 3252 } 3253 3254 static const char* const s1_; 3255 static const char* const s2_; 3256 static const char* p1_; 3257 static const char* p2_; 3258 3259 static int a_; 3260 static int b_; 3261 }; 3262 3263 const char* const SingleEvaluationTest::s1_ = "01234"; 3264 const char* const SingleEvaluationTest::s2_ = "abcde"; 3265 const char* SingleEvaluationTest::p1_; 3266 const char* SingleEvaluationTest::p2_; 3267 int SingleEvaluationTest::a_; 3268 int SingleEvaluationTest::b_; 3269 3270 // Tests that when ASSERT_STREQ fails, it evaluates its arguments 3271 // exactly once. 3272 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) { 3273 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(), 3274 "p2_++"); 3275 EXPECT_EQ(s1_ + 1, p1_); 3276 EXPECT_EQ(s2_ + 1, p2_); 3277 } 3278 3279 // Tests that string assertion arguments are evaluated exactly once. 3280 TEST_F(SingleEvaluationTest, ASSERT_STR) { 3281 // successful EXPECT_STRNE 3282 EXPECT_STRNE(p1_++, p2_++); 3283 EXPECT_EQ(s1_ + 1, p1_); 3284 EXPECT_EQ(s2_ + 1, p2_); 3285 3286 // failed EXPECT_STRCASEEQ 3287 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "Ignoring case"); 3288 EXPECT_EQ(s1_ + 2, p1_); 3289 EXPECT_EQ(s2_ + 2, p2_); 3290 } 3291 3292 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly 3293 // once. 3294 TEST_F(SingleEvaluationTest, FailedASSERT_NE) { 3295 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(), 3296 "(a_++) != (b_++)"); 3297 EXPECT_EQ(1, a_); 3298 EXPECT_EQ(1, b_); 3299 } 3300 3301 // Tests that assertion arguments are evaluated exactly once. 3302 TEST_F(SingleEvaluationTest, OtherCases) { 3303 // successful EXPECT_TRUE 3304 EXPECT_TRUE(0 == a_++); // NOLINT 3305 EXPECT_EQ(1, a_); 3306 3307 // failed EXPECT_TRUE 3308 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++"); 3309 EXPECT_EQ(2, a_); 3310 3311 // successful EXPECT_GT 3312 EXPECT_GT(a_++, b_++); 3313 EXPECT_EQ(3, a_); 3314 EXPECT_EQ(1, b_); 3315 3316 // failed EXPECT_LT 3317 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)"); 3318 EXPECT_EQ(4, a_); 3319 EXPECT_EQ(2, b_); 3320 3321 // successful ASSERT_TRUE 3322 ASSERT_TRUE(0 < a_++); // NOLINT 3323 EXPECT_EQ(5, a_); 3324 3325 // successful ASSERT_GT 3326 ASSERT_GT(a_++, b_++); 3327 EXPECT_EQ(6, a_); 3328 EXPECT_EQ(3, b_); 3329 } 3330 3331 #if GTEST_HAS_EXCEPTIONS 3332 3333 #if GTEST_HAS_RTTI 3334 3335 #define ERROR_DESC "std::runtime_error" 3336 3337 #else // GTEST_HAS_RTTI 3338 3339 #define ERROR_DESC "an std::exception-derived error" 3340 3341 #endif // GTEST_HAS_RTTI 3342 3343 void ThrowAnInteger() { throw 1; } 3344 void ThrowRuntimeError(const char* what) { throw std::runtime_error(what); } 3345 3346 // Tests that assertion arguments are evaluated exactly once. 3347 TEST_F(SingleEvaluationTest, ExceptionTests) { 3348 // successful EXPECT_THROW 3349 EXPECT_THROW( 3350 { // NOLINT 3351 a_++; 3352 ThrowAnInteger(); 3353 }, 3354 int); 3355 EXPECT_EQ(1, a_); 3356 3357 // failed EXPECT_THROW, throws different 3358 EXPECT_NONFATAL_FAILURE(EXPECT_THROW( 3359 { // NOLINT 3360 a_++; 3361 ThrowAnInteger(); 3362 }, 3363 bool), 3364 "throws a different type"); 3365 EXPECT_EQ(2, a_); 3366 3367 // failed EXPECT_THROW, throws runtime error 3368 EXPECT_NONFATAL_FAILURE(EXPECT_THROW( 3369 { // NOLINT 3370 a_++; 3371 ThrowRuntimeError("A description"); 3372 }, 3373 bool), 3374 "throws " ERROR_DESC 3375 " with description \"A description\""); 3376 EXPECT_EQ(3, a_); 3377 3378 // failed EXPECT_THROW, throws nothing 3379 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing"); 3380 EXPECT_EQ(4, a_); 3381 3382 // successful EXPECT_NO_THROW 3383 EXPECT_NO_THROW(a_++); 3384 EXPECT_EQ(5, a_); 3385 3386 // failed EXPECT_NO_THROW 3387 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT 3388 a_++; 3389 ThrowAnInteger(); 3390 }), 3391 "it throws"); 3392 EXPECT_EQ(6, a_); 3393 3394 // successful EXPECT_ANY_THROW 3395 EXPECT_ANY_THROW({ // NOLINT 3396 a_++; 3397 ThrowAnInteger(); 3398 }); 3399 EXPECT_EQ(7, a_); 3400 3401 // failed EXPECT_ANY_THROW 3402 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't"); 3403 EXPECT_EQ(8, a_); 3404 } 3405 3406 #endif // GTEST_HAS_EXCEPTIONS 3407 3408 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE. 3409 class NoFatalFailureTest : public Test { 3410 protected: 3411 void Succeeds() {} 3412 void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; } 3413 void Fails() { FAIL() << "some fatal failure"; } 3414 3415 void DoAssertNoFatalFailureOnFails() { 3416 ASSERT_NO_FATAL_FAILURE(Fails()); 3417 ADD_FAILURE() << "should not reach here."; 3418 } 3419 3420 void DoExpectNoFatalFailureOnFails() { 3421 EXPECT_NO_FATAL_FAILURE(Fails()); 3422 ADD_FAILURE() << "other failure"; 3423 } 3424 }; 3425 3426 TEST_F(NoFatalFailureTest, NoFailure) { 3427 EXPECT_NO_FATAL_FAILURE(Succeeds()); 3428 ASSERT_NO_FATAL_FAILURE(Succeeds()); 3429 } 3430 3431 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) { 3432 EXPECT_NONFATAL_FAILURE(EXPECT_NO_FATAL_FAILURE(FailsNonFatal()), 3433 "some non-fatal failure"); 3434 EXPECT_NONFATAL_FAILURE(ASSERT_NO_FATAL_FAILURE(FailsNonFatal()), 3435 "some non-fatal failure"); 3436 } 3437 3438 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) { 3439 TestPartResultArray gtest_failures; 3440 { 3441 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); 3442 DoAssertNoFatalFailureOnFails(); 3443 } 3444 ASSERT_EQ(2, gtest_failures.size()); 3445 EXPECT_EQ(TestPartResult::kFatalFailure, 3446 gtest_failures.GetTestPartResult(0).type()); 3447 EXPECT_EQ(TestPartResult::kFatalFailure, 3448 gtest_failures.GetTestPartResult(1).type()); 3449 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", 3450 gtest_failures.GetTestPartResult(0).message()); 3451 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", 3452 gtest_failures.GetTestPartResult(1).message()); 3453 } 3454 3455 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) { 3456 TestPartResultArray gtest_failures; 3457 { 3458 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); 3459 DoExpectNoFatalFailureOnFails(); 3460 } 3461 ASSERT_EQ(3, gtest_failures.size()); 3462 EXPECT_EQ(TestPartResult::kFatalFailure, 3463 gtest_failures.GetTestPartResult(0).type()); 3464 EXPECT_EQ(TestPartResult::kNonFatalFailure, 3465 gtest_failures.GetTestPartResult(1).type()); 3466 EXPECT_EQ(TestPartResult::kNonFatalFailure, 3467 gtest_failures.GetTestPartResult(2).type()); 3468 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", 3469 gtest_failures.GetTestPartResult(0).message()); 3470 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", 3471 gtest_failures.GetTestPartResult(1).message()); 3472 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure", 3473 gtest_failures.GetTestPartResult(2).message()); 3474 } 3475 3476 TEST_F(NoFatalFailureTest, MessageIsStreamable) { 3477 TestPartResultArray gtest_failures; 3478 { 3479 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); 3480 EXPECT_NO_FATAL_FAILURE([] { FAIL() << "foo"; }()) << "my message"; 3481 } 3482 ASSERT_EQ(2, gtest_failures.size()); 3483 EXPECT_EQ(TestPartResult::kFatalFailure, 3484 gtest_failures.GetTestPartResult(0).type()); 3485 EXPECT_EQ(TestPartResult::kNonFatalFailure, 3486 gtest_failures.GetTestPartResult(1).type()); 3487 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo", 3488 gtest_failures.GetTestPartResult(0).message()); 3489 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message", 3490 gtest_failures.GetTestPartResult(1).message()); 3491 } 3492 3493 // Tests non-string assertions. 3494 3495 std::string EditsToString(const std::vector<EditType>& edits) { 3496 std::string out; 3497 for (size_t i = 0; i < edits.size(); ++i) { 3498 static const char kEdits[] = " +-/"; 3499 out.append(1, kEdits[edits[i]]); 3500 } 3501 return out; 3502 } 3503 3504 std::vector<size_t> CharsToIndices(const std::string& str) { 3505 std::vector<size_t> out; 3506 for (size_t i = 0; i < str.size(); ++i) { 3507 out.push_back(static_cast<size_t>(str[i])); 3508 } 3509 return out; 3510 } 3511 3512 std::vector<std::string> CharsToLines(const std::string& str) { 3513 std::vector<std::string> out; 3514 for (size_t i = 0; i < str.size(); ++i) { 3515 out.push_back(str.substr(i, 1)); 3516 } 3517 return out; 3518 } 3519 3520 TEST(EditDistance, TestSuites) { 3521 struct Case { 3522 int line; 3523 const char* left; 3524 const char* right; 3525 const char* expected_edits; 3526 const char* expected_diff; 3527 }; 3528 static const Case kCases[] = { 3529 // No change. 3530 {__LINE__, "A", "A", " ", ""}, 3531 {__LINE__, "ABCDE", "ABCDE", " ", ""}, 3532 // Simple adds. 3533 {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"}, 3534 {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"}, 3535 // Simple removes. 3536 {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"}, 3537 {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"}, 3538 // Simple replaces. 3539 {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"}, 3540 {__LINE__, "ABCD", "abcd", "////", 3541 "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"}, 3542 // Path finding. 3543 {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +", 3544 "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"}, 3545 {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ", 3546 "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"}, 3547 {__LINE__, "ABCDE", "BCDCD", "- +/", 3548 "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"}, 3549 {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++", 3550 "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n" 3551 "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"}, 3552 {}}; 3553 for (const Case* c = kCases; c->left; ++c) { 3554 EXPECT_TRUE(c->expected_edits == 3555 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left), 3556 CharsToIndices(c->right)))) 3557 << "Left <" << c->left << "> Right <" << c->right << "> Edits <" 3558 << EditsToString(CalculateOptimalEdits(CharsToIndices(c->left), 3559 CharsToIndices(c->right))) 3560 << ">"; 3561 EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left), 3562 CharsToLines(c->right))) 3563 << "Left <" << c->left << "> Right <" << c->right << "> Diff <" 3564 << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right)) 3565 << ">"; 3566 } 3567 } 3568 3569 // Tests EqFailure(), used for implementing *EQ* assertions. 3570 TEST(AssertionTest, EqFailure) { 3571 const std::string foo_val("5"), bar_val("6"); 3572 const std::string msg1( 3573 EqFailure("foo", "bar", foo_val, bar_val, false).failure_message()); 3574 EXPECT_STREQ( 3575 "Expected equality of these values:\n" 3576 " foo\n" 3577 " Which is: 5\n" 3578 " bar\n" 3579 " Which is: 6", 3580 msg1.c_str()); 3581 3582 const std::string msg2( 3583 EqFailure("foo", "6", foo_val, bar_val, false).failure_message()); 3584 EXPECT_STREQ( 3585 "Expected equality of these values:\n" 3586 " foo\n" 3587 " Which is: 5\n" 3588 " 6", 3589 msg2.c_str()); 3590 3591 const std::string msg3( 3592 EqFailure("5", "bar", foo_val, bar_val, false).failure_message()); 3593 EXPECT_STREQ( 3594 "Expected equality of these values:\n" 3595 " 5\n" 3596 " bar\n" 3597 " Which is: 6", 3598 msg3.c_str()); 3599 3600 const std::string msg4( 3601 EqFailure("5", "6", foo_val, bar_val, false).failure_message()); 3602 EXPECT_STREQ( 3603 "Expected equality of these values:\n" 3604 " 5\n" 3605 " 6", 3606 msg4.c_str()); 3607 3608 const std::string msg5( 3609 EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true) 3610 .failure_message()); 3611 EXPECT_STREQ( 3612 "Expected equality of these values:\n" 3613 " foo\n" 3614 " Which is: \"x\"\n" 3615 " bar\n" 3616 " Which is: \"y\"\n" 3617 "Ignoring case", 3618 msg5.c_str()); 3619 } 3620 3621 TEST(AssertionTest, EqFailureWithDiff) { 3622 const std::string left( 3623 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15"); 3624 const std::string right( 3625 "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14"); 3626 const std::string msg1( 3627 EqFailure("left", "right", left, right, false).failure_message()); 3628 EXPECT_STREQ( 3629 "Expected equality of these values:\n" 3630 " left\n" 3631 " Which is: " 3632 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n" 3633 " right\n" 3634 " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n" 3635 "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n" 3636 "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n", 3637 msg1.c_str()); 3638 } 3639 3640 // Tests AppendUserMessage(), used for implementing the *EQ* macros. 3641 TEST(AssertionTest, AppendUserMessage) { 3642 const std::string foo("foo"); 3643 3644 Message msg; 3645 EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str()); 3646 3647 msg << "bar"; 3648 EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str()); 3649 } 3650 3651 #ifdef __BORLANDC__ 3652 // Silences warnings: "Condition is always true", "Unreachable code" 3653 #pragma option push -w-ccc -w-rch 3654 #endif 3655 3656 // Tests ASSERT_TRUE. 3657 TEST(AssertionTest, ASSERT_TRUE) { 3658 ASSERT_TRUE(2 > 1); // NOLINT 3659 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1"); 3660 } 3661 3662 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult. 3663 TEST(AssertionTest, AssertTrueWithAssertionResult) { 3664 ASSERT_TRUE(ResultIsEven(2)); 3665 #ifndef __BORLANDC__ 3666 // ICE's in C++Builder. 3667 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)), 3668 "Value of: ResultIsEven(3)\n" 3669 " Actual: false (3 is odd)\n" 3670 "Expected: true"); 3671 #endif 3672 ASSERT_TRUE(ResultIsEvenNoExplanation(2)); 3673 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)), 3674 "Value of: ResultIsEvenNoExplanation(3)\n" 3675 " Actual: false (3 is odd)\n" 3676 "Expected: true"); 3677 } 3678 3679 // Tests ASSERT_FALSE. 3680 TEST(AssertionTest, ASSERT_FALSE) { 3681 ASSERT_FALSE(2 < 1); // NOLINT 3682 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1), 3683 "Value of: 2 > 1\n" 3684 " Actual: true\n" 3685 "Expected: false"); 3686 } 3687 3688 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult. 3689 TEST(AssertionTest, AssertFalseWithAssertionResult) { 3690 ASSERT_FALSE(ResultIsEven(3)); 3691 #ifndef __BORLANDC__ 3692 // ICE's in C++Builder. 3693 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)), 3694 "Value of: ResultIsEven(2)\n" 3695 " Actual: true (2 is even)\n" 3696 "Expected: false"); 3697 #endif 3698 ASSERT_FALSE(ResultIsEvenNoExplanation(3)); 3699 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)), 3700 "Value of: ResultIsEvenNoExplanation(2)\n" 3701 " Actual: true\n" 3702 "Expected: false"); 3703 } 3704 3705 #ifdef __BORLANDC__ 3706 // Restores warnings after previous "#pragma option push" suppressed them 3707 #pragma option pop 3708 #endif 3709 3710 // Tests using ASSERT_EQ on double values. The purpose is to make 3711 // sure that the specialization we did for integer and anonymous enums 3712 // isn't used for double arguments. 3713 TEST(ExpectTest, ASSERT_EQ_Double) { 3714 // A success. 3715 ASSERT_EQ(5.6, 5.6); 3716 3717 // A failure. 3718 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1"); 3719 } 3720 3721 // Tests ASSERT_EQ. 3722 TEST(AssertionTest, ASSERT_EQ) { 3723 ASSERT_EQ(5, 2 + 3); 3724 // clang-format off 3725 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), 3726 "Expected equality of these values:\n" 3727 " 5\n" 3728 " 2*3\n" 3729 " Which is: 6"); 3730 // clang-format on 3731 } 3732 3733 // Tests ASSERT_EQ(NULL, pointer). 3734 TEST(AssertionTest, ASSERT_EQ_NULL) { 3735 // A success. 3736 const char* p = nullptr; 3737 ASSERT_EQ(nullptr, p); 3738 3739 // A failure. 3740 static int n = 0; 3741 EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:"); 3742 } 3743 3744 // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be 3745 // treated as a null pointer by the compiler, we need to make sure 3746 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as 3747 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer). 3748 TEST(ExpectTest, ASSERT_EQ_0) { 3749 int n = 0; 3750 3751 // A success. 3752 ASSERT_EQ(0, n); 3753 3754 // A failure. 3755 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), " 0\n 5.6"); 3756 } 3757 3758 // Tests ASSERT_NE. 3759 TEST(AssertionTest, ASSERT_NE) { 3760 ASSERT_NE(6, 7); 3761 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'), 3762 "Expected: ('a') != ('a'), " 3763 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); 3764 } 3765 3766 // Tests ASSERT_LE. 3767 TEST(AssertionTest, ASSERT_LE) { 3768 ASSERT_LE(2, 3); 3769 ASSERT_LE(2, 2); 3770 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0"); 3771 } 3772 3773 // Tests ASSERT_LT. 3774 TEST(AssertionTest, ASSERT_LT) { 3775 ASSERT_LT(2, 3); 3776 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2"); 3777 } 3778 3779 // Tests ASSERT_GE. 3780 TEST(AssertionTest, ASSERT_GE) { 3781 ASSERT_GE(2, 1); 3782 ASSERT_GE(2, 2); 3783 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3"); 3784 } 3785 3786 // Tests ASSERT_GT. 3787 TEST(AssertionTest, ASSERT_GT) { 3788 ASSERT_GT(2, 1); 3789 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2"); 3790 } 3791 3792 #if GTEST_HAS_EXCEPTIONS 3793 3794 void ThrowNothing() {} 3795 3796 // Tests ASSERT_THROW. 3797 TEST(AssertionTest, ASSERT_THROW) { 3798 ASSERT_THROW(ThrowAnInteger(), int); 3799 3800 #ifndef __BORLANDC__ 3801 3802 // ICE's in C++Builder 2007 and 2009. 3803 EXPECT_FATAL_FAILURE( 3804 ASSERT_THROW(ThrowAnInteger(), bool), 3805 "Expected: ThrowAnInteger() throws an exception of type bool.\n" 3806 " Actual: it throws a different type."); 3807 EXPECT_FATAL_FAILURE( 3808 ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error), 3809 "Expected: ThrowRuntimeError(\"A description\") " 3810 "throws an exception of type std::logic_error.\n " 3811 "Actual: it throws " ERROR_DESC 3812 " " 3813 "with description \"A description\"."); 3814 #endif 3815 3816 EXPECT_FATAL_FAILURE( 3817 ASSERT_THROW(ThrowNothing(), bool), 3818 "Expected: ThrowNothing() throws an exception of type bool.\n" 3819 " Actual: it throws nothing."); 3820 } 3821 3822 // Tests ASSERT_NO_THROW. 3823 TEST(AssertionTest, ASSERT_NO_THROW) { 3824 ASSERT_NO_THROW(ThrowNothing()); 3825 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()), 3826 "Expected: ThrowAnInteger() doesn't throw an exception." 3827 "\n Actual: it throws."); 3828 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")), 3829 "Expected: ThrowRuntimeError(\"A description\") " 3830 "doesn't throw an exception.\n " 3831 "Actual: it throws " ERROR_DESC 3832 " " 3833 "with description \"A description\"."); 3834 } 3835 3836 // Tests ASSERT_ANY_THROW. 3837 TEST(AssertionTest, ASSERT_ANY_THROW) { 3838 ASSERT_ANY_THROW(ThrowAnInteger()); 3839 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()), 3840 "Expected: ThrowNothing() throws an exception.\n" 3841 " Actual: it doesn't."); 3842 } 3843 3844 #endif // GTEST_HAS_EXCEPTIONS 3845 3846 // Makes sure we deal with the precedence of <<. This test should 3847 // compile. 3848 TEST(AssertionTest, AssertPrecedence) { 3849 ASSERT_EQ(1 < 2, true); 3850 bool false_value = false; 3851 ASSERT_EQ(true && false_value, false); 3852 } 3853 3854 // A subroutine used by the following test. 3855 void TestEq1(int x) { ASSERT_EQ(1, x); } 3856 3857 // Tests calling a test subroutine that's not part of a fixture. 3858 TEST(AssertionTest, NonFixtureSubroutine) { 3859 EXPECT_FATAL_FAILURE(TestEq1(2), " x\n Which is: 2"); 3860 } 3861 3862 // An uncopyable class. 3863 class Uncopyable { 3864 public: 3865 explicit Uncopyable(int a_value) : value_(a_value) {} 3866 3867 int value() const { return value_; } 3868 bool operator==(const Uncopyable& rhs) const { 3869 return value() == rhs.value(); 3870 } 3871 3872 private: 3873 // This constructor deliberately has no implementation, as we don't 3874 // want this class to be copyable. 3875 Uncopyable(const Uncopyable&); // NOLINT 3876 3877 int value_; 3878 }; 3879 3880 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) { 3881 return os << value.value(); 3882 } 3883 3884 bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; } 3885 3886 // A subroutine used by the following test. 3887 void TestAssertNonPositive() { 3888 Uncopyable y(-1); 3889 ASSERT_PRED1(IsPositiveUncopyable, y); 3890 } 3891 // A subroutine used by the following test. 3892 void TestAssertEqualsUncopyable() { 3893 Uncopyable x(5); 3894 Uncopyable y(-1); 3895 ASSERT_EQ(x, y); 3896 } 3897 3898 // Tests that uncopyable objects can be used in assertions. 3899 TEST(AssertionTest, AssertWorksWithUncopyableObject) { 3900 Uncopyable x(5); 3901 ASSERT_PRED1(IsPositiveUncopyable, x); 3902 ASSERT_EQ(x, x); 3903 EXPECT_FATAL_FAILURE( 3904 TestAssertNonPositive(), 3905 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); 3906 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(), 3907 "Expected equality of these values:\n" 3908 " x\n Which is: 5\n y\n Which is: -1"); 3909 } 3910 3911 // Tests that uncopyable objects can be used in expects. 3912 TEST(AssertionTest, ExpectWorksWithUncopyableObject) { 3913 Uncopyable x(5); 3914 EXPECT_PRED1(IsPositiveUncopyable, x); 3915 Uncopyable y(-1); 3916 EXPECT_NONFATAL_FAILURE( 3917 EXPECT_PRED1(IsPositiveUncopyable, y), 3918 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); 3919 EXPECT_EQ(x, x); 3920 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), 3921 "Expected equality of these values:\n" 3922 " x\n Which is: 5\n y\n Which is: -1"); 3923 } 3924 3925 enum NamedEnum { kE1 = 0, kE2 = 1 }; 3926 3927 TEST(AssertionTest, NamedEnum) { 3928 EXPECT_EQ(kE1, kE1); 3929 EXPECT_LT(kE1, kE2); 3930 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0"); 3931 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1"); 3932 } 3933 3934 // Sun Studio and HP aCC2reject this code. 3935 #if !defined(__SUNPRO_CC) && !defined(__HP_aCC) 3936 3937 // Tests using assertions with anonymous enums. 3938 enum { 3939 kCaseA = -1, 3940 3941 #ifdef GTEST_OS_LINUX 3942 3943 // We want to test the case where the size of the anonymous enum is 3944 // larger than sizeof(int), to make sure our implementation of the 3945 // assertions doesn't truncate the enums. However, MSVC 3946 // (incorrectly) doesn't allow an enum value to exceed the range of 3947 // an int, so this has to be conditionally compiled. 3948 // 3949 // On Linux, kCaseB and kCaseA have the same value when truncated to 3950 // int size. We want to test whether this will confuse the 3951 // assertions. 3952 kCaseB = testing::internal::kMaxBiggestInt, 3953 3954 #else 3955 3956 kCaseB = INT_MAX, 3957 3958 #endif // GTEST_OS_LINUX 3959 3960 kCaseC = 42 3961 }; 3962 3963 TEST(AssertionTest, AnonymousEnum) { 3964 #ifdef GTEST_OS_LINUX 3965 3966 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB)); 3967 3968 #endif // GTEST_OS_LINUX 3969 3970 EXPECT_EQ(kCaseA, kCaseA); 3971 EXPECT_NE(kCaseA, kCaseB); 3972 EXPECT_LT(kCaseA, kCaseB); 3973 EXPECT_LE(kCaseA, kCaseB); 3974 EXPECT_GT(kCaseB, kCaseA); 3975 EXPECT_GE(kCaseA, kCaseA); 3976 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)"); 3977 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42"); 3978 3979 ASSERT_EQ(kCaseA, kCaseA); 3980 ASSERT_NE(kCaseA, kCaseB); 3981 ASSERT_LT(kCaseA, kCaseB); 3982 ASSERT_LE(kCaseA, kCaseB); 3983 ASSERT_GT(kCaseB, kCaseA); 3984 ASSERT_GE(kCaseA, kCaseA); 3985 3986 #ifndef __BORLANDC__ 3987 3988 // ICE's in C++Builder. 3989 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), " kCaseB\n Which is: "); 3990 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: 42"); 3991 #endif 3992 3993 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: -1"); 3994 } 3995 3996 #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC) 3997 3998 #ifdef GTEST_OS_WINDOWS 3999 4000 static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; } 4001 4002 static HRESULT OkHRESULTSuccess() { return S_OK; } 4003 4004 static HRESULT FalseHRESULTSuccess() { return S_FALSE; } 4005 4006 // HRESULT assertion tests test both zero and non-zero 4007 // success codes as well as failure message for each. 4008 // 4009 // Windows CE doesn't support message texts. 4010 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) { 4011 EXPECT_HRESULT_SUCCEEDED(S_OK); 4012 EXPECT_HRESULT_SUCCEEDED(S_FALSE); 4013 4014 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), 4015 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" 4016 " Actual: 0x8000FFFF"); 4017 } 4018 4019 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) { 4020 ASSERT_HRESULT_SUCCEEDED(S_OK); 4021 ASSERT_HRESULT_SUCCEEDED(S_FALSE); 4022 4023 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), 4024 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" 4025 " Actual: 0x8000FFFF"); 4026 } 4027 4028 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) { 4029 EXPECT_HRESULT_FAILED(E_UNEXPECTED); 4030 4031 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()), 4032 "Expected: (OkHRESULTSuccess()) fails.\n" 4033 " Actual: 0x0"); 4034 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()), 4035 "Expected: (FalseHRESULTSuccess()) fails.\n" 4036 " Actual: 0x1"); 4037 } 4038 4039 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) { 4040 ASSERT_HRESULT_FAILED(E_UNEXPECTED); 4041 4042 #ifndef __BORLANDC__ 4043 4044 // ICE's in C++Builder 2007 and 2009. 4045 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()), 4046 "Expected: (OkHRESULTSuccess()) fails.\n" 4047 " Actual: 0x0"); 4048 #endif 4049 4050 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()), 4051 "Expected: (FalseHRESULTSuccess()) fails.\n" 4052 " Actual: 0x1"); 4053 } 4054 4055 // Tests that streaming to the HRESULT macros works. 4056 TEST(HRESULTAssertionTest, Streaming) { 4057 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; 4058 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; 4059 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; 4060 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; 4061 4062 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) 4063 << "expected failure", 4064 "expected failure"); 4065 4066 #ifndef __BORLANDC__ 4067 4068 // ICE's in C++Builder 2007 and 2009. 4069 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) 4070 << "expected failure", 4071 "expected failure"); 4072 #endif 4073 4074 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << "expected failure", 4075 "expected failure"); 4076 4077 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << "expected failure", 4078 "expected failure"); 4079 } 4080 4081 #endif // GTEST_OS_WINDOWS 4082 4083 // The following code intentionally tests a suboptimal syntax. 4084 #ifdef __GNUC__ 4085 #pragma GCC diagnostic push 4086 #pragma GCC diagnostic ignored "-Wdangling-else" 4087 #pragma GCC diagnostic ignored "-Wempty-body" 4088 #pragma GCC diagnostic ignored "-Wpragmas" 4089 #endif 4090 // Tests that the assertion macros behave like single statements. 4091 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) { 4092 if (AlwaysFalse()) 4093 ASSERT_TRUE(false) << "This should never be executed; " 4094 "It's a compilation test only."; 4095 4096 if (AlwaysTrue()) 4097 EXPECT_FALSE(false); 4098 else 4099 ; // NOLINT 4100 4101 if (AlwaysFalse()) ASSERT_LT(1, 3); 4102 4103 if (AlwaysFalse()) 4104 ; // NOLINT 4105 else 4106 EXPECT_GT(3, 2) << ""; 4107 } 4108 #ifdef __GNUC__ 4109 #pragma GCC diagnostic pop 4110 #endif 4111 4112 #if GTEST_HAS_EXCEPTIONS 4113 // Tests that the compiler will not complain about unreachable code in the 4114 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros. 4115 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { 4116 int n = 0; 4117 4118 EXPECT_THROW(throw 1, int); 4119 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), ""); 4120 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw n, const char*), ""); 4121 EXPECT_NO_THROW(n++); 4122 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), ""); 4123 EXPECT_ANY_THROW(throw 1); 4124 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), ""); 4125 } 4126 4127 TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) { 4128 EXPECT_THROW(throw std::exception(), std::exception); 4129 } 4130 4131 // The following code intentionally tests a suboptimal syntax. 4132 #ifdef __GNUC__ 4133 #pragma GCC diagnostic push 4134 #pragma GCC diagnostic ignored "-Wdangling-else" 4135 #pragma GCC diagnostic ignored "-Wempty-body" 4136 #pragma GCC diagnostic ignored "-Wpragmas" 4137 #endif 4138 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { 4139 if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool); 4140 4141 if (AlwaysTrue()) 4142 EXPECT_THROW(ThrowAnInteger(), int); 4143 else 4144 ; // NOLINT 4145 4146 if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger()); 4147 4148 if (AlwaysTrue()) 4149 EXPECT_NO_THROW(ThrowNothing()); 4150 else 4151 ; // NOLINT 4152 4153 if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing()); 4154 4155 if (AlwaysTrue()) 4156 EXPECT_ANY_THROW(ThrowAnInteger()); 4157 else 4158 ; // NOLINT 4159 } 4160 #ifdef __GNUC__ 4161 #pragma GCC diagnostic pop 4162 #endif 4163 4164 #endif // GTEST_HAS_EXCEPTIONS 4165 4166 // The following code intentionally tests a suboptimal syntax. 4167 #ifdef __GNUC__ 4168 #pragma GCC diagnostic push 4169 #pragma GCC diagnostic ignored "-Wdangling-else" 4170 #pragma GCC diagnostic ignored "-Wempty-body" 4171 #pragma GCC diagnostic ignored "-Wpragmas" 4172 #endif 4173 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) { 4174 if (AlwaysFalse()) 4175 EXPECT_NO_FATAL_FAILURE(FAIL()) 4176 << "This should never be executed. " << "It's a compilation test only."; 4177 else 4178 ; // NOLINT 4179 4180 if (AlwaysFalse()) 4181 ASSERT_NO_FATAL_FAILURE(FAIL()) << ""; 4182 else 4183 ; // NOLINT 4184 4185 if (AlwaysTrue()) 4186 EXPECT_NO_FATAL_FAILURE(SUCCEED()); 4187 else 4188 ; // NOLINT 4189 4190 if (AlwaysFalse()) 4191 ; // NOLINT 4192 else 4193 ASSERT_NO_FATAL_FAILURE(SUCCEED()); 4194 } 4195 #ifdef __GNUC__ 4196 #pragma GCC diagnostic pop 4197 #endif 4198 4199 // Tests that the assertion macros work well with switch statements. 4200 TEST(AssertionSyntaxTest, WorksWithSwitch) { 4201 switch (0) { 4202 case 1: 4203 break; 4204 default: 4205 ASSERT_TRUE(true); 4206 } 4207 4208 switch (0) 4209 case 0: 4210 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case"; 4211 4212 // Binary assertions are implemented using a different code path 4213 // than the Boolean assertions. Hence we test them separately. 4214 switch (0) { 4215 case 1: 4216 default: 4217 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler"; 4218 } 4219 4220 switch (0) 4221 case 0: 4222 EXPECT_NE(1, 2); 4223 } 4224 4225 #if GTEST_HAS_EXCEPTIONS 4226 4227 void ThrowAString() { throw "std::string"; } 4228 4229 // Test that the exception assertion macros compile and work with const 4230 // type qualifier. 4231 TEST(AssertionSyntaxTest, WorksWithConst) { 4232 ASSERT_THROW(ThrowAString(), const char*); 4233 4234 EXPECT_THROW(ThrowAString(), const char*); 4235 } 4236 4237 #endif // GTEST_HAS_EXCEPTIONS 4238 4239 } // namespace 4240 4241 namespace testing { 4242 4243 // Tests that Google Test tracks SUCCEED*. 4244 TEST(SuccessfulAssertionTest, SUCCEED) { 4245 SUCCEED(); 4246 SUCCEED() << "OK"; 4247 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count()); 4248 } 4249 4250 // Tests that Google Test doesn't track successful EXPECT_*. 4251 TEST(SuccessfulAssertionTest, EXPECT) { 4252 EXPECT_TRUE(true); 4253 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); 4254 } 4255 4256 // Tests that Google Test doesn't track successful EXPECT_STR*. 4257 TEST(SuccessfulAssertionTest, EXPECT_STR) { 4258 EXPECT_STREQ("", ""); 4259 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); 4260 } 4261 4262 // Tests that Google Test doesn't track successful ASSERT_*. 4263 TEST(SuccessfulAssertionTest, ASSERT) { 4264 ASSERT_TRUE(true); 4265 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); 4266 } 4267 4268 // Tests that Google Test doesn't track successful ASSERT_STR*. 4269 TEST(SuccessfulAssertionTest, ASSERT_STR) { 4270 ASSERT_STREQ("", ""); 4271 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); 4272 } 4273 4274 } // namespace testing 4275 4276 namespace { 4277 4278 // Tests the message streaming variation of assertions. 4279 4280 TEST(AssertionWithMessageTest, EXPECT) { 4281 EXPECT_EQ(1, 1) << "This should succeed."; 4282 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.", 4283 "Expected failure #1"); 4284 EXPECT_LE(1, 2) << "This should succeed."; 4285 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.", 4286 "Expected failure #2."); 4287 EXPECT_GE(1, 0) << "This should succeed."; 4288 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.", 4289 "Expected failure #3."); 4290 4291 EXPECT_STREQ("1", "1") << "This should succeed."; 4292 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.", 4293 "Expected failure #4."); 4294 EXPECT_STRCASEEQ("a", "A") << "This should succeed."; 4295 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.", 4296 "Expected failure #5."); 4297 4298 EXPECT_FLOAT_EQ(1, 1) << "This should succeed."; 4299 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.", 4300 "Expected failure #6."); 4301 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed."; 4302 } 4303 4304 TEST(AssertionWithMessageTest, ASSERT) { 4305 ASSERT_EQ(1, 1) << "This should succeed."; 4306 ASSERT_NE(1, 2) << "This should succeed."; 4307 ASSERT_LE(1, 2) << "This should succeed."; 4308 ASSERT_LT(1, 2) << "This should succeed."; 4309 ASSERT_GE(1, 0) << "This should succeed."; 4310 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.", 4311 "Expected failure."); 4312 } 4313 4314 TEST(AssertionWithMessageTest, ASSERT_STR) { 4315 ASSERT_STREQ("1", "1") << "This should succeed."; 4316 ASSERT_STRNE("1", "2") << "This should succeed."; 4317 ASSERT_STRCASEEQ("a", "A") << "This should succeed."; 4318 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.", 4319 "Expected failure."); 4320 } 4321 4322 TEST(AssertionWithMessageTest, ASSERT_FLOATING) { 4323 ASSERT_FLOAT_EQ(1, 1) << "This should succeed."; 4324 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed."; 4325 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT 4326 "Expect failure."); 4327 } 4328 4329 // Tests using ASSERT_FALSE with a streamed message. 4330 TEST(AssertionWithMessageTest, ASSERT_FALSE) { 4331 ASSERT_FALSE(false) << "This shouldn't fail."; 4332 EXPECT_FATAL_FAILURE( 4333 { // NOLINT 4334 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1 4335 << " evaluates to " << true; 4336 }, 4337 "Expected failure"); 4338 } 4339 4340 // Tests using FAIL with a streamed message. 4341 TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); } 4342 4343 // Tests using SUCCEED with a streamed message. 4344 TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; } 4345 4346 // Tests using ASSERT_TRUE with a streamed message. 4347 TEST(AssertionWithMessageTest, ASSERT_TRUE) { 4348 ASSERT_TRUE(true) << "This should succeed."; 4349 ASSERT_TRUE(true) << true; 4350 EXPECT_FATAL_FAILURE( 4351 { // NOLINT 4352 ASSERT_TRUE(false) << static_cast<const char*>(nullptr) 4353 << static_cast<char*>(nullptr); 4354 }, 4355 "(null)(null)"); 4356 } 4357 4358 #ifdef GTEST_OS_WINDOWS 4359 // Tests using wide strings in assertion messages. 4360 TEST(AssertionWithMessageTest, WideStringMessage) { 4361 EXPECT_NONFATAL_FAILURE( 4362 { // NOLINT 4363 EXPECT_TRUE(false) << L"This failure is expected.\x8119"; 4364 }, 4365 "This failure is expected."); 4366 EXPECT_FATAL_FAILURE( 4367 { // NOLINT 4368 ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120"; 4369 }, 4370 "This failure is expected too."); 4371 } 4372 #endif // GTEST_OS_WINDOWS 4373 4374 // Tests EXPECT_TRUE. 4375 TEST(ExpectTest, EXPECT_TRUE) { 4376 EXPECT_TRUE(true) << "Intentional success"; 4377 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.", 4378 "Intentional failure #1."); 4379 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.", 4380 "Intentional failure #2."); 4381 EXPECT_TRUE(2 > 1); // NOLINT 4382 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1), 4383 "Value of: 2 < 1\n" 4384 " Actual: false\n" 4385 "Expected: true"); 4386 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3"); 4387 } 4388 4389 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult. 4390 TEST(ExpectTest, ExpectTrueWithAssertionResult) { 4391 EXPECT_TRUE(ResultIsEven(2)); 4392 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)), 4393 "Value of: ResultIsEven(3)\n" 4394 " Actual: false (3 is odd)\n" 4395 "Expected: true"); 4396 EXPECT_TRUE(ResultIsEvenNoExplanation(2)); 4397 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)), 4398 "Value of: ResultIsEvenNoExplanation(3)\n" 4399 " Actual: false (3 is odd)\n" 4400 "Expected: true"); 4401 } 4402 4403 // Tests EXPECT_FALSE with a streamed message. 4404 TEST(ExpectTest, EXPECT_FALSE) { 4405 EXPECT_FALSE(2 < 1); // NOLINT 4406 EXPECT_FALSE(false) << "Intentional success"; 4407 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.", 4408 "Intentional failure #1."); 4409 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.", 4410 "Intentional failure #2."); 4411 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1), 4412 "Value of: 2 > 1\n" 4413 " Actual: true\n" 4414 "Expected: false"); 4415 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3"); 4416 } 4417 4418 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult. 4419 TEST(ExpectTest, ExpectFalseWithAssertionResult) { 4420 EXPECT_FALSE(ResultIsEven(3)); 4421 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)), 4422 "Value of: ResultIsEven(2)\n" 4423 " Actual: true (2 is even)\n" 4424 "Expected: false"); 4425 EXPECT_FALSE(ResultIsEvenNoExplanation(3)); 4426 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)), 4427 "Value of: ResultIsEvenNoExplanation(2)\n" 4428 " Actual: true\n" 4429 "Expected: false"); 4430 } 4431 4432 #ifdef __BORLANDC__ 4433 // Restores warnings after previous "#pragma option push" suppressed them 4434 #pragma option pop 4435 #endif 4436 4437 // Tests EXPECT_EQ. 4438 TEST(ExpectTest, EXPECT_EQ) { 4439 EXPECT_EQ(5, 2 + 3); 4440 // clang-format off 4441 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3), 4442 "Expected equality of these values:\n" 4443 " 5\n" 4444 " 2*3\n" 4445 " Which is: 6"); 4446 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3"); 4447 // clang-format on 4448 } 4449 4450 // Tests using EXPECT_EQ on double values. The purpose is to make 4451 // sure that the specialization we did for integer and anonymous enums 4452 // isn't used for double arguments. 4453 TEST(ExpectTest, EXPECT_EQ_Double) { 4454 // A success. 4455 EXPECT_EQ(5.6, 5.6); 4456 4457 // A failure. 4458 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1"); 4459 } 4460 4461 // Tests EXPECT_EQ(NULL, pointer). 4462 TEST(ExpectTest, EXPECT_EQ_NULL) { 4463 // A success. 4464 const char* p = nullptr; 4465 EXPECT_EQ(nullptr, p); 4466 4467 // A failure. 4468 int n = 0; 4469 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:"); 4470 } 4471 4472 // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be 4473 // treated as a null pointer by the compiler, we need to make sure 4474 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as 4475 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer). 4476 TEST(ExpectTest, EXPECT_EQ_0) { 4477 int n = 0; 4478 4479 // A success. 4480 EXPECT_EQ(0, n); 4481 4482 // A failure. 4483 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), " 0\n 5.6"); 4484 } 4485 4486 // Tests EXPECT_NE. 4487 TEST(ExpectTest, EXPECT_NE) { 4488 EXPECT_NE(6, 7); 4489 4490 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'), 4491 "Expected: ('a') != ('a'), " 4492 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); 4493 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2"); 4494 char* const p0 = nullptr; 4495 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0"); 4496 // Only way to get the Nokia compiler to compile the cast 4497 // is to have a separate void* variable first. Putting 4498 // the two casts on the same line doesn't work, neither does 4499 // a direct C-style to char*. 4500 void* pv1 = (void*)0x1234; // NOLINT 4501 char* const p1 = reinterpret_cast<char*>(pv1); 4502 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1"); 4503 } 4504 4505 // Tests EXPECT_LE. 4506 TEST(ExpectTest, EXPECT_LE) { 4507 EXPECT_LE(2, 3); 4508 EXPECT_LE(2, 2); 4509 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0), 4510 "Expected: (2) <= (0), actual: 2 vs 0"); 4511 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)"); 4512 } 4513 4514 // Tests EXPECT_LT. 4515 TEST(ExpectTest, EXPECT_LT) { 4516 EXPECT_LT(2, 3); 4517 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2), 4518 "Expected: (2) < (2), actual: 2 vs 2"); 4519 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)"); 4520 } 4521 4522 // Tests EXPECT_GE. 4523 TEST(ExpectTest, EXPECT_GE) { 4524 EXPECT_GE(2, 1); 4525 EXPECT_GE(2, 2); 4526 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3), 4527 "Expected: (2) >= (3), actual: 2 vs 3"); 4528 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)"); 4529 } 4530 4531 // Tests EXPECT_GT. 4532 TEST(ExpectTest, EXPECT_GT) { 4533 EXPECT_GT(2, 1); 4534 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2), 4535 "Expected: (2) > (2), actual: 2 vs 2"); 4536 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)"); 4537 } 4538 4539 #if GTEST_HAS_EXCEPTIONS 4540 4541 // Tests EXPECT_THROW. 4542 TEST(ExpectTest, EXPECT_THROW) { 4543 EXPECT_THROW(ThrowAnInteger(), int); 4544 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool), 4545 "Expected: ThrowAnInteger() throws an exception of " 4546 "type bool.\n Actual: it throws a different type."); 4547 EXPECT_NONFATAL_FAILURE( 4548 EXPECT_THROW(ThrowRuntimeError("A description"), std::logic_error), 4549 "Expected: ThrowRuntimeError(\"A description\") " 4550 "throws an exception of type std::logic_error.\n " 4551 "Actual: it throws " ERROR_DESC 4552 " " 4553 "with description \"A description\"."); 4554 EXPECT_NONFATAL_FAILURE( 4555 EXPECT_THROW(ThrowNothing(), bool), 4556 "Expected: ThrowNothing() throws an exception of type bool.\n" 4557 " Actual: it throws nothing."); 4558 } 4559 4560 // Tests EXPECT_NO_THROW. 4561 TEST(ExpectTest, EXPECT_NO_THROW) { 4562 EXPECT_NO_THROW(ThrowNothing()); 4563 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()), 4564 "Expected: ThrowAnInteger() doesn't throw an " 4565 "exception.\n Actual: it throws."); 4566 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")), 4567 "Expected: ThrowRuntimeError(\"A description\") " 4568 "doesn't throw an exception.\n " 4569 "Actual: it throws " ERROR_DESC 4570 " " 4571 "with description \"A description\"."); 4572 } 4573 4574 // Tests EXPECT_ANY_THROW. 4575 TEST(ExpectTest, EXPECT_ANY_THROW) { 4576 EXPECT_ANY_THROW(ThrowAnInteger()); 4577 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()), 4578 "Expected: ThrowNothing() throws an exception.\n" 4579 " Actual: it doesn't."); 4580 } 4581 4582 #endif // GTEST_HAS_EXCEPTIONS 4583 4584 // Make sure we deal with the precedence of <<. 4585 TEST(ExpectTest, ExpectPrecedence) { 4586 EXPECT_EQ(1 < 2, true); 4587 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false), 4588 " true && false\n Which is: false"); 4589 } 4590 4591 // Tests the StreamableToString() function. 4592 4593 // Tests using StreamableToString() on a scalar. 4594 TEST(StreamableToStringTest, Scalar) { 4595 EXPECT_STREQ("5", StreamableToString(5).c_str()); 4596 } 4597 4598 // Tests using StreamableToString() on a non-char pointer. 4599 TEST(StreamableToStringTest, Pointer) { 4600 int n = 0; 4601 int* p = &n; 4602 EXPECT_STRNE("(null)", StreamableToString(p).c_str()); 4603 } 4604 4605 // Tests using StreamableToString() on a NULL non-char pointer. 4606 TEST(StreamableToStringTest, NullPointer) { 4607 int* p = nullptr; 4608 EXPECT_STREQ("(null)", StreamableToString(p).c_str()); 4609 } 4610 4611 // Tests using StreamableToString() on a C string. 4612 TEST(StreamableToStringTest, CString) { 4613 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str()); 4614 } 4615 4616 // Tests using StreamableToString() on a NULL C string. 4617 TEST(StreamableToStringTest, NullCString) { 4618 char* p = nullptr; 4619 EXPECT_STREQ("(null)", StreamableToString(p).c_str()); 4620 } 4621 4622 // Tests using streamable values as assertion messages. 4623 4624 // Tests using std::string as an assertion message. 4625 TEST(StreamableTest, string) { 4626 static const std::string str( 4627 "This failure message is a std::string, and is expected."); 4628 EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str()); 4629 } 4630 4631 // Tests that we can output strings containing embedded NULs. 4632 // Limited to Linux because we can only do this with std::string's. 4633 TEST(StreamableTest, stringWithEmbeddedNUL) { 4634 static const char char_array_with_nul[] = 4635 "Here's a NUL\0 and some more string"; 4636 static const std::string string_with_nul( 4637 char_array_with_nul, 4638 sizeof(char_array_with_nul) - 1); // drops the trailing NUL 4639 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul, 4640 "Here's a NUL\\0 and some more string"); 4641 } 4642 4643 // Tests that we can output a NUL char. 4644 TEST(StreamableTest, NULChar) { 4645 EXPECT_FATAL_FAILURE( 4646 { // NOLINT 4647 FAIL() << "A NUL" << '\0' << " and some more string"; 4648 }, 4649 "A NUL\\0 and some more string"); 4650 } 4651 4652 // Tests using int as an assertion message. 4653 TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); } 4654 4655 // Tests using NULL char pointer as an assertion message. 4656 // 4657 // In MSVC, streaming a NULL char * causes access violation. Google Test 4658 // implemented a workaround (substituting "(null)" for NULL). This 4659 // tests whether the workaround works. 4660 TEST(StreamableTest, NullCharPtr) { 4661 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)"); 4662 } 4663 4664 // Tests that basic IO manipulators (endl, ends, and flush) can be 4665 // streamed to testing::Message. 4666 TEST(StreamableTest, BasicIoManip) { 4667 EXPECT_FATAL_FAILURE( 4668 { // NOLINT 4669 FAIL() << "Line 1." << std::endl 4670 << "A NUL char " << std::ends << std::flush << " in line 2."; 4671 }, 4672 "Line 1.\nA NUL char \\0 in line 2."); 4673 } 4674 4675 // Tests the macros that haven't been covered so far. 4676 4677 void AddFailureHelper(bool* aborted) { 4678 *aborted = true; 4679 ADD_FAILURE() << "Intentional failure."; 4680 *aborted = false; 4681 } 4682 4683 // Tests ADD_FAILURE. 4684 TEST(MacroTest, ADD_FAILURE) { 4685 bool aborted = true; 4686 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Intentional failure."); 4687 EXPECT_FALSE(aborted); 4688 } 4689 4690 // Tests ADD_FAILURE_AT. 4691 TEST(MacroTest, ADD_FAILURE_AT) { 4692 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and 4693 // the failure message contains the user-streamed part. 4694 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!"); 4695 4696 // Verifies that the user-streamed part is optional. 4697 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed"); 4698 4699 // Unfortunately, we cannot verify that the failure message contains 4700 // the right file path and line number the same way, as 4701 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and 4702 // line number. Instead, we do that in googletest-output-test_.cc. 4703 } 4704 4705 // Tests FAIL. 4706 TEST(MacroTest, FAIL) { 4707 EXPECT_FATAL_FAILURE(FAIL(), "Failed"); 4708 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.", 4709 "Intentional failure."); 4710 } 4711 4712 // Tests GTEST_FAIL_AT. 4713 TEST(MacroTest, GTEST_FAIL_AT) { 4714 // Verifies that GTEST_FAIL_AT does generate a fatal failure and 4715 // the failure message contains the user-streamed part. 4716 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!"); 4717 4718 // Verifies that the user-streamed part is optional. 4719 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed"); 4720 4721 // See the ADD_FAIL_AT test above to see how we test that the failure message 4722 // contains the right filename and line number -- the same applies here. 4723 } 4724 4725 // Tests SUCCEED 4726 TEST(MacroTest, SUCCEED) { 4727 SUCCEED(); 4728 SUCCEED() << "Explicit success."; 4729 } 4730 4731 // Tests for EXPECT_EQ() and ASSERT_EQ(). 4732 // 4733 // These tests fail *intentionally*, s.t. the failure messages can be 4734 // generated and tested. 4735 // 4736 // We have different tests for different argument types. 4737 4738 // Tests using bool values in {EXPECT|ASSERT}_EQ. 4739 TEST(EqAssertionTest, Bool) { 4740 EXPECT_EQ(true, true); 4741 EXPECT_FATAL_FAILURE( 4742 { 4743 bool false_value = false; 4744 ASSERT_EQ(false_value, true); 4745 }, 4746 " false_value\n Which is: false\n true"); 4747 } 4748 4749 // Tests using int values in {EXPECT|ASSERT}_EQ. 4750 TEST(EqAssertionTest, Int) { 4751 ASSERT_EQ(32, 32); 4752 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), " 32\n 33"); 4753 } 4754 4755 // Tests using time_t values in {EXPECT|ASSERT}_EQ. 4756 TEST(EqAssertionTest, Time_T) { 4757 EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0)); 4758 EXPECT_FATAL_FAILURE( 4759 ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), "1234"); 4760 } 4761 4762 // Tests using char values in {EXPECT|ASSERT}_EQ. 4763 TEST(EqAssertionTest, Char) { 4764 ASSERT_EQ('z', 'z'); 4765 const char ch = 'b'; 4766 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), " ch\n Which is: 'b'"); 4767 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), " ch\n Which is: 'b'"); 4768 } 4769 4770 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ. 4771 TEST(EqAssertionTest, WideChar) { 4772 EXPECT_EQ(L'b', L'b'); 4773 4774 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'), 4775 "Expected equality of these values:\n" 4776 " L'\0'\n" 4777 " Which is: L'\0' (0, 0x0)\n" 4778 " L'x'\n" 4779 " Which is: L'x' (120, 0x78)"); 4780 4781 static wchar_t wchar; 4782 wchar = L'b'; 4783 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar"); 4784 wchar = 0x8119; 4785 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar), 4786 " wchar\n Which is: L'"); 4787 } 4788 4789 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ. 4790 TEST(EqAssertionTest, StdString) { 4791 // Compares a const char* to an std::string that has identical 4792 // content. 4793 ASSERT_EQ("Test", ::std::string("Test")); 4794 4795 // Compares two identical std::strings. 4796 static const ::std::string str1("A * in the middle"); 4797 static const ::std::string str2(str1); 4798 EXPECT_EQ(str1, str2); 4799 4800 // Compares a const char* to an std::string that has different 4801 // content 4802 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "\"test\""); 4803 4804 // Compares an std::string to a char* that has different content. 4805 char* const p1 = const_cast<char*>("foo"); 4806 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1"); 4807 4808 // Compares two std::strings that have different contents, one of 4809 // which having a NUL character in the middle. This should fail. 4810 static ::std::string str3(str1); 4811 str3.at(2) = '\0'; 4812 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3), 4813 " str3\n Which is: \"A \\0 in the middle\""); 4814 } 4815 4816 #if GTEST_HAS_STD_WSTRING 4817 4818 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ. 4819 TEST(EqAssertionTest, StdWideString) { 4820 // Compares two identical std::wstrings. 4821 const ::std::wstring wstr1(L"A * in the middle"); 4822 const ::std::wstring wstr2(wstr1); 4823 ASSERT_EQ(wstr1, wstr2); 4824 4825 // Compares an std::wstring to a const wchar_t* that has identical 4826 // content. 4827 const wchar_t kTestX8119[] = {'T', 'e', 's', 't', 0x8119, '\0'}; 4828 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119); 4829 4830 // Compares an std::wstring to a const wchar_t* that has different 4831 // content. 4832 const wchar_t kTestX8120[] = {'T', 'e', 's', 't', 0x8120, '\0'}; 4833 EXPECT_NONFATAL_FAILURE( 4834 { // NOLINT 4835 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120); 4836 }, 4837 "kTestX8120"); 4838 4839 // Compares two std::wstrings that have different contents, one of 4840 // which having a NUL character in the middle. 4841 ::std::wstring wstr3(wstr1); 4842 wstr3.at(2) = L'\0'; 4843 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3"); 4844 4845 // Compares a wchar_t* to an std::wstring that has different 4846 // content. 4847 EXPECT_FATAL_FAILURE( 4848 { // NOLINT 4849 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar")); 4850 }, 4851 ""); 4852 } 4853 4854 #endif // GTEST_HAS_STD_WSTRING 4855 4856 // Tests using char pointers in {EXPECT|ASSERT}_EQ. 4857 TEST(EqAssertionTest, CharPointer) { 4858 char* const p0 = nullptr; 4859 // Only way to get the Nokia compiler to compile the cast 4860 // is to have a separate void* variable first. Putting 4861 // the two casts on the same line doesn't work, neither does 4862 // a direct C-style to char*. 4863 void* pv1 = (void*)0x1234; // NOLINT 4864 void* pv2 = (void*)0xABC0; // NOLINT 4865 char* const p1 = reinterpret_cast<char*>(pv1); 4866 char* const p2 = reinterpret_cast<char*>(pv2); 4867 ASSERT_EQ(p1, p1); 4868 4869 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:"); 4870 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:"); 4871 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234), 4872 reinterpret_cast<char*>(0xABC0)), 4873 "ABC0"); 4874 } 4875 4876 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ. 4877 TEST(EqAssertionTest, WideCharPointer) { 4878 wchar_t* const p0 = nullptr; 4879 // Only way to get the Nokia compiler to compile the cast 4880 // is to have a separate void* variable first. Putting 4881 // the two casts on the same line doesn't work, neither does 4882 // a direct C-style to char*. 4883 void* pv1 = (void*)0x1234; // NOLINT 4884 void* pv2 = (void*)0xABC0; // NOLINT 4885 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1); 4886 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2); 4887 EXPECT_EQ(p0, p0); 4888 4889 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:"); 4890 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:"); 4891 void* pv3 = (void*)0x1234; // NOLINT 4892 void* pv4 = (void*)0xABC0; // NOLINT 4893 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3); 4894 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4); 4895 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4"); 4896 } 4897 4898 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ. 4899 TEST(EqAssertionTest, OtherPointer) { 4900 ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr)); 4901 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr), 4902 reinterpret_cast<const int*>(0x1234)), 4903 "0x1234"); 4904 } 4905 4906 // A class that supports binary comparison operators but not streaming. 4907 class UnprintableChar { 4908 public: 4909 explicit UnprintableChar(char ch) : char_(ch) {} 4910 4911 bool operator==(const UnprintableChar& rhs) const { 4912 return char_ == rhs.char_; 4913 } 4914 bool operator!=(const UnprintableChar& rhs) const { 4915 return char_ != rhs.char_; 4916 } 4917 bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; } 4918 bool operator<=(const UnprintableChar& rhs) const { 4919 return char_ <= rhs.char_; 4920 } 4921 bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; } 4922 bool operator>=(const UnprintableChar& rhs) const { 4923 return char_ >= rhs.char_; 4924 } 4925 4926 private: 4927 char char_; 4928 }; 4929 4930 // Tests that ASSERT_EQ() and friends don't require the arguments to 4931 // be printable. 4932 TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) { 4933 const UnprintableChar x('x'), y('y'); 4934 ASSERT_EQ(x, x); 4935 EXPECT_NE(x, y); 4936 ASSERT_LT(x, y); 4937 EXPECT_LE(x, y); 4938 ASSERT_GT(y, x); 4939 EXPECT_GE(x, x); 4940 4941 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>"); 4942 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>"); 4943 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>"); 4944 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>"); 4945 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>"); 4946 4947 // Code tested by EXPECT_FATAL_FAILURE cannot reference local 4948 // variables, so we have to write UnprintableChar('x') instead of x. 4949 #ifndef __BORLANDC__ 4950 // ICE's in C++Builder. 4951 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')), 4952 "1-byte object <78>"); 4953 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), 4954 "1-byte object <78>"); 4955 #endif 4956 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), 4957 "1-byte object <79>"); 4958 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), 4959 "1-byte object <78>"); 4960 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), 4961 "1-byte object <79>"); 4962 } 4963 4964 // Tests the FRIEND_TEST macro. 4965 4966 // This class has a private member we want to test. We will test it 4967 // both in a TEST and in a TEST_F. 4968 class Foo { 4969 public: 4970 Foo() = default; 4971 4972 private: 4973 int Bar() const { return 1; } 4974 4975 // Declares the friend tests that can access the private member 4976 // Bar(). 4977 FRIEND_TEST(FRIEND_TEST_Test, TEST); 4978 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F); 4979 }; 4980 4981 // Tests that the FRIEND_TEST declaration allows a TEST to access a 4982 // class's private members. This should compile. 4983 TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); } 4984 4985 // The fixture needed to test using FRIEND_TEST with TEST_F. 4986 class FRIEND_TEST_Test2 : public Test { 4987 protected: 4988 Foo foo; 4989 }; 4990 4991 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a 4992 // class's private members. This should compile. 4993 TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); } 4994 4995 // Tests the life cycle of Test objects. 4996 4997 // The test fixture for testing the life cycle of Test objects. 4998 // 4999 // This class counts the number of live test objects that uses this 5000 // fixture. 5001 class TestLifeCycleTest : public Test { 5002 protected: 5003 // Constructor. Increments the number of test objects that uses 5004 // this fixture. 5005 TestLifeCycleTest() { count_++; } 5006 5007 // Destructor. Decrements the number of test objects that uses this 5008 // fixture. 5009 ~TestLifeCycleTest() override { count_--; } 5010 5011 // Returns the number of live test objects that uses this fixture. 5012 int count() const { return count_; } 5013 5014 private: 5015 static int count_; 5016 }; 5017 5018 int TestLifeCycleTest::count_ = 0; 5019 5020 // Tests the life cycle of test objects. 5021 TEST_F(TestLifeCycleTest, Test1) { 5022 // There should be only one test object in this test case that's 5023 // currently alive. 5024 ASSERT_EQ(1, count()); 5025 } 5026 5027 // Tests the life cycle of test objects. 5028 TEST_F(TestLifeCycleTest, Test2) { 5029 // After Test1 is done and Test2 is started, there should still be 5030 // only one live test object, as the object for Test1 should've been 5031 // deleted. 5032 ASSERT_EQ(1, count()); 5033 } 5034 5035 } // namespace 5036 5037 // Tests that the copy constructor works when it is NOT optimized away by 5038 // the compiler. 5039 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) { 5040 // Checks that the copy constructor doesn't try to dereference NULL pointers 5041 // in the source object. 5042 AssertionResult r1 = AssertionSuccess(); 5043 AssertionResult r2 = r1; 5044 // The following line is added to prevent the compiler from optimizing 5045 // away the constructor call. 5046 r1 << "abc"; 5047 5048 AssertionResult r3 = r1; 5049 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1)); 5050 EXPECT_STREQ("abc", r1.message()); 5051 } 5052 5053 // Tests that AssertionSuccess and AssertionFailure construct 5054 // AssertionResult objects as expected. 5055 TEST(AssertionResultTest, ConstructionWorks) { 5056 AssertionResult r1 = AssertionSuccess(); 5057 EXPECT_TRUE(r1); 5058 EXPECT_STREQ("", r1.message()); 5059 5060 AssertionResult r2 = AssertionSuccess() << "abc"; 5061 EXPECT_TRUE(r2); 5062 EXPECT_STREQ("abc", r2.message()); 5063 5064 AssertionResult r3 = AssertionFailure(); 5065 EXPECT_FALSE(r3); 5066 EXPECT_STREQ("", r3.message()); 5067 5068 AssertionResult r4 = AssertionFailure() << "def"; 5069 EXPECT_FALSE(r4); 5070 EXPECT_STREQ("def", r4.message()); 5071 5072 AssertionResult r5 = AssertionFailure(Message() << "ghi"); 5073 EXPECT_FALSE(r5); 5074 EXPECT_STREQ("ghi", r5.message()); 5075 } 5076 5077 // Tests that the negation flips the predicate result but keeps the message. 5078 TEST(AssertionResultTest, NegationWorks) { 5079 AssertionResult r1 = AssertionSuccess() << "abc"; 5080 EXPECT_FALSE(!r1); 5081 EXPECT_STREQ("abc", (!r1).message()); 5082 5083 AssertionResult r2 = AssertionFailure() << "def"; 5084 EXPECT_TRUE(!r2); 5085 EXPECT_STREQ("def", (!r2).message()); 5086 } 5087 5088 TEST(AssertionResultTest, StreamingWorks) { 5089 AssertionResult r = AssertionSuccess(); 5090 r << "abc" << 'd' << 0 << true; 5091 EXPECT_STREQ("abcd0true", r.message()); 5092 } 5093 5094 TEST(AssertionResultTest, CanStreamOstreamManipulators) { 5095 AssertionResult r = AssertionSuccess(); 5096 r << "Data" << std::endl << std::flush << std::ends << "Will be visible"; 5097 EXPECT_STREQ("Data\n\\0Will be visible", r.message()); 5098 } 5099 5100 // The next test uses explicit conversion operators 5101 5102 TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) { 5103 struct ExplicitlyConvertibleToBool { 5104 explicit operator bool() const { return value; } 5105 bool value; 5106 }; 5107 ExplicitlyConvertibleToBool v1 = {false}; 5108 ExplicitlyConvertibleToBool v2 = {true}; 5109 EXPECT_FALSE(v1); 5110 EXPECT_TRUE(v2); 5111 } 5112 5113 struct ConvertibleToAssertionResult { 5114 operator AssertionResult() const { return AssertionResult(true); } 5115 }; 5116 5117 TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) { 5118 ConvertibleToAssertionResult obj; 5119 EXPECT_TRUE(obj); 5120 } 5121 5122 // Tests streaming a user type whose definition and operator << are 5123 // both in the global namespace. 5124 class Base { 5125 public: 5126 explicit Base(int an_x) : x_(an_x) {} 5127 int x() const { return x_; } 5128 5129 private: 5130 int x_; 5131 }; 5132 std::ostream& operator<<(std::ostream& os, const Base& val) { 5133 return os << val.x(); 5134 } 5135 std::ostream& operator<<(std::ostream& os, const Base* pointer) { 5136 return os << "(" << pointer->x() << ")"; 5137 } 5138 5139 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) { 5140 Message msg; 5141 Base a(1); 5142 5143 msg << a << &a; // Uses ::operator<<. 5144 EXPECT_STREQ("1(1)", msg.GetString().c_str()); 5145 } 5146 5147 // Tests streaming a user type whose definition and operator<< are 5148 // both in an unnamed namespace. 5149 namespace { 5150 class MyTypeInUnnamedNameSpace : public Base { 5151 public: 5152 explicit MyTypeInUnnamedNameSpace(int an_x) : Base(an_x) {} 5153 }; 5154 std::ostream& operator<<(std::ostream& os, 5155 const MyTypeInUnnamedNameSpace& val) { 5156 return os << val.x(); 5157 } 5158 std::ostream& operator<<(std::ostream& os, 5159 const MyTypeInUnnamedNameSpace* pointer) { 5160 return os << "(" << pointer->x() << ")"; 5161 } 5162 } // namespace 5163 5164 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) { 5165 Message msg; 5166 MyTypeInUnnamedNameSpace a(1); 5167 5168 msg << a << &a; // Uses <unnamed_namespace>::operator<<. 5169 EXPECT_STREQ("1(1)", msg.GetString().c_str()); 5170 } 5171 5172 // Tests streaming a user type whose definition and operator<< are 5173 // both in a user namespace. 5174 namespace namespace1 { 5175 class MyTypeInNameSpace1 : public Base { 5176 public: 5177 explicit MyTypeInNameSpace1(int an_x) : Base(an_x) {} 5178 }; 5179 std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) { 5180 return os << val.x(); 5181 } 5182 std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) { 5183 return os << "(" << pointer->x() << ")"; 5184 } 5185 } // namespace namespace1 5186 5187 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) { 5188 Message msg; 5189 namespace1::MyTypeInNameSpace1 a(1); 5190 5191 msg << a << &a; // Uses namespace1::operator<<. 5192 EXPECT_STREQ("1(1)", msg.GetString().c_str()); 5193 } 5194 5195 // Tests streaming a user type whose definition is in a user namespace 5196 // but whose operator<< is in the global namespace. 5197 namespace namespace2 { 5198 class MyTypeInNameSpace2 : public ::Base { 5199 public: 5200 explicit MyTypeInNameSpace2(int an_x) : Base(an_x) {} 5201 }; 5202 } // namespace namespace2 5203 std::ostream& operator<<(std::ostream& os, 5204 const namespace2::MyTypeInNameSpace2& val) { 5205 return os << val.x(); 5206 } 5207 std::ostream& operator<<(std::ostream& os, 5208 const namespace2::MyTypeInNameSpace2* pointer) { 5209 return os << "(" << pointer->x() << ")"; 5210 } 5211 5212 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) { 5213 Message msg; 5214 namespace2::MyTypeInNameSpace2 a(1); 5215 5216 msg << a << &a; // Uses ::operator<<. 5217 EXPECT_STREQ("1(1)", msg.GetString().c_str()); 5218 } 5219 5220 // Tests streaming NULL pointers to testing::Message. 5221 TEST(MessageTest, NullPointers) { 5222 Message msg; 5223 char* const p1 = nullptr; 5224 unsigned char* const p2 = nullptr; 5225 int* p3 = nullptr; 5226 double* p4 = nullptr; 5227 bool* p5 = nullptr; 5228 Message* p6 = nullptr; 5229 5230 msg << p1 << p2 << p3 << p4 << p5 << p6; 5231 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str()); 5232 } 5233 5234 // Tests streaming wide strings to testing::Message. 5235 TEST(MessageTest, WideStrings) { 5236 // Streams a NULL of type const wchar_t*. 5237 const wchar_t* const_wstr = nullptr; 5238 EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str()); 5239 5240 // Streams a NULL of type wchar_t*. 5241 wchar_t* wstr = nullptr; 5242 EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str()); 5243 5244 // Streams a non-NULL of type const wchar_t*. 5245 const_wstr = L"abc\x8119"; 5246 EXPECT_STREQ("abc\xe8\x84\x99", 5247 (Message() << const_wstr).GetString().c_str()); 5248 5249 // Streams a non-NULL of type wchar_t*. 5250 wstr = const_cast<wchar_t*>(const_wstr); 5251 EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str()); 5252 } 5253 5254 // This line tests that we can define tests in the testing namespace. 5255 namespace testing { 5256 5257 // Tests the TestInfo class. 5258 5259 class TestInfoTest : public Test { 5260 protected: 5261 static const TestInfo* GetTestInfo(const char* test_name) { 5262 const TestSuite* const test_suite = 5263 GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr); 5264 5265 for (int i = 0; i < test_suite->total_test_count(); ++i) { 5266 const TestInfo* const test_info = test_suite->GetTestInfo(i); 5267 if (strcmp(test_name, test_info->name()) == 0) return test_info; 5268 } 5269 return nullptr; 5270 } 5271 5272 static const TestResult* GetTestResult(const TestInfo* test_info) { 5273 return test_info->result(); 5274 } 5275 }; 5276 5277 // Tests TestInfo::test_case_name() and TestInfo::name(). 5278 TEST_F(TestInfoTest, Names) { 5279 const TestInfo* const test_info = GetTestInfo("Names"); 5280 5281 ASSERT_STREQ("TestInfoTest", test_info->test_suite_name()); 5282 ASSERT_STREQ("Names", test_info->name()); 5283 } 5284 5285 // Tests TestInfo::result(). 5286 TEST_F(TestInfoTest, result) { 5287 const TestInfo* const test_info = GetTestInfo("result"); 5288 5289 // Initially, there is no TestPartResult for this test. 5290 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); 5291 5292 // After the previous assertion, there is still none. 5293 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); 5294 } 5295 5296 #define VERIFY_CODE_LOCATION \ 5297 const int expected_line = __LINE__ - 1; \ 5298 const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \ 5299 ASSERT_TRUE(test_info); \ 5300 EXPECT_STREQ(__FILE__, test_info->file()); \ 5301 EXPECT_EQ(expected_line, test_info->line()) 5302 5303 // clang-format off 5304 TEST(CodeLocationForTEST, Verify) { 5305 VERIFY_CODE_LOCATION; 5306 } 5307 5308 class CodeLocationForTESTF : public Test {}; 5309 5310 TEST_F(CodeLocationForTESTF, Verify) { 5311 VERIFY_CODE_LOCATION; 5312 } 5313 5314 class CodeLocationForTESTP : public TestWithParam<int> {}; 5315 5316 TEST_P(CodeLocationForTESTP, Verify) { 5317 VERIFY_CODE_LOCATION; 5318 } 5319 5320 INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0)); 5321 5322 template <typename T> 5323 class CodeLocationForTYPEDTEST : public Test {}; 5324 5325 TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int); 5326 5327 TYPED_TEST(CodeLocationForTYPEDTEST, Verify) { 5328 VERIFY_CODE_LOCATION; 5329 } 5330 5331 template <typename T> 5332 class CodeLocationForTYPEDTESTP : public Test {}; 5333 5334 TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP); 5335 5336 TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) { 5337 VERIFY_CODE_LOCATION; 5338 } 5339 5340 REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify); 5341 5342 INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int); 5343 5344 #undef VERIFY_CODE_LOCATION 5345 // clang-format on 5346 5347 // Tests setting up and tearing down a test case. 5348 // Legacy API is deprecated but still available 5349 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 5350 class SetUpTestCaseTest : public Test { 5351 protected: 5352 // This will be called once before the first test in this test case 5353 // is run. 5354 static void SetUpTestCase() { 5355 printf("Setting up the test case . . .\n"); 5356 5357 // Initializes some shared resource. In this simple example, we 5358 // just create a C string. More complex stuff can be done if 5359 // desired. 5360 shared_resource_ = "123"; 5361 5362 // Increments the number of test cases that have been set up. 5363 counter_++; 5364 5365 // SetUpTestCase() should be called only once. 5366 EXPECT_EQ(1, counter_); 5367 } 5368 5369 // This will be called once after the last test in this test case is 5370 // run. 5371 static void TearDownTestCase() { 5372 printf("Tearing down the test case . . .\n"); 5373 5374 // Decrements the number of test cases that have been set up. 5375 counter_--; 5376 5377 // TearDownTestCase() should be called only once. 5378 EXPECT_EQ(0, counter_); 5379 5380 // Cleans up the shared resource. 5381 shared_resource_ = nullptr; 5382 } 5383 5384 // This will be called before each test in this test case. 5385 void SetUp() override { 5386 // SetUpTestCase() should be called only once, so counter_ should 5387 // always be 1. 5388 EXPECT_EQ(1, counter_); 5389 } 5390 5391 // Number of test cases that have been set up. 5392 static int counter_; 5393 5394 // Some resource to be shared by all tests in this test case. 5395 static const char* shared_resource_; 5396 }; 5397 5398 int SetUpTestCaseTest::counter_ = 0; 5399 const char* SetUpTestCaseTest::shared_resource_ = nullptr; 5400 5401 // A test that uses the shared resource. 5402 TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); } 5403 5404 // Another test that uses the shared resource. 5405 TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); } 5406 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 5407 5408 // Tests SetupTestSuite/TearDown TestSuite 5409 class SetUpTestSuiteTest : public Test { 5410 protected: 5411 // This will be called once before the first test in this test case 5412 // is run. 5413 static void SetUpTestSuite() { 5414 printf("Setting up the test suite . . .\n"); 5415 5416 // Initializes some shared resource. In this simple example, we 5417 // just create a C string. More complex stuff can be done if 5418 // desired. 5419 shared_resource_ = "123"; 5420 5421 // Increments the number of test cases that have been set up. 5422 counter_++; 5423 5424 // SetUpTestSuite() should be called only once. 5425 EXPECT_EQ(1, counter_); 5426 } 5427 5428 // This will be called once after the last test in this test case is 5429 // run. 5430 static void TearDownTestSuite() { 5431 printf("Tearing down the test suite . . .\n"); 5432 5433 // Decrements the number of test suites that have been set up. 5434 counter_--; 5435 5436 // TearDownTestSuite() should be called only once. 5437 EXPECT_EQ(0, counter_); 5438 5439 // Cleans up the shared resource. 5440 shared_resource_ = nullptr; 5441 } 5442 5443 // This will be called before each test in this test case. 5444 void SetUp() override { 5445 // SetUpTestSuite() should be called only once, so counter_ should 5446 // always be 1. 5447 EXPECT_EQ(1, counter_); 5448 } 5449 5450 // Number of test suites that have been set up. 5451 static int counter_; 5452 5453 // Some resource to be shared by all tests in this test case. 5454 static const char* shared_resource_; 5455 }; 5456 5457 int SetUpTestSuiteTest::counter_ = 0; 5458 const char* SetUpTestSuiteTest::shared_resource_ = nullptr; 5459 5460 // A test that uses the shared resource. 5461 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) { 5462 EXPECT_STRNE(nullptr, shared_resource_); 5463 } 5464 5465 // Another test that uses the shared resource. 5466 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) { 5467 EXPECT_STREQ("123", shared_resource_); 5468 } 5469 5470 // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly. 5471 5472 // The Flags struct stores a copy of all Google Test flags. 5473 struct Flags { 5474 // Constructs a Flags struct where each flag has its default value. 5475 Flags() 5476 : also_run_disabled_tests(false), 5477 break_on_failure(false), 5478 catch_exceptions(false), 5479 death_test_use_fork(false), 5480 fail_fast(false), 5481 filter(""), 5482 list_tests(false), 5483 output(""), 5484 brief(false), 5485 print_time(true), 5486 random_seed(0), 5487 repeat(1), 5488 recreate_environments_when_repeating(true), 5489 shuffle(false), 5490 stack_trace_depth(kMaxStackTraceDepth), 5491 stream_result_to(""), 5492 throw_on_failure(false) {} 5493 5494 // Factory methods. 5495 5496 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has 5497 // the given value. 5498 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) { 5499 Flags flags; 5500 flags.also_run_disabled_tests = also_run_disabled_tests; 5501 return flags; 5502 } 5503 5504 // Creates a Flags struct where the gtest_break_on_failure flag has 5505 // the given value. 5506 static Flags BreakOnFailure(bool break_on_failure) { 5507 Flags flags; 5508 flags.break_on_failure = break_on_failure; 5509 return flags; 5510 } 5511 5512 // Creates a Flags struct where the gtest_catch_exceptions flag has 5513 // the given value. 5514 static Flags CatchExceptions(bool catch_exceptions) { 5515 Flags flags; 5516 flags.catch_exceptions = catch_exceptions; 5517 return flags; 5518 } 5519 5520 // Creates a Flags struct where the gtest_death_test_use_fork flag has 5521 // the given value. 5522 static Flags DeathTestUseFork(bool death_test_use_fork) { 5523 Flags flags; 5524 flags.death_test_use_fork = death_test_use_fork; 5525 return flags; 5526 } 5527 5528 // Creates a Flags struct where the gtest_fail_fast flag has 5529 // the given value. 5530 static Flags FailFast(bool fail_fast) { 5531 Flags flags; 5532 flags.fail_fast = fail_fast; 5533 return flags; 5534 } 5535 5536 // Creates a Flags struct where the gtest_filter flag has the given 5537 // value. 5538 static Flags Filter(const char* filter) { 5539 Flags flags; 5540 flags.filter = filter; 5541 return flags; 5542 } 5543 5544 // Creates a Flags struct where the gtest_list_tests flag has the 5545 // given value. 5546 static Flags ListTests(bool list_tests) { 5547 Flags flags; 5548 flags.list_tests = list_tests; 5549 return flags; 5550 } 5551 5552 // Creates a Flags struct where the gtest_output flag has the given 5553 // value. 5554 static Flags Output(const char* output) { 5555 Flags flags; 5556 flags.output = output; 5557 return flags; 5558 } 5559 5560 // Creates a Flags struct where the gtest_brief flag has the given 5561 // value. 5562 static Flags Brief(bool brief) { 5563 Flags flags; 5564 flags.brief = brief; 5565 return flags; 5566 } 5567 5568 // Creates a Flags struct where the gtest_print_time flag has the given 5569 // value. 5570 static Flags PrintTime(bool print_time) { 5571 Flags flags; 5572 flags.print_time = print_time; 5573 return flags; 5574 } 5575 5576 // Creates a Flags struct where the gtest_random_seed flag has the given 5577 // value. 5578 static Flags RandomSeed(int32_t random_seed) { 5579 Flags flags; 5580 flags.random_seed = random_seed; 5581 return flags; 5582 } 5583 5584 // Creates a Flags struct where the gtest_repeat flag has the given 5585 // value. 5586 static Flags Repeat(int32_t repeat) { 5587 Flags flags; 5588 flags.repeat = repeat; 5589 return flags; 5590 } 5591 5592 // Creates a Flags struct where the gtest_recreate_environments_when_repeating 5593 // flag has the given value. 5594 static Flags RecreateEnvironmentsWhenRepeating( 5595 bool recreate_environments_when_repeating) { 5596 Flags flags; 5597 flags.recreate_environments_when_repeating = 5598 recreate_environments_when_repeating; 5599 return flags; 5600 } 5601 5602 // Creates a Flags struct where the gtest_shuffle flag has the given 5603 // value. 5604 static Flags Shuffle(bool shuffle) { 5605 Flags flags; 5606 flags.shuffle = shuffle; 5607 return flags; 5608 } 5609 5610 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has 5611 // the given value. 5612 static Flags StackTraceDepth(int32_t stack_trace_depth) { 5613 Flags flags; 5614 flags.stack_trace_depth = stack_trace_depth; 5615 return flags; 5616 } 5617 5618 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has 5619 // the given value. 5620 static Flags StreamResultTo(const char* stream_result_to) { 5621 Flags flags; 5622 flags.stream_result_to = stream_result_to; 5623 return flags; 5624 } 5625 5626 // Creates a Flags struct where the gtest_throw_on_failure flag has 5627 // the given value. 5628 static Flags ThrowOnFailure(bool throw_on_failure) { 5629 Flags flags; 5630 flags.throw_on_failure = throw_on_failure; 5631 return flags; 5632 } 5633 5634 // These fields store the flag values. 5635 bool also_run_disabled_tests; 5636 bool break_on_failure; 5637 bool catch_exceptions; 5638 bool death_test_use_fork; 5639 bool fail_fast; 5640 const char* filter; 5641 bool list_tests; 5642 const char* output; 5643 bool brief; 5644 bool print_time; 5645 int32_t random_seed; 5646 int32_t repeat; 5647 bool recreate_environments_when_repeating; 5648 bool shuffle; 5649 int32_t stack_trace_depth; 5650 const char* stream_result_to; 5651 bool throw_on_failure; 5652 }; 5653 5654 // Fixture for testing ParseGoogleTestFlagsOnly(). 5655 class ParseFlagsTest : public Test { 5656 protected: 5657 // Clears the flags before each test. 5658 void SetUp() override { 5659 GTEST_FLAG_SET(also_run_disabled_tests, false); 5660 GTEST_FLAG_SET(break_on_failure, false); 5661 GTEST_FLAG_SET(catch_exceptions, false); 5662 GTEST_FLAG_SET(death_test_use_fork, false); 5663 GTEST_FLAG_SET(fail_fast, false); 5664 GTEST_FLAG_SET(filter, ""); 5665 GTEST_FLAG_SET(list_tests, false); 5666 GTEST_FLAG_SET(output, ""); 5667 GTEST_FLAG_SET(brief, false); 5668 GTEST_FLAG_SET(print_time, true); 5669 GTEST_FLAG_SET(random_seed, 0); 5670 GTEST_FLAG_SET(repeat, 1); 5671 GTEST_FLAG_SET(recreate_environments_when_repeating, true); 5672 GTEST_FLAG_SET(shuffle, false); 5673 GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth); 5674 GTEST_FLAG_SET(stream_result_to, ""); 5675 GTEST_FLAG_SET(throw_on_failure, false); 5676 } 5677 5678 // Asserts that two narrow or wide string arrays are equal. 5679 template <typename CharType> 5680 static void AssertStringArrayEq(int size1, CharType** array1, int size2, 5681 CharType** array2) { 5682 ASSERT_EQ(size1, size2) << " Array sizes different."; 5683 5684 for (int i = 0; i != size1; i++) { 5685 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i; 5686 } 5687 } 5688 5689 // Verifies that the flag values match the expected values. 5690 static void CheckFlags(const Flags& expected) { 5691 EXPECT_EQ(expected.also_run_disabled_tests, 5692 GTEST_FLAG_GET(also_run_disabled_tests)); 5693 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure)); 5694 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions)); 5695 EXPECT_EQ(expected.death_test_use_fork, 5696 GTEST_FLAG_GET(death_test_use_fork)); 5697 EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast)); 5698 EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str()); 5699 EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests)); 5700 EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str()); 5701 EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief)); 5702 EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time)); 5703 EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed)); 5704 EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat)); 5705 EXPECT_EQ(expected.recreate_environments_when_repeating, 5706 GTEST_FLAG_GET(recreate_environments_when_repeating)); 5707 EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle)); 5708 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth)); 5709 EXPECT_STREQ(expected.stream_result_to, 5710 GTEST_FLAG_GET(stream_result_to).c_str()); 5711 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure)); 5712 } 5713 5714 // Parses a command line (specified by argc1 and argv1), then 5715 // verifies that the flag values are expected and that the 5716 // recognized flags are removed from the command line. 5717 template <typename CharType> 5718 static void TestParsingFlags(int argc1, const CharType** argv1, int argc2, 5719 const CharType** argv2, const Flags& expected, 5720 bool should_print_help) { 5721 const bool saved_help_flag = ::testing::internal::g_help_flag; 5722 ::testing::internal::g_help_flag = false; 5723 5724 #if GTEST_HAS_STREAM_REDIRECTION 5725 CaptureStdout(); 5726 #endif 5727 5728 // Parses the command line. 5729 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1)); 5730 5731 #if GTEST_HAS_STREAM_REDIRECTION 5732 const std::string captured_stdout = GetCapturedStdout(); 5733 #endif 5734 5735 // Verifies the flag values. 5736 CheckFlags(expected); 5737 5738 // Verifies that the recognized flags are removed from the command 5739 // line. 5740 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2); 5741 5742 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the 5743 // help message for the flags it recognizes. 5744 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag); 5745 5746 #if GTEST_HAS_STREAM_REDIRECTION 5747 const char* const expected_help_fragment = 5748 "This program contains tests written using"; 5749 if (should_print_help) { 5750 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout); 5751 } else { 5752 EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment, 5753 captured_stdout); 5754 } 5755 #endif // GTEST_HAS_STREAM_REDIRECTION 5756 5757 ::testing::internal::g_help_flag = saved_help_flag; 5758 } 5759 5760 // This macro wraps TestParsingFlags s.t. the user doesn't need 5761 // to specify the array sizes. 5762 5763 #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ 5764 TestParsingFlags(sizeof(argv1) / sizeof(*argv1) - 1, argv1, \ 5765 sizeof(argv2) / sizeof(*argv2) - 1, argv2, expected, \ 5766 should_print_help) 5767 }; 5768 5769 // Tests parsing an empty command line. 5770 TEST_F(ParseFlagsTest, Empty) { 5771 const char* argv[] = {nullptr}; 5772 5773 const char* argv2[] = {nullptr}; 5774 5775 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); 5776 } 5777 5778 // Tests parsing a command line that has no flag. 5779 TEST_F(ParseFlagsTest, NoFlag) { 5780 const char* argv[] = {"foo.exe", nullptr}; 5781 5782 const char* argv2[] = {"foo.exe", nullptr}; 5783 5784 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); 5785 } 5786 5787 // Tests parsing --gtest_fail_fast. 5788 TEST_F(ParseFlagsTest, FailFast) { 5789 const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr}; 5790 5791 const char* argv2[] = {"foo.exe", nullptr}; 5792 5793 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false); 5794 } 5795 5796 // Tests parsing an empty --gtest_filter flag. 5797 TEST_F(ParseFlagsTest, FilterEmpty) { 5798 const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr}; 5799 5800 const char* argv2[] = {"foo.exe", nullptr}; 5801 5802 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false); 5803 } 5804 5805 // Tests parsing a non-empty --gtest_filter flag. 5806 TEST_F(ParseFlagsTest, FilterNonEmpty) { 5807 const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr}; 5808 5809 const char* argv2[] = {"foo.exe", nullptr}; 5810 5811 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); 5812 } 5813 5814 // Tests parsing --gtest_break_on_failure. 5815 TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) { 5816 const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr}; 5817 5818 const char* argv2[] = {"foo.exe", nullptr}; 5819 5820 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); 5821 } 5822 5823 // Tests parsing --gtest_break_on_failure=0. 5824 TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) { 5825 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr}; 5826 5827 const char* argv2[] = {"foo.exe", nullptr}; 5828 5829 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); 5830 } 5831 5832 // Tests parsing --gtest_break_on_failure=f. 5833 TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) { 5834 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr}; 5835 5836 const char* argv2[] = {"foo.exe", nullptr}; 5837 5838 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); 5839 } 5840 5841 // Tests parsing --gtest_break_on_failure=F. 5842 TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) { 5843 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr}; 5844 5845 const char* argv2[] = {"foo.exe", nullptr}; 5846 5847 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); 5848 } 5849 5850 // Tests parsing a --gtest_break_on_failure flag that has a "true" 5851 // definition. 5852 TEST_F(ParseFlagsTest, BreakOnFailureTrue) { 5853 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr}; 5854 5855 const char* argv2[] = {"foo.exe", nullptr}; 5856 5857 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); 5858 } 5859 5860 // Tests parsing --gtest_catch_exceptions. 5861 TEST_F(ParseFlagsTest, CatchExceptions) { 5862 const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr}; 5863 5864 const char* argv2[] = {"foo.exe", nullptr}; 5865 5866 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false); 5867 } 5868 5869 // Tests parsing --gtest_death_test_use_fork. 5870 TEST_F(ParseFlagsTest, DeathTestUseFork) { 5871 const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr}; 5872 5873 const char* argv2[] = {"foo.exe", nullptr}; 5874 5875 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false); 5876 } 5877 5878 // Tests having the same flag twice with different values. The 5879 // expected behavior is that the one coming last takes precedence. 5880 TEST_F(ParseFlagsTest, DuplicatedFlags) { 5881 const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b", 5882 nullptr}; 5883 5884 const char* argv2[] = {"foo.exe", nullptr}; 5885 5886 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false); 5887 } 5888 5889 // Tests having an unrecognized flag on the command line. 5890 TEST_F(ParseFlagsTest, UnrecognizedFlag) { 5891 const char* argv[] = {"foo.exe", "--gtest_break_on_failure", 5892 "bar", // Unrecognized by Google Test. 5893 "--gtest_filter=b", nullptr}; 5894 5895 const char* argv2[] = {"foo.exe", "bar", nullptr}; 5896 5897 Flags flags; 5898 flags.break_on_failure = true; 5899 flags.filter = "b"; 5900 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false); 5901 } 5902 5903 // Tests having a --gtest_list_tests flag 5904 TEST_F(ParseFlagsTest, ListTestsFlag) { 5905 const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr}; 5906 5907 const char* argv2[] = {"foo.exe", nullptr}; 5908 5909 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); 5910 } 5911 5912 // Tests having a --gtest_list_tests flag with a "true" value 5913 TEST_F(ParseFlagsTest, ListTestsTrue) { 5914 const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr}; 5915 5916 const char* argv2[] = {"foo.exe", nullptr}; 5917 5918 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); 5919 } 5920 5921 // Tests having a --gtest_list_tests flag with a "false" value 5922 TEST_F(ParseFlagsTest, ListTestsFalse) { 5923 const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr}; 5924 5925 const char* argv2[] = {"foo.exe", nullptr}; 5926 5927 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); 5928 } 5929 5930 // Tests parsing --gtest_list_tests=f. 5931 TEST_F(ParseFlagsTest, ListTestsFalse_f) { 5932 const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr}; 5933 5934 const char* argv2[] = {"foo.exe", nullptr}; 5935 5936 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); 5937 } 5938 5939 // Tests parsing --gtest_list_tests=F. 5940 TEST_F(ParseFlagsTest, ListTestsFalse_F) { 5941 const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr}; 5942 5943 const char* argv2[] = {"foo.exe", nullptr}; 5944 5945 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); 5946 } 5947 5948 // Tests parsing --gtest_output=xml 5949 TEST_F(ParseFlagsTest, OutputXml) { 5950 const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr}; 5951 5952 const char* argv2[] = {"foo.exe", nullptr}; 5953 5954 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false); 5955 } 5956 5957 // Tests parsing --gtest_output=xml:file 5958 TEST_F(ParseFlagsTest, OutputXmlFile) { 5959 const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr}; 5960 5961 const char* argv2[] = {"foo.exe", nullptr}; 5962 5963 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false); 5964 } 5965 5966 // Tests parsing --gtest_output=xml:directory/path/ 5967 TEST_F(ParseFlagsTest, OutputXmlDirectory) { 5968 const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/", 5969 nullptr}; 5970 5971 const char* argv2[] = {"foo.exe", nullptr}; 5972 5973 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"), 5974 false); 5975 } 5976 5977 // Tests having a --gtest_brief flag 5978 TEST_F(ParseFlagsTest, BriefFlag) { 5979 const char* argv[] = {"foo.exe", "--gtest_brief", nullptr}; 5980 5981 const char* argv2[] = {"foo.exe", nullptr}; 5982 5983 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false); 5984 } 5985 5986 // Tests having a --gtest_brief flag with a "true" value 5987 TEST_F(ParseFlagsTest, BriefFlagTrue) { 5988 const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr}; 5989 5990 const char* argv2[] = {"foo.exe", nullptr}; 5991 5992 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false); 5993 } 5994 5995 // Tests having a --gtest_brief flag with a "false" value 5996 TEST_F(ParseFlagsTest, BriefFlagFalse) { 5997 const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr}; 5998 5999 const char* argv2[] = {"foo.exe", nullptr}; 6000 6001 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false); 6002 } 6003 6004 // Tests having a --gtest_print_time flag 6005 TEST_F(ParseFlagsTest, PrintTimeFlag) { 6006 const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr}; 6007 6008 const char* argv2[] = {"foo.exe", nullptr}; 6009 6010 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); 6011 } 6012 6013 // Tests having a --gtest_print_time flag with a "true" value 6014 TEST_F(ParseFlagsTest, PrintTimeTrue) { 6015 const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr}; 6016 6017 const char* argv2[] = {"foo.exe", nullptr}; 6018 6019 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); 6020 } 6021 6022 // Tests having a --gtest_print_time flag with a "false" value 6023 TEST_F(ParseFlagsTest, PrintTimeFalse) { 6024 const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr}; 6025 6026 const char* argv2[] = {"foo.exe", nullptr}; 6027 6028 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); 6029 } 6030 6031 // Tests parsing --gtest_print_time=f. 6032 TEST_F(ParseFlagsTest, PrintTimeFalse_f) { 6033 const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr}; 6034 6035 const char* argv2[] = {"foo.exe", nullptr}; 6036 6037 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); 6038 } 6039 6040 // Tests parsing --gtest_print_time=F. 6041 TEST_F(ParseFlagsTest, PrintTimeFalse_F) { 6042 const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr}; 6043 6044 const char* argv2[] = {"foo.exe", nullptr}; 6045 6046 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); 6047 } 6048 6049 // Tests parsing --gtest_random_seed=number 6050 TEST_F(ParseFlagsTest, RandomSeed) { 6051 const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr}; 6052 6053 const char* argv2[] = {"foo.exe", nullptr}; 6054 6055 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false); 6056 } 6057 6058 // Tests parsing --gtest_repeat=number 6059 TEST_F(ParseFlagsTest, Repeat) { 6060 const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr}; 6061 6062 const char* argv2[] = {"foo.exe", nullptr}; 6063 6064 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false); 6065 } 6066 6067 // Tests parsing --gtest_recreate_environments_when_repeating 6068 TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) { 6069 const char* argv[] = { 6070 "foo.exe", 6071 "--gtest_recreate_environments_when_repeating=0", 6072 nullptr, 6073 }; 6074 6075 const char* argv2[] = {"foo.exe", nullptr}; 6076 6077 GTEST_TEST_PARSING_FLAGS_( 6078 argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false); 6079 } 6080 6081 // Tests having a --gtest_also_run_disabled_tests flag 6082 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) { 6083 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr}; 6084 6085 const char* argv2[] = {"foo.exe", nullptr}; 6086 6087 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), 6088 false); 6089 } 6090 6091 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value 6092 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) { 6093 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1", 6094 nullptr}; 6095 6096 const char* argv2[] = {"foo.exe", nullptr}; 6097 6098 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), 6099 false); 6100 } 6101 6102 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value 6103 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) { 6104 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0", 6105 nullptr}; 6106 6107 const char* argv2[] = {"foo.exe", nullptr}; 6108 6109 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false), 6110 false); 6111 } 6112 6113 // Tests parsing --gtest_shuffle. 6114 TEST_F(ParseFlagsTest, ShuffleWithoutValue) { 6115 const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr}; 6116 6117 const char* argv2[] = {"foo.exe", nullptr}; 6118 6119 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); 6120 } 6121 6122 // Tests parsing --gtest_shuffle=0. 6123 TEST_F(ParseFlagsTest, ShuffleFalse_0) { 6124 const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr}; 6125 6126 const char* argv2[] = {"foo.exe", nullptr}; 6127 6128 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false); 6129 } 6130 6131 // Tests parsing a --gtest_shuffle flag that has a "true" definition. 6132 TEST_F(ParseFlagsTest, ShuffleTrue) { 6133 const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr}; 6134 6135 const char* argv2[] = {"foo.exe", nullptr}; 6136 6137 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); 6138 } 6139 6140 // Tests parsing --gtest_stack_trace_depth=number. 6141 TEST_F(ParseFlagsTest, StackTraceDepth) { 6142 const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr}; 6143 6144 const char* argv2[] = {"foo.exe", nullptr}; 6145 6146 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false); 6147 } 6148 6149 TEST_F(ParseFlagsTest, StreamResultTo) { 6150 const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234", 6151 nullptr}; 6152 6153 const char* argv2[] = {"foo.exe", nullptr}; 6154 6155 GTEST_TEST_PARSING_FLAGS_(argv, argv2, 6156 Flags::StreamResultTo("localhost:1234"), false); 6157 } 6158 6159 // Tests parsing --gtest_throw_on_failure. 6160 TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) { 6161 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr}; 6162 6163 const char* argv2[] = {"foo.exe", nullptr}; 6164 6165 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); 6166 } 6167 6168 // Tests parsing --gtest_throw_on_failure=0. 6169 TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) { 6170 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr}; 6171 6172 const char* argv2[] = {"foo.exe", nullptr}; 6173 6174 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false); 6175 } 6176 6177 // Tests parsing a --gtest_throw_on_failure flag that has a "true" 6178 // definition. 6179 TEST_F(ParseFlagsTest, ThrowOnFailureTrue) { 6180 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr}; 6181 6182 const char* argv2[] = {"foo.exe", nullptr}; 6183 6184 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); 6185 } 6186 6187 // Tests parsing a bad --gtest_filter flag. 6188 TEST_F(ParseFlagsTest, FilterBad) { 6189 const char* argv[] = {"foo.exe", "--gtest_filter", nullptr}; 6190 6191 const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr}; 6192 6193 #if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST) 6194 // Invalid flag arguments are a fatal error when using the Abseil Flags. 6195 EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true), 6196 testing::ExitedWithCode(1), 6197 "ERROR: Missing the value for the flag 'gtest_filter'"); 6198 #elif !defined(GTEST_HAS_ABSL) 6199 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true); 6200 #else 6201 static_cast<void>(argv); 6202 static_cast<void>(argv2); 6203 #endif 6204 } 6205 6206 // Tests parsing --gtest_output (invalid). 6207 TEST_F(ParseFlagsTest, OutputEmpty) { 6208 const char* argv[] = {"foo.exe", "--gtest_output", nullptr}; 6209 6210 const char* argv2[] = {"foo.exe", "--gtest_output", nullptr}; 6211 6212 #if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST) 6213 // Invalid flag arguments are a fatal error when using the Abseil Flags. 6214 EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true), 6215 testing::ExitedWithCode(1), 6216 "ERROR: Missing the value for the flag 'gtest_output'"); 6217 #elif !defined(GTEST_HAS_ABSL) 6218 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true); 6219 #else 6220 static_cast<void>(argv); 6221 static_cast<void>(argv2); 6222 #endif 6223 } 6224 6225 #ifdef GTEST_HAS_ABSL 6226 TEST_F(ParseFlagsTest, AbseilPositionalFlags) { 6227 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", "--", 6228 "--other_flag", nullptr}; 6229 6230 // When using Abseil flags, it should be possible to pass flags not recognized 6231 // using "--" to delimit positional arguments. These flags should be returned 6232 // though argv. 6233 const char* argv2[] = {"foo.exe", "--other_flag", nullptr}; 6234 6235 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); 6236 } 6237 #endif 6238 6239 TEST_F(ParseFlagsTest, UnrecognizedFlags) { 6240 const char* argv[] = {"foo.exe", "--gtest_filter=abcd", "--other_flag", 6241 nullptr}; 6242 6243 const char* argv2[] = {"foo.exe", "--other_flag", nullptr}; 6244 6245 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abcd"), false); 6246 } 6247 6248 #ifdef GTEST_OS_WINDOWS 6249 // Tests parsing wide strings. 6250 TEST_F(ParseFlagsTest, WideStrings) { 6251 const wchar_t* argv[] = {L"foo.exe", 6252 L"--gtest_filter=Foo*", 6253 L"--gtest_list_tests=1", 6254 L"--gtest_break_on_failure", 6255 L"--non_gtest_flag", 6256 NULL}; 6257 6258 const wchar_t* argv2[] = {L"foo.exe", L"--non_gtest_flag", NULL}; 6259 6260 Flags expected_flags; 6261 expected_flags.break_on_failure = true; 6262 expected_flags.filter = "Foo*"; 6263 expected_flags.list_tests = true; 6264 6265 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); 6266 } 6267 #endif // GTEST_OS_WINDOWS 6268 6269 #if GTEST_USE_OWN_FLAGFILE_FLAG_ 6270 class FlagfileTest : public ParseFlagsTest { 6271 public: 6272 void SetUp() override { 6273 ParseFlagsTest::SetUp(); 6274 6275 testdata_path_.Set(internal::FilePath( 6276 testing::TempDir() + internal::GetCurrentExecutableName().string() + 6277 "_flagfile_test")); 6278 testing::internal::posix::RmDir(testdata_path_.c_str()); 6279 EXPECT_TRUE(testdata_path_.CreateFolder()); 6280 } 6281 6282 void TearDown() override { 6283 testing::internal::posix::RmDir(testdata_path_.c_str()); 6284 ParseFlagsTest::TearDown(); 6285 } 6286 6287 internal::FilePath CreateFlagfile(const char* contents) { 6288 internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName( 6289 testdata_path_, internal::FilePath("unique"), "txt")); 6290 FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w"); 6291 fprintf(f, "%s", contents); 6292 fclose(f); 6293 return file_path; 6294 } 6295 6296 private: 6297 internal::FilePath testdata_path_; 6298 }; 6299 6300 // Tests an empty flagfile. 6301 TEST_F(FlagfileTest, Empty) { 6302 internal::FilePath flagfile_path(CreateFlagfile("")); 6303 std::string flagfile_flag = 6304 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); 6305 6306 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; 6307 6308 const char* argv2[] = {"foo.exe", nullptr}; 6309 6310 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); 6311 } 6312 6313 // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile. 6314 TEST_F(FlagfileTest, FilterNonEmpty) { 6315 internal::FilePath flagfile_path( 6316 CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc")); 6317 std::string flagfile_flag = 6318 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); 6319 6320 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; 6321 6322 const char* argv2[] = {"foo.exe", nullptr}; 6323 6324 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); 6325 } 6326 6327 // Tests passing several flags via --gtest_flagfile. 6328 TEST_F(FlagfileTest, SeveralFlags) { 6329 internal::FilePath flagfile_path( 6330 CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc\n" 6331 "--" GTEST_FLAG_PREFIX_ "break_on_failure\n" 6332 "--" GTEST_FLAG_PREFIX_ "list_tests")); 6333 std::string flagfile_flag = 6334 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); 6335 6336 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; 6337 6338 const char* argv2[] = {"foo.exe", nullptr}; 6339 6340 Flags expected_flags; 6341 expected_flags.break_on_failure = true; 6342 expected_flags.filter = "abc"; 6343 expected_flags.list_tests = true; 6344 6345 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); 6346 } 6347 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ 6348 6349 // Tests current_test_info() in UnitTest. 6350 class CurrentTestInfoTest : public Test { 6351 protected: 6352 // Tests that current_test_info() returns NULL before the first test in 6353 // the test case is run. 6354 static void SetUpTestSuite() { 6355 // There should be no tests running at this point. 6356 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); 6357 EXPECT_TRUE(test_info == nullptr) 6358 << "There should be no tests running at this point."; 6359 } 6360 6361 // Tests that current_test_info() returns NULL after the last test in 6362 // the test case has run. 6363 static void TearDownTestSuite() { 6364 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); 6365 EXPECT_TRUE(test_info == nullptr) 6366 << "There should be no tests running at this point."; 6367 } 6368 }; 6369 6370 // Tests that current_test_info() returns TestInfo for currently running 6371 // test by checking the expected test name against the actual one. 6372 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) { 6373 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); 6374 ASSERT_TRUE(nullptr != test_info) 6375 << "There is a test running so we should have a valid TestInfo."; 6376 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) 6377 << "Expected the name of the currently running test suite."; 6378 EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name()) 6379 << "Expected the name of the currently running test."; 6380 } 6381 6382 // Tests that current_test_info() returns TestInfo for currently running 6383 // test by checking the expected test name against the actual one. We 6384 // use this test to see that the TestInfo object actually changed from 6385 // the previous invocation. 6386 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) { 6387 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); 6388 ASSERT_TRUE(nullptr != test_info) 6389 << "There is a test running so we should have a valid TestInfo."; 6390 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) 6391 << "Expected the name of the currently running test suite."; 6392 EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name()) 6393 << "Expected the name of the currently running test."; 6394 } 6395 6396 } // namespace testing 6397 6398 // These two lines test that we can define tests in a namespace that 6399 // has the name "testing" and is nested in another namespace. 6400 namespace my_namespace { 6401 namespace testing { 6402 6403 // Makes sure that TEST knows to use ::testing::Test instead of 6404 // ::my_namespace::testing::Test. 6405 class Test {}; 6406 6407 // Makes sure that an assertion knows to use ::testing::Message instead of 6408 // ::my_namespace::testing::Message. 6409 class Message {}; 6410 6411 // Makes sure that an assertion knows to use 6412 // ::testing::AssertionResult instead of 6413 // ::my_namespace::testing::AssertionResult. 6414 class AssertionResult {}; 6415 6416 // Tests that an assertion that should succeed works as expected. 6417 TEST(NestedTestingNamespaceTest, Success) { 6418 EXPECT_EQ(1, 1) << "This shouldn't fail."; 6419 } 6420 6421 // Tests that an assertion that should fail works as expected. 6422 TEST(NestedTestingNamespaceTest, Failure) { 6423 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.", 6424 "This failure is expected."); 6425 } 6426 6427 } // namespace testing 6428 } // namespace my_namespace 6429 6430 // Tests that one can call superclass SetUp and TearDown methods-- 6431 // that is, that they are not private. 6432 // No tests are based on this fixture; the test "passes" if it compiles 6433 // successfully. 6434 class ProtectedFixtureMethodsTest : public Test { 6435 protected: 6436 void SetUp() override { Test::SetUp(); } 6437 void TearDown() override { Test::TearDown(); } 6438 }; 6439 6440 // StreamingAssertionsTest tests the streaming versions of a representative 6441 // sample of assertions. 6442 TEST(StreamingAssertionsTest, Unconditional) { 6443 SUCCEED() << "expected success"; 6444 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure", 6445 "expected failure"); 6446 EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure"); 6447 } 6448 6449 #ifdef __BORLANDC__ 6450 // Silences warnings: "Condition is always true", "Unreachable code" 6451 #pragma option push -w-ccc -w-rch 6452 #endif 6453 6454 TEST(StreamingAssertionsTest, Truth) { 6455 EXPECT_TRUE(true) << "unexpected failure"; 6456 ASSERT_TRUE(true) << "unexpected failure"; 6457 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure", 6458 "expected failure"); 6459 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure", 6460 "expected failure"); 6461 } 6462 6463 TEST(StreamingAssertionsTest, Truth2) { 6464 EXPECT_FALSE(false) << "unexpected failure"; 6465 ASSERT_FALSE(false) << "unexpected failure"; 6466 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure", 6467 "expected failure"); 6468 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure", 6469 "expected failure"); 6470 } 6471 6472 #ifdef __BORLANDC__ 6473 // Restores warnings after previous "#pragma option push" suppressed them 6474 #pragma option pop 6475 #endif 6476 6477 TEST(StreamingAssertionsTest, IntegerEquals) { 6478 EXPECT_EQ(1, 1) << "unexpected failure"; 6479 ASSERT_EQ(1, 1) << "unexpected failure"; 6480 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure", 6481 "expected failure"); 6482 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure", 6483 "expected failure"); 6484 } 6485 6486 TEST(StreamingAssertionsTest, IntegerLessThan) { 6487 EXPECT_LT(1, 2) << "unexpected failure"; 6488 ASSERT_LT(1, 2) << "unexpected failure"; 6489 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure", 6490 "expected failure"); 6491 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure", 6492 "expected failure"); 6493 } 6494 6495 TEST(StreamingAssertionsTest, StringsEqual) { 6496 EXPECT_STREQ("foo", "foo") << "unexpected failure"; 6497 ASSERT_STREQ("foo", "foo") << "unexpected failure"; 6498 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure", 6499 "expected failure"); 6500 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure", 6501 "expected failure"); 6502 } 6503 6504 TEST(StreamingAssertionsTest, StringsNotEqual) { 6505 EXPECT_STRNE("foo", "bar") << "unexpected failure"; 6506 ASSERT_STRNE("foo", "bar") << "unexpected failure"; 6507 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure", 6508 "expected failure"); 6509 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure", 6510 "expected failure"); 6511 } 6512 6513 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) { 6514 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure"; 6515 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure"; 6516 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure", 6517 "expected failure"); 6518 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure", 6519 "expected failure"); 6520 } 6521 6522 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) { 6523 EXPECT_STRCASENE("foo", "bar") << "unexpected failure"; 6524 ASSERT_STRCASENE("foo", "bar") << "unexpected failure"; 6525 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure", 6526 "expected failure"); 6527 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure", 6528 "expected failure"); 6529 } 6530 6531 TEST(StreamingAssertionsTest, FloatingPointEquals) { 6532 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; 6533 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; 6534 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure", 6535 "expected failure"); 6536 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure", 6537 "expected failure"); 6538 } 6539 6540 #if GTEST_HAS_EXCEPTIONS 6541 6542 TEST(StreamingAssertionsTest, Throw) { 6543 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure"; 6544 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure"; 6545 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) 6546 << "expected failure", 6547 "expected failure"); 6548 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) 6549 << "expected failure", 6550 "expected failure"); 6551 } 6552 6553 TEST(StreamingAssertionsTest, NoThrow) { 6554 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure"; 6555 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure"; 6556 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) 6557 << "expected failure", 6558 "expected failure"); 6559 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure", 6560 "expected failure"); 6561 } 6562 6563 TEST(StreamingAssertionsTest, AnyThrow) { 6564 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; 6565 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; 6566 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) 6567 << "expected failure", 6568 "expected failure"); 6569 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure", 6570 "expected failure"); 6571 } 6572 6573 #endif // GTEST_HAS_EXCEPTIONS 6574 6575 // Tests that Google Test correctly decides whether to use colors in the output. 6576 6577 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { 6578 GTEST_FLAG_SET(color, "yes"); 6579 6580 SetEnv("TERM", "xterm"); // TERM supports colors. 6581 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6582 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 6583 6584 SetEnv("TERM", "dumb"); // TERM doesn't support colors. 6585 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6586 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 6587 } 6588 6589 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { 6590 SetEnv("TERM", "dumb"); // TERM doesn't support colors. 6591 6592 GTEST_FLAG_SET(color, "True"); 6593 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 6594 6595 GTEST_FLAG_SET(color, "t"); 6596 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 6597 6598 GTEST_FLAG_SET(color, "1"); 6599 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 6600 } 6601 6602 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { 6603 GTEST_FLAG_SET(color, "no"); 6604 6605 SetEnv("TERM", "xterm"); // TERM supports colors. 6606 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 6607 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. 6608 6609 SetEnv("TERM", "dumb"); // TERM doesn't support colors. 6610 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 6611 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. 6612 } 6613 6614 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { 6615 SetEnv("TERM", "xterm"); // TERM supports colors. 6616 6617 GTEST_FLAG_SET(color, "F"); 6618 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 6619 6620 GTEST_FLAG_SET(color, "0"); 6621 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 6622 6623 GTEST_FLAG_SET(color, "unknown"); 6624 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 6625 } 6626 6627 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { 6628 GTEST_FLAG_SET(color, "auto"); 6629 6630 SetEnv("TERM", "xterm"); // TERM supports colors. 6631 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. 6632 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6633 } 6634 6635 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { 6636 GTEST_FLAG_SET(color, "auto"); 6637 6638 #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) 6639 // On Windows, we ignore the TERM variable as it's usually not set. 6640 6641 SetEnv("TERM", "dumb"); 6642 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6643 6644 SetEnv("TERM", ""); 6645 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6646 6647 SetEnv("TERM", "xterm"); 6648 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6649 #else 6650 // On non-Windows platforms, we rely on TERM to determine if the 6651 // terminal supports colors. 6652 6653 SetEnv("TERM", "dumb"); // TERM doesn't support colors. 6654 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 6655 6656 SetEnv("TERM", "emacs"); // TERM doesn't support colors. 6657 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 6658 6659 SetEnv("TERM", "vt100"); // TERM doesn't support colors. 6660 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 6661 6662 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. 6663 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 6664 6665 SetEnv("TERM", "xterm"); // TERM supports colors. 6666 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6667 6668 SetEnv("TERM", "xterm-color"); // TERM supports colors. 6669 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6670 6671 SetEnv("TERM", "xterm-kitty"); // TERM supports colors. 6672 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6673 6674 SetEnv("TERM", "alacritty"); // TERM supports colors. 6675 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6676 6677 SetEnv("TERM", "xterm-256color"); // TERM supports colors. 6678 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6679 6680 SetEnv("TERM", "screen"); // TERM supports colors. 6681 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6682 6683 SetEnv("TERM", "screen-256color"); // TERM supports colors. 6684 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6685 6686 SetEnv("TERM", "tmux"); // TERM supports colors. 6687 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6688 6689 SetEnv("TERM", "tmux-256color"); // TERM supports colors. 6690 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6691 6692 SetEnv("TERM", "rxvt-unicode"); // TERM supports colors. 6693 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6694 6695 SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors. 6696 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6697 6698 SetEnv("TERM", "linux"); // TERM supports colors. 6699 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6700 6701 SetEnv("TERM", "cygwin"); // TERM supports colors. 6702 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 6703 #endif // GTEST_OS_WINDOWS 6704 } 6705 6706 // Verifies that StaticAssertTypeEq works in a namespace scope. 6707 6708 GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy1 = 6709 StaticAssertTypeEq<bool, bool>(); 6710 GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy2 = 6711 StaticAssertTypeEq<const int, const int>(); 6712 6713 // Verifies that StaticAssertTypeEq works in a class. 6714 6715 template <typename T> 6716 class StaticAssertTypeEqTestHelper { 6717 public: 6718 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); } 6719 }; 6720 6721 TEST(StaticAssertTypeEqTest, WorksInClass) { 6722 StaticAssertTypeEqTestHelper<bool>(); 6723 } 6724 6725 // Verifies that StaticAssertTypeEq works inside a function. 6726 6727 typedef int IntAlias; 6728 6729 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) { 6730 StaticAssertTypeEq<int, IntAlias>(); 6731 StaticAssertTypeEq<int*, IntAlias*>(); 6732 } 6733 6734 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) { 6735 EXPECT_FALSE(HasNonfatalFailure()); 6736 } 6737 6738 static void FailFatally() { FAIL(); } 6739 6740 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) { 6741 FailFatally(); 6742 const bool has_nonfatal_failure = HasNonfatalFailure(); 6743 ClearCurrentTestPartResults(); 6744 EXPECT_FALSE(has_nonfatal_failure); 6745 } 6746 6747 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { 6748 ADD_FAILURE(); 6749 const bool has_nonfatal_failure = HasNonfatalFailure(); 6750 ClearCurrentTestPartResults(); 6751 EXPECT_TRUE(has_nonfatal_failure); 6752 } 6753 6754 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { 6755 FailFatally(); 6756 ADD_FAILURE(); 6757 const bool has_nonfatal_failure = HasNonfatalFailure(); 6758 ClearCurrentTestPartResults(); 6759 EXPECT_TRUE(has_nonfatal_failure); 6760 } 6761 6762 // A wrapper for calling HasNonfatalFailure outside of a test body. 6763 static bool HasNonfatalFailureHelper() { 6764 return testing::Test::HasNonfatalFailure(); 6765 } 6766 6767 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) { 6768 EXPECT_FALSE(HasNonfatalFailureHelper()); 6769 } 6770 6771 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) { 6772 ADD_FAILURE(); 6773 const bool has_nonfatal_failure = HasNonfatalFailureHelper(); 6774 ClearCurrentTestPartResults(); 6775 EXPECT_TRUE(has_nonfatal_failure); 6776 } 6777 6778 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) { 6779 EXPECT_FALSE(HasFailure()); 6780 } 6781 6782 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) { 6783 FailFatally(); 6784 const bool has_failure = HasFailure(); 6785 ClearCurrentTestPartResults(); 6786 EXPECT_TRUE(has_failure); 6787 } 6788 6789 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { 6790 ADD_FAILURE(); 6791 const bool has_failure = HasFailure(); 6792 ClearCurrentTestPartResults(); 6793 EXPECT_TRUE(has_failure); 6794 } 6795 6796 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { 6797 FailFatally(); 6798 ADD_FAILURE(); 6799 const bool has_failure = HasFailure(); 6800 ClearCurrentTestPartResults(); 6801 EXPECT_TRUE(has_failure); 6802 } 6803 6804 // A wrapper for calling HasFailure outside of a test body. 6805 static bool HasFailureHelper() { return testing::Test::HasFailure(); } 6806 6807 TEST(HasFailureTest, WorksOutsideOfTestBody) { 6808 EXPECT_FALSE(HasFailureHelper()); 6809 } 6810 6811 TEST(HasFailureTest, WorksOutsideOfTestBody2) { 6812 ADD_FAILURE(); 6813 const bool has_failure = HasFailureHelper(); 6814 ClearCurrentTestPartResults(); 6815 EXPECT_TRUE(has_failure); 6816 } 6817 6818 class TestListener : public EmptyTestEventListener { 6819 public: 6820 TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {} 6821 TestListener(int* on_start_counter, bool* is_destroyed) 6822 : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {} 6823 6824 ~TestListener() override { 6825 if (is_destroyed_) *is_destroyed_ = true; 6826 } 6827 6828 protected: 6829 void OnTestProgramStart(const UnitTest& /*unit_test*/) override { 6830 if (on_start_counter_ != nullptr) (*on_start_counter_)++; 6831 } 6832 6833 private: 6834 int* on_start_counter_; 6835 bool* is_destroyed_; 6836 }; 6837 6838 // Tests the constructor. 6839 TEST(TestEventListenersTest, ConstructionWorks) { 6840 TestEventListeners listeners; 6841 6842 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr); 6843 EXPECT_TRUE(listeners.default_result_printer() == nullptr); 6844 EXPECT_TRUE(listeners.default_xml_generator() == nullptr); 6845 } 6846 6847 // Tests that the TestEventListeners destructor deletes all the listeners it 6848 // owns. 6849 TEST(TestEventListenersTest, DestructionWorks) { 6850 bool default_result_printer_is_destroyed = false; 6851 bool default_xml_printer_is_destroyed = false; 6852 bool extra_listener_is_destroyed = false; 6853 TestListener* default_result_printer = 6854 new TestListener(nullptr, &default_result_printer_is_destroyed); 6855 TestListener* default_xml_printer = 6856 new TestListener(nullptr, &default_xml_printer_is_destroyed); 6857 TestListener* extra_listener = 6858 new TestListener(nullptr, &extra_listener_is_destroyed); 6859 6860 { 6861 TestEventListeners listeners; 6862 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, 6863 default_result_printer); 6864 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, 6865 default_xml_printer); 6866 listeners.Append(extra_listener); 6867 } 6868 EXPECT_TRUE(default_result_printer_is_destroyed); 6869 EXPECT_TRUE(default_xml_printer_is_destroyed); 6870 EXPECT_TRUE(extra_listener_is_destroyed); 6871 } 6872 6873 // Tests that a listener Append'ed to a TestEventListeners list starts 6874 // receiving events. 6875 TEST(TestEventListenersTest, Append) { 6876 int on_start_counter = 0; 6877 bool is_destroyed = false; 6878 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); 6879 { 6880 TestEventListeners listeners; 6881 listeners.Append(listener); 6882 TestEventListenersAccessor::GetRepeater(&listeners) 6883 ->OnTestProgramStart(*UnitTest::GetInstance()); 6884 EXPECT_EQ(1, on_start_counter); 6885 } 6886 EXPECT_TRUE(is_destroyed); 6887 } 6888 6889 // Tests that listeners receive events in the order they were appended to 6890 // the list, except for *End requests, which must be received in the reverse 6891 // order. 6892 class SequenceTestingListener : public EmptyTestEventListener { 6893 public: 6894 SequenceTestingListener(std::vector<std::string>* vector, const char* id) 6895 : vector_(vector), id_(id) {} 6896 6897 protected: 6898 void OnTestProgramStart(const UnitTest& /*unit_test*/) override { 6899 vector_->push_back(GetEventDescription("OnTestProgramStart")); 6900 } 6901 6902 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override { 6903 vector_->push_back(GetEventDescription("OnTestProgramEnd")); 6904 } 6905 6906 void OnTestIterationStart(const UnitTest& /*unit_test*/, 6907 int /*iteration*/) override { 6908 vector_->push_back(GetEventDescription("OnTestIterationStart")); 6909 } 6910 6911 void OnTestIterationEnd(const UnitTest& /*unit_test*/, 6912 int /*iteration*/) override { 6913 vector_->push_back(GetEventDescription("OnTestIterationEnd")); 6914 } 6915 6916 private: 6917 std::string GetEventDescription(const char* method) { 6918 Message message; 6919 message << id_ << "." << method; 6920 return message.GetString(); 6921 } 6922 6923 std::vector<std::string>* vector_; 6924 const char* const id_; 6925 6926 SequenceTestingListener(const SequenceTestingListener&) = delete; 6927 SequenceTestingListener& operator=(const SequenceTestingListener&) = delete; 6928 }; 6929 6930 TEST(EventListenerTest, AppendKeepsOrder) { 6931 std::vector<std::string> vec; 6932 TestEventListeners listeners; 6933 listeners.Append(new SequenceTestingListener(&vec, "1st")); 6934 listeners.Append(new SequenceTestingListener(&vec, "2nd")); 6935 listeners.Append(new SequenceTestingListener(&vec, "3rd")); 6936 6937 TestEventListenersAccessor::GetRepeater(&listeners) 6938 ->OnTestProgramStart(*UnitTest::GetInstance()); 6939 ASSERT_EQ(3U, vec.size()); 6940 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str()); 6941 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str()); 6942 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str()); 6943 6944 vec.clear(); 6945 TestEventListenersAccessor::GetRepeater(&listeners) 6946 ->OnTestProgramEnd(*UnitTest::GetInstance()); 6947 ASSERT_EQ(3U, vec.size()); 6948 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str()); 6949 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str()); 6950 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str()); 6951 6952 vec.clear(); 6953 TestEventListenersAccessor::GetRepeater(&listeners) 6954 ->OnTestIterationStart(*UnitTest::GetInstance(), 0); 6955 ASSERT_EQ(3U, vec.size()); 6956 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str()); 6957 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str()); 6958 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str()); 6959 6960 vec.clear(); 6961 TestEventListenersAccessor::GetRepeater(&listeners) 6962 ->OnTestIterationEnd(*UnitTest::GetInstance(), 0); 6963 ASSERT_EQ(3U, vec.size()); 6964 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str()); 6965 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str()); 6966 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str()); 6967 } 6968 6969 // Tests that a listener removed from a TestEventListeners list stops receiving 6970 // events and is not deleted when the list is destroyed. 6971 TEST(TestEventListenersTest, Release) { 6972 int on_start_counter = 0; 6973 bool is_destroyed = false; 6974 // Although Append passes the ownership of this object to the list, 6975 // the following calls release it, and we need to delete it before the 6976 // test ends. 6977 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); 6978 { 6979 TestEventListeners listeners; 6980 listeners.Append(listener); 6981 EXPECT_EQ(listener, listeners.Release(listener)); 6982 TestEventListenersAccessor::GetRepeater(&listeners) 6983 ->OnTestProgramStart(*UnitTest::GetInstance()); 6984 EXPECT_TRUE(listeners.Release(listener) == nullptr); 6985 } 6986 EXPECT_EQ(0, on_start_counter); 6987 EXPECT_FALSE(is_destroyed); 6988 delete listener; 6989 } 6990 6991 // Tests that no events are forwarded when event forwarding is disabled. 6992 TEST(EventListenerTest, SuppressEventForwarding) { 6993 int on_start_counter = 0; 6994 TestListener* listener = new TestListener(&on_start_counter, nullptr); 6995 6996 TestEventListeners listeners; 6997 listeners.Append(listener); 6998 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); 6999 TestEventListenersAccessor::SuppressEventForwarding(&listeners); 7000 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); 7001 TestEventListenersAccessor::GetRepeater(&listeners) 7002 ->OnTestProgramStart(*UnitTest::GetInstance()); 7003 EXPECT_EQ(0, on_start_counter); 7004 } 7005 7006 // Tests that events generated by Google Test are not forwarded in 7007 // death test subprocesses. 7008 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprocesses) { 7009 EXPECT_DEATH_IF_SUPPORTED( 7010 { 7011 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( 7012 *GetUnitTestImpl()->listeners())) 7013 << "expected failure"; 7014 }, 7015 "expected failure"); 7016 } 7017 7018 // Tests that a listener installed via SetDefaultResultPrinter() starts 7019 // receiving events and is returned via default_result_printer() and that 7020 // the previous default_result_printer is removed from the list and deleted. 7021 TEST(EventListenerTest, default_result_printer) { 7022 int on_start_counter = 0; 7023 bool is_destroyed = false; 7024 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); 7025 7026 TestEventListeners listeners; 7027 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); 7028 7029 EXPECT_EQ(listener, listeners.default_result_printer()); 7030 7031 TestEventListenersAccessor::GetRepeater(&listeners) 7032 ->OnTestProgramStart(*UnitTest::GetInstance()); 7033 7034 EXPECT_EQ(1, on_start_counter); 7035 7036 // Replacing default_result_printer with something else should remove it 7037 // from the list and destroy it. 7038 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr); 7039 7040 EXPECT_TRUE(listeners.default_result_printer() == nullptr); 7041 EXPECT_TRUE(is_destroyed); 7042 7043 // After broadcasting an event the counter is still the same, indicating 7044 // the listener is not in the list anymore. 7045 TestEventListenersAccessor::GetRepeater(&listeners) 7046 ->OnTestProgramStart(*UnitTest::GetInstance()); 7047 EXPECT_EQ(1, on_start_counter); 7048 } 7049 7050 // Tests that the default_result_printer listener stops receiving events 7051 // when removed via Release and that is not owned by the list anymore. 7052 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) { 7053 int on_start_counter = 0; 7054 bool is_destroyed = false; 7055 // Although Append passes the ownership of this object to the list, 7056 // the following calls release it, and we need to delete it before the 7057 // test ends. 7058 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); 7059 { 7060 TestEventListeners listeners; 7061 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); 7062 7063 EXPECT_EQ(listener, listeners.Release(listener)); 7064 EXPECT_TRUE(listeners.default_result_printer() == nullptr); 7065 EXPECT_FALSE(is_destroyed); 7066 7067 // Broadcasting events now should not affect default_result_printer. 7068 TestEventListenersAccessor::GetRepeater(&listeners) 7069 ->OnTestProgramStart(*UnitTest::GetInstance()); 7070 EXPECT_EQ(0, on_start_counter); 7071 } 7072 // Destroying the list should not affect the listener now, too. 7073 EXPECT_FALSE(is_destroyed); 7074 delete listener; 7075 } 7076 7077 // Tests that a listener installed via SetDefaultXmlGenerator() starts 7078 // receiving events and is returned via default_xml_generator() and that 7079 // the previous default_xml_generator is removed from the list and deleted. 7080 TEST(EventListenerTest, default_xml_generator) { 7081 int on_start_counter = 0; 7082 bool is_destroyed = false; 7083 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); 7084 7085 TestEventListeners listeners; 7086 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); 7087 7088 EXPECT_EQ(listener, listeners.default_xml_generator()); 7089 7090 TestEventListenersAccessor::GetRepeater(&listeners) 7091 ->OnTestProgramStart(*UnitTest::GetInstance()); 7092 7093 EXPECT_EQ(1, on_start_counter); 7094 7095 // Replacing default_xml_generator with something else should remove it 7096 // from the list and destroy it. 7097 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr); 7098 7099 EXPECT_TRUE(listeners.default_xml_generator() == nullptr); 7100 EXPECT_TRUE(is_destroyed); 7101 7102 // After broadcasting an event the counter is still the same, indicating 7103 // the listener is not in the list anymore. 7104 TestEventListenersAccessor::GetRepeater(&listeners) 7105 ->OnTestProgramStart(*UnitTest::GetInstance()); 7106 EXPECT_EQ(1, on_start_counter); 7107 } 7108 7109 // Tests that the default_xml_generator listener stops receiving events 7110 // when removed via Release and that is not owned by the list anymore. 7111 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) { 7112 int on_start_counter = 0; 7113 bool is_destroyed = false; 7114 // Although Append passes the ownership of this object to the list, 7115 // the following calls release it, and we need to delete it before the 7116 // test ends. 7117 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); 7118 { 7119 TestEventListeners listeners; 7120 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); 7121 7122 EXPECT_EQ(listener, listeners.Release(listener)); 7123 EXPECT_TRUE(listeners.default_xml_generator() == nullptr); 7124 EXPECT_FALSE(is_destroyed); 7125 7126 // Broadcasting events now should not affect default_xml_generator. 7127 TestEventListenersAccessor::GetRepeater(&listeners) 7128 ->OnTestProgramStart(*UnitTest::GetInstance()); 7129 EXPECT_EQ(0, on_start_counter); 7130 } 7131 // Destroying the list should not affect the listener now, too. 7132 EXPECT_FALSE(is_destroyed); 7133 delete listener; 7134 } 7135 7136 // Tests to ensure that the alternative, verbose spellings of 7137 // some of the macros work. We don't test them thoroughly as that 7138 // would be quite involved. Since their implementations are 7139 // straightforward, and they are rarely used, we'll just rely on the 7140 // users to tell us when they are broken. 7141 GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. 7142 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED. 7143 7144 // GTEST_FAIL is the same as FAIL. 7145 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure", 7146 "An expected failure"); 7147 7148 // GTEST_ASSERT_XY is the same as ASSERT_XY. 7149 7150 GTEST_ASSERT_EQ(0, 0); 7151 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure", 7152 "An expected failure"); 7153 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure", 7154 "An expected failure"); 7155 7156 GTEST_ASSERT_NE(0, 1); 7157 GTEST_ASSERT_NE(1, 0); 7158 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure", 7159 "An expected failure"); 7160 7161 GTEST_ASSERT_LE(0, 0); 7162 GTEST_ASSERT_LE(0, 1); 7163 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure", 7164 "An expected failure"); 7165 7166 GTEST_ASSERT_LT(0, 1); 7167 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure", 7168 "An expected failure"); 7169 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure", 7170 "An expected failure"); 7171 7172 GTEST_ASSERT_GE(0, 0); 7173 GTEST_ASSERT_GE(1, 0); 7174 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure", 7175 "An expected failure"); 7176 7177 GTEST_ASSERT_GT(1, 0); 7178 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure", 7179 "An expected failure"); 7180 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure", 7181 "An expected failure"); 7182 } 7183 7184 // Tests for internal utilities necessary for implementation of the universal 7185 // printing. 7186 7187 class ConversionHelperBase {}; 7188 class ConversionHelperDerived : public ConversionHelperBase {}; 7189 7190 struct HasDebugStringMethods { 7191 std::string DebugString() const { return ""; } 7192 std::string ShortDebugString() const { return ""; } 7193 }; 7194 7195 struct InheritsDebugStringMethods : public HasDebugStringMethods {}; 7196 7197 struct WrongTypeDebugStringMethod { 7198 std::string DebugString() const { return ""; } 7199 int ShortDebugString() const { return 1; } 7200 }; 7201 7202 struct NotConstDebugStringMethod { 7203 std::string DebugString() { return ""; } 7204 std::string ShortDebugString() const { return ""; } 7205 }; 7206 7207 struct MissingDebugStringMethod { 7208 std::string DebugString() { return ""; } 7209 }; 7210 7211 struct IncompleteType; 7212 7213 // Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time 7214 // constant. 7215 TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) { 7216 static_assert(HasDebugStringAndShortDebugString<HasDebugStringMethods>::value, 7217 "const_true"); 7218 static_assert( 7219 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value, 7220 "const_true"); 7221 static_assert(HasDebugStringAndShortDebugString< 7222 const InheritsDebugStringMethods>::value, 7223 "const_true"); 7224 static_assert( 7225 !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value, 7226 "const_false"); 7227 static_assert( 7228 !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value, 7229 "const_false"); 7230 static_assert( 7231 !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value, 7232 "const_false"); 7233 static_assert(!HasDebugStringAndShortDebugString<IncompleteType>::value, 7234 "const_false"); 7235 static_assert(!HasDebugStringAndShortDebugString<int>::value, "const_false"); 7236 } 7237 7238 // Tests that HasDebugStringAndShortDebugString<T>::value is true when T has 7239 // needed methods. 7240 TEST(HasDebugStringAndShortDebugStringTest, 7241 ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) { 7242 EXPECT_TRUE( 7243 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value); 7244 } 7245 7246 // Tests that HasDebugStringAndShortDebugString<T>::value is false when T 7247 // doesn't have needed methods. 7248 TEST(HasDebugStringAndShortDebugStringTest, 7249 ValueIsFalseWhenTypeIsNotAProtocolMessage) { 7250 EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value); 7251 EXPECT_FALSE( 7252 HasDebugStringAndShortDebugString<const ConversionHelperBase>::value); 7253 } 7254 7255 // Tests GTEST_REMOVE_REFERENCE_AND_CONST_. 7256 7257 template <typename T1, typename T2> 7258 void TestGTestRemoveReferenceAndConst() { 7259 static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value, 7260 "GTEST_REMOVE_REFERENCE_AND_CONST_ failed."); 7261 } 7262 7263 TEST(RemoveReferenceToConstTest, Works) { 7264 TestGTestRemoveReferenceAndConst<int, int>(); 7265 TestGTestRemoveReferenceAndConst<double, double&>(); 7266 TestGTestRemoveReferenceAndConst<char, const char>(); 7267 TestGTestRemoveReferenceAndConst<char, const char&>(); 7268 TestGTestRemoveReferenceAndConst<const char*, const char*>(); 7269 } 7270 7271 // Tests GTEST_REFERENCE_TO_CONST_. 7272 7273 template <typename T1, typename T2> 7274 void TestGTestReferenceToConst() { 7275 static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value, 7276 "GTEST_REFERENCE_TO_CONST_ failed."); 7277 } 7278 7279 TEST(GTestReferenceToConstTest, Works) { 7280 TestGTestReferenceToConst<const char&, char>(); 7281 TestGTestReferenceToConst<const int&, const int>(); 7282 TestGTestReferenceToConst<const double&, double>(); 7283 TestGTestReferenceToConst<const std::string&, const std::string&>(); 7284 } 7285 7286 // Tests IsContainerTest. 7287 7288 class NonContainer {}; 7289 7290 TEST(IsContainerTestTest, WorksForNonContainer) { 7291 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0))); 7292 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0))); 7293 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0))); 7294 } 7295 7296 TEST(IsContainerTestTest, WorksForContainer) { 7297 EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool>>(0))); 7298 EXPECT_EQ(sizeof(IsContainer), 7299 sizeof(IsContainerTest<std::map<int, double>>(0))); 7300 } 7301 7302 struct ConstOnlyContainerWithPointerIterator { 7303 using const_iterator = int*; 7304 const_iterator begin() const; 7305 const_iterator end() const; 7306 }; 7307 7308 struct ConstOnlyContainerWithClassIterator { 7309 struct const_iterator { 7310 const int& operator*() const; 7311 const_iterator& operator++(/* pre-increment */); 7312 }; 7313 const_iterator begin() const; 7314 const_iterator end() const; 7315 }; 7316 7317 TEST(IsContainerTestTest, ConstOnlyContainer) { 7318 EXPECT_EQ(sizeof(IsContainer), 7319 sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0))); 7320 EXPECT_EQ(sizeof(IsContainer), 7321 sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0))); 7322 } 7323 7324 // Tests IsHashTable. 7325 struct AHashTable { 7326 typedef void hasher; 7327 }; 7328 struct NotReallyAHashTable { 7329 typedef void hasher; 7330 typedef void reverse_iterator; 7331 }; 7332 TEST(IsHashTable, Basic) { 7333 EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value); 7334 EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value); 7335 EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value); 7336 EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value); 7337 } 7338 7339 // Tests ArrayEq(). 7340 7341 TEST(ArrayEqTest, WorksForDegeneratedArrays) { 7342 EXPECT_TRUE(ArrayEq(5, 5L)); 7343 EXPECT_FALSE(ArrayEq('a', 0)); 7344 } 7345 7346 TEST(ArrayEqTest, WorksForOneDimensionalArrays) { 7347 // Note that a and b are distinct but compatible types. 7348 const int a[] = {0, 1}; 7349 long b[] = {0, 1}; 7350 EXPECT_TRUE(ArrayEq(a, b)); 7351 EXPECT_TRUE(ArrayEq(a, 2, b)); 7352 7353 b[0] = 2; 7354 EXPECT_FALSE(ArrayEq(a, b)); 7355 EXPECT_FALSE(ArrayEq(a, 1, b)); 7356 } 7357 7358 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) { 7359 const char a[][3] = {"hi", "lo"}; 7360 const char b[][3] = {"hi", "lo"}; 7361 const char c[][3] = {"hi", "li"}; 7362 7363 EXPECT_TRUE(ArrayEq(a, b)); 7364 EXPECT_TRUE(ArrayEq(a, 2, b)); 7365 7366 EXPECT_FALSE(ArrayEq(a, c)); 7367 EXPECT_FALSE(ArrayEq(a, 2, c)); 7368 } 7369 7370 // Tests ArrayAwareFind(). 7371 7372 TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) { 7373 const char a[] = "hello"; 7374 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o')); 7375 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x')); 7376 } 7377 7378 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) { 7379 int a[][2] = {{0, 1}, {2, 3}, {4, 5}}; 7380 const int b[2] = {2, 3}; 7381 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b)); 7382 7383 const int c[2] = {6, 7}; 7384 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c)); 7385 } 7386 7387 // Tests CopyArray(). 7388 7389 TEST(CopyArrayTest, WorksForDegeneratedArrays) { 7390 int n = 0; 7391 CopyArray('a', &n); 7392 EXPECT_EQ('a', n); 7393 } 7394 7395 TEST(CopyArrayTest, WorksForOneDimensionalArrays) { 7396 const char a[3] = "hi"; 7397 int b[3]; 7398 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. 7399 CopyArray(a, &b); 7400 EXPECT_TRUE(ArrayEq(a, b)); 7401 #endif 7402 7403 int c[3]; 7404 CopyArray(a, 3, c); 7405 EXPECT_TRUE(ArrayEq(a, c)); 7406 } 7407 7408 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { 7409 const int a[2][3] = {{0, 1, 2}, {3, 4, 5}}; 7410 int b[2][3]; 7411 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. 7412 CopyArray(a, &b); 7413 EXPECT_TRUE(ArrayEq(a, b)); 7414 #endif 7415 7416 int c[2][3]; 7417 CopyArray(a, 2, c); 7418 EXPECT_TRUE(ArrayEq(a, c)); 7419 } 7420 7421 // Tests NativeArray. 7422 7423 TEST(NativeArrayTest, ConstructorFromArrayWorks) { 7424 const int a[3] = {0, 1, 2}; 7425 NativeArray<int> na(a, 3, RelationToSourceReference()); 7426 EXPECT_EQ(3U, na.size()); 7427 EXPECT_EQ(a, na.begin()); 7428 } 7429 7430 TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) { 7431 typedef int Array[2]; 7432 Array* a = new Array[1]; 7433 (*a)[0] = 0; 7434 (*a)[1] = 1; 7435 NativeArray<int> na(*a, 2, RelationToSourceCopy()); 7436 EXPECT_NE(*a, na.begin()); 7437 delete[] a; 7438 EXPECT_EQ(0, na.begin()[0]); 7439 EXPECT_EQ(1, na.begin()[1]); 7440 7441 // We rely on the heap checker to verify that na deletes the copy of 7442 // array. 7443 } 7444 7445 TEST(NativeArrayTest, TypeMembersAreCorrect) { 7446 StaticAssertTypeEq<char, NativeArray<char>::value_type>(); 7447 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>(); 7448 7449 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>(); 7450 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>(); 7451 } 7452 7453 TEST(NativeArrayTest, MethodsWork) { 7454 const int a[3] = {0, 1, 2}; 7455 NativeArray<int> na(a, 3, RelationToSourceCopy()); 7456 ASSERT_EQ(3U, na.size()); 7457 EXPECT_EQ(3, na.end() - na.begin()); 7458 7459 NativeArray<int>::const_iterator it = na.begin(); 7460 EXPECT_EQ(0, *it); 7461 ++it; 7462 EXPECT_EQ(1, *it); 7463 it++; 7464 EXPECT_EQ(2, *it); 7465 ++it; 7466 EXPECT_EQ(na.end(), it); 7467 7468 EXPECT_TRUE(na == na); 7469 7470 NativeArray<int> na2(a, 3, RelationToSourceReference()); 7471 EXPECT_TRUE(na == na2); 7472 7473 const int b1[3] = {0, 1, 1}; 7474 const int b2[4] = {0, 1, 2, 3}; 7475 EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference())); 7476 EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy())); 7477 } 7478 7479 TEST(NativeArrayTest, WorksForTwoDimensionalArray) { 7480 const char a[2][3] = {"hi", "lo"}; 7481 NativeArray<char[3]> na(a, 2, RelationToSourceReference()); 7482 ASSERT_EQ(2U, na.size()); 7483 EXPECT_EQ(a, na.begin()); 7484 } 7485 7486 // ElemFromList 7487 TEST(ElemFromList, Basic) { 7488 using testing::internal::ElemFromList; 7489 EXPECT_TRUE( 7490 (std::is_same<int, ElemFromList<0, int, double, char>::type>::value)); 7491 EXPECT_TRUE( 7492 (std::is_same<double, ElemFromList<1, int, double, char>::type>::value)); 7493 EXPECT_TRUE( 7494 (std::is_same<char, ElemFromList<2, int, double, char>::type>::value)); 7495 EXPECT_TRUE(( 7496 std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int, 7497 char, int, int, int, int>::type>::value)); 7498 } 7499 7500 // FlatTuple 7501 TEST(FlatTuple, Basic) { 7502 using testing::internal::FlatTuple; 7503 7504 FlatTuple<int, double, const char*> tuple = {}; 7505 EXPECT_EQ(0, tuple.Get<0>()); 7506 EXPECT_EQ(0.0, tuple.Get<1>()); 7507 EXPECT_EQ(nullptr, tuple.Get<2>()); 7508 7509 tuple = FlatTuple<int, double, const char*>( 7510 testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo"); 7511 EXPECT_EQ(7, tuple.Get<0>()); 7512 EXPECT_EQ(3.2, tuple.Get<1>()); 7513 EXPECT_EQ(std::string("Foo"), tuple.Get<2>()); 7514 7515 tuple.Get<1>() = 5.1; 7516 EXPECT_EQ(5.1, tuple.Get<1>()); 7517 } 7518 7519 namespace { 7520 std::string AddIntToString(int i, const std::string& s) { 7521 return s + std::to_string(i); 7522 } 7523 } // namespace 7524 7525 TEST(FlatTuple, Apply) { 7526 using testing::internal::FlatTuple; 7527 7528 FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{}, 7529 5, "Hello"}; 7530 7531 // Lambda. 7532 EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool { 7533 return i == static_cast<int>(s.size()); 7534 })); 7535 7536 // Function. 7537 EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5"); 7538 7539 // Mutating operations. 7540 tuple.Apply([](int& i, std::string& s) { 7541 ++i; 7542 s += s; 7543 }); 7544 EXPECT_EQ(tuple.Get<0>(), 6); 7545 EXPECT_EQ(tuple.Get<1>(), "HelloHello"); 7546 } 7547 7548 struct ConstructionCounting { 7549 ConstructionCounting() { ++default_ctor_calls; } 7550 ~ConstructionCounting() { ++dtor_calls; } 7551 ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; } 7552 ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; } 7553 ConstructionCounting& operator=(const ConstructionCounting&) { 7554 ++copy_assignment_calls; 7555 return *this; 7556 } 7557 ConstructionCounting& operator=(ConstructionCounting&&) noexcept { 7558 ++move_assignment_calls; 7559 return *this; 7560 } 7561 7562 static void Reset() { 7563 default_ctor_calls = 0; 7564 dtor_calls = 0; 7565 copy_ctor_calls = 0; 7566 move_ctor_calls = 0; 7567 copy_assignment_calls = 0; 7568 move_assignment_calls = 0; 7569 } 7570 7571 static int default_ctor_calls; 7572 static int dtor_calls; 7573 static int copy_ctor_calls; 7574 static int move_ctor_calls; 7575 static int copy_assignment_calls; 7576 static int move_assignment_calls; 7577 }; 7578 7579 int ConstructionCounting::default_ctor_calls = 0; 7580 int ConstructionCounting::dtor_calls = 0; 7581 int ConstructionCounting::copy_ctor_calls = 0; 7582 int ConstructionCounting::move_ctor_calls = 0; 7583 int ConstructionCounting::copy_assignment_calls = 0; 7584 int ConstructionCounting::move_assignment_calls = 0; 7585 7586 TEST(FlatTuple, ConstructorCalls) { 7587 using testing::internal::FlatTuple; 7588 7589 // Default construction. 7590 ConstructionCounting::Reset(); 7591 { FlatTuple<ConstructionCounting> tuple; } 7592 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1); 7593 EXPECT_EQ(ConstructionCounting::dtor_calls, 1); 7594 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0); 7595 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0); 7596 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0); 7597 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0); 7598 7599 // Copy construction. 7600 ConstructionCounting::Reset(); 7601 { 7602 ConstructionCounting elem; 7603 FlatTuple<ConstructionCounting> tuple{ 7604 testing::internal::FlatTupleConstructTag{}, elem}; 7605 } 7606 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1); 7607 EXPECT_EQ(ConstructionCounting::dtor_calls, 2); 7608 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1); 7609 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0); 7610 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0); 7611 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0); 7612 7613 // Move construction. 7614 ConstructionCounting::Reset(); 7615 { 7616 FlatTuple<ConstructionCounting> tuple{ 7617 testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}}; 7618 } 7619 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1); 7620 EXPECT_EQ(ConstructionCounting::dtor_calls, 2); 7621 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0); 7622 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1); 7623 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0); 7624 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0); 7625 7626 // Copy assignment. 7627 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its 7628 // elements 7629 ConstructionCounting::Reset(); 7630 { 7631 FlatTuple<ConstructionCounting> tuple; 7632 ConstructionCounting elem; 7633 tuple.Get<0>() = elem; 7634 } 7635 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2); 7636 EXPECT_EQ(ConstructionCounting::dtor_calls, 2); 7637 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0); 7638 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0); 7639 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1); 7640 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0); 7641 7642 // Move assignment. 7643 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its 7644 // elements 7645 ConstructionCounting::Reset(); 7646 { 7647 FlatTuple<ConstructionCounting> tuple; 7648 tuple.Get<0>() = ConstructionCounting{}; 7649 } 7650 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2); 7651 EXPECT_EQ(ConstructionCounting::dtor_calls, 2); 7652 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0); 7653 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0); 7654 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0); 7655 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1); 7656 7657 ConstructionCounting::Reset(); 7658 } 7659 7660 TEST(FlatTuple, ManyTypes) { 7661 using testing::internal::FlatTuple; 7662 7663 // Instantiate FlatTuple with 257 ints. 7664 // Tests show that we can do it with thousands of elements, but very long 7665 // compile times makes it unusuitable for this test. 7666 #define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int, 7667 #define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8 7668 #define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16 7669 #define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32 7670 #define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64 7671 #define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128 7672 7673 // Let's make sure that we can have a very long list of types without blowing 7674 // up the template instantiation depth. 7675 FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple; 7676 7677 tuple.Get<0>() = 7; 7678 tuple.Get<99>() = 17; 7679 tuple.Get<256>() = 1000; 7680 EXPECT_EQ(7, tuple.Get<0>()); 7681 EXPECT_EQ(17, tuple.Get<99>()); 7682 EXPECT_EQ(1000, tuple.Get<256>()); 7683 } 7684 7685 // Tests SkipPrefix(). 7686 7687 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) { 7688 const char* const str = "hello"; 7689 7690 const char* p = str; 7691 EXPECT_TRUE(SkipPrefix("", &p)); 7692 EXPECT_EQ(str, p); 7693 7694 p = str; 7695 EXPECT_TRUE(SkipPrefix("hell", &p)); 7696 EXPECT_EQ(str + 4, p); 7697 } 7698 7699 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) { 7700 const char* const str = "world"; 7701 7702 const char* p = str; 7703 EXPECT_FALSE(SkipPrefix("W", &p)); 7704 EXPECT_EQ(str, p); 7705 7706 p = str; 7707 EXPECT_FALSE(SkipPrefix("world!", &p)); 7708 EXPECT_EQ(str, p); 7709 } 7710 7711 // Tests ad_hoc_test_result(). 7712 TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) { 7713 const testing::TestResult& test_result = 7714 testing::UnitTest::GetInstance()->ad_hoc_test_result(); 7715 EXPECT_FALSE(test_result.Failed()); 7716 } 7717 7718 class DynamicUnitTestFixture : public testing::Test {}; 7719 7720 class DynamicTest : public DynamicUnitTestFixture { 7721 void TestBody() override { EXPECT_TRUE(true); } 7722 }; 7723 7724 auto* dynamic_test = testing::RegisterTest( 7725 "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__, 7726 __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; }); 7727 7728 TEST(RegisterTest, WasRegistered) { 7729 const auto& unittest = testing::UnitTest::GetInstance(); 7730 for (int i = 0; i < unittest->total_test_suite_count(); ++i) { 7731 auto* tests = unittest->GetTestSuite(i); 7732 if (tests->name() != std::string("DynamicUnitTestFixture")) continue; 7733 for (int j = 0; j < tests->total_test_count(); ++j) { 7734 if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue; 7735 // Found it. 7736 EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE"); 7737 EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE"); 7738 return; 7739 } 7740 } 7741 7742 FAIL() << "Didn't find the test!"; 7743 } 7744 7745 // Test that the pattern globbing algorithm is linear. If not, this test should 7746 // time out. 7747 TEST(PatternGlobbingTest, MatchesFilterLinearRuntime) { 7748 std::string name(100, 'a'); // Construct the string (a^100)b 7749 name.push_back('b'); 7750 7751 std::string pattern; // Construct the string ((a*)^100)b 7752 for (int i = 0; i < 100; ++i) { 7753 pattern.append("a*"); 7754 } 7755 pattern.push_back('b'); 7756 7757 EXPECT_TRUE( 7758 testing::internal::UnitTestOptions::MatchesFilter(name, pattern.c_str())); 7759 } 7760 7761 TEST(PatternGlobbingTest, MatchesFilterWithMultiplePatterns) { 7762 const std::string name = "aaaa"; 7763 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*")); 7764 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*:")); 7765 EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab")); 7766 EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:")); 7767 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:a*")); 7768 } 7769 7770 TEST(PatternGlobbingTest, MatchesFilterEdgeCases) { 7771 EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("", "*a")); 7772 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", "*")); 7773 EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("a", "")); 7774 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", "")); 7775 } 7776