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