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@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 37// Verifies that the command line flag variables can be accessed 38// in code once <gtest/gtest.h> has been #included. 39// Do not move it after other #includes. 40TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { 41 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) 42 || testing::GTEST_FLAG(break_on_failure) 43 || testing::GTEST_FLAG(catch_exceptions) 44 || testing::GTEST_FLAG(color) != "unknown" 45 || testing::GTEST_FLAG(filter) != "unknown" 46 || testing::GTEST_FLAG(list_tests) 47 || testing::GTEST_FLAG(output) != "unknown" 48 || testing::GTEST_FLAG(print_time) 49 || testing::GTEST_FLAG(repeat) > 0 50 || testing::GTEST_FLAG(show_internal_stack_frames) 51 || testing::GTEST_FLAG(stack_trace_depth) > 0 52 || testing::GTEST_FLAG(throw_on_failure); 53 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused. 54} 55 56#include <gtest/gtest-spi.h> 57 58// Indicates that this translation unit is part of Google Test's 59// implementation. It must come before gtest-internal-inl.h is 60// included, or there will be a compiler error. This trick is to 61// prevent a user from accidentally including gtest-internal-inl.h in 62// his code. 63#define GTEST_IMPLEMENTATION_ 1 64#include "src/gtest-internal-inl.h" 65#undef GTEST_IMPLEMENTATION_ 66 67#include <stdlib.h> 68 69#if GTEST_HAS_PTHREAD 70#include <pthread.h> 71#endif // GTEST_HAS_PTHREAD 72 73#if GTEST_OS_LINUX 74#include <string.h> 75#include <signal.h> 76#include <sys/stat.h> 77#include <unistd.h> 78#include <string> 79#include <vector> 80#endif // GTEST_OS_LINUX 81 82namespace testing { 83namespace internal { 84const char* FormatTimeInMillisAsSeconds(TimeInMillis ms); 85bool ParseInt32Flag(const char* str, const char* flag, Int32* value); 86} // namespace internal 87} // namespace testing 88 89using testing::internal::FormatTimeInMillisAsSeconds; 90using testing::internal::ParseInt32Flag; 91 92namespace testing { 93 94GTEST_DECLARE_string_(output); 95GTEST_DECLARE_string_(color); 96 97namespace internal { 98bool ShouldUseColor(bool stdout_is_tty); 99} // namespace internal 100} // namespace testing 101 102using testing::AssertionFailure; 103using testing::AssertionResult; 104using testing::AssertionSuccess; 105using testing::DoubleLE; 106using testing::FloatLE; 107using testing::GTEST_FLAG(also_run_disabled_tests); 108using testing::GTEST_FLAG(break_on_failure); 109using testing::GTEST_FLAG(catch_exceptions); 110using testing::GTEST_FLAG(death_test_use_fork); 111using testing::GTEST_FLAG(color); 112using testing::GTEST_FLAG(filter); 113using testing::GTEST_FLAG(list_tests); 114using testing::GTEST_FLAG(output); 115using testing::GTEST_FLAG(print_time); 116using testing::GTEST_FLAG(repeat); 117using testing::GTEST_FLAG(show_internal_stack_frames); 118using testing::GTEST_FLAG(stack_trace_depth); 119using testing::GTEST_FLAG(throw_on_failure); 120using testing::IsNotSubstring; 121using testing::IsSubstring; 122using testing::Message; 123using testing::ScopedFakeTestPartResultReporter; 124using testing::StaticAssertTypeEq; 125using testing::Test; 126using testing::TestPartResult; 127using testing::TestPartResultArray; 128using testing::TPRT_FATAL_FAILURE; 129using testing::TPRT_NONFATAL_FAILURE; 130using testing::TPRT_SUCCESS; 131using testing::UnitTest; 132using testing::internal::kTestTypeIdInGoogleTest; 133using testing::internal::AppendUserMessage; 134using testing::internal::CodePointToUtf8; 135using testing::internal::EqFailure; 136using testing::internal::FloatingPoint; 137using testing::internal::GetCurrentOsStackTraceExceptTop; 138using testing::internal::GetFailedPartCount; 139using testing::internal::GetTestTypeId; 140using testing::internal::GetTypeId; 141using testing::internal::GTestFlagSaver; 142using testing::internal::Int32; 143using testing::internal::Int32FromEnvOrDie; 144using testing::internal::List; 145using testing::internal::ShouldRunTestOnShard; 146using testing::internal::ShouldShard; 147using testing::internal::ShouldUseColor; 148using testing::internal::StreamableToString; 149using testing::internal::String; 150using testing::internal::TestProperty; 151using testing::internal::TestResult; 152using testing::internal::ThreadLocal; 153using testing::internal::UnitTestImpl; 154using testing::internal::WideStringToUtf8; 155 156// This line tests that we can define tests in an unnamed namespace. 157namespace { 158 159// Tests GetTypeId. 160 161TEST(GetTypeIdTest, ReturnsSameValueForSameType) { 162 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>()); 163 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>()); 164} 165 166class SubClassOfTest : public Test {}; 167class AnotherSubClassOfTest : public Test {}; 168 169TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) { 170 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>()); 171 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>()); 172 EXPECT_NE(GetTypeId<int>(), GetTestTypeId()); 173 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId()); 174 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId()); 175 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>()); 176} 177 178// Verifies that GetTestTypeId() returns the same value, no matter it 179// is called from inside Google Test or outside of it. 180TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { 181 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); 182} 183 184// Tests FormatTimeInMillisAsSeconds(). 185 186// DISABLED see bug 2398288 187TEST(FormatTimeInMillisAsSecondsTest, DISABLED_FormatsZero) { 188 EXPECT_STREQ("0", FormatTimeInMillisAsSeconds(0)); 189} 190 191// DISABLED see bug 2398288 192TEST(FormatTimeInMillisAsSecondsTest, DISABLED_FormatsPositiveNumber) { 193 EXPECT_STREQ("0.003", FormatTimeInMillisAsSeconds(3)); 194 EXPECT_STREQ("0.01", FormatTimeInMillisAsSeconds(10)); 195 EXPECT_STREQ("0.2", FormatTimeInMillisAsSeconds(200)); 196 EXPECT_STREQ("1.2", FormatTimeInMillisAsSeconds(1200)); 197 EXPECT_STREQ("3", FormatTimeInMillisAsSeconds(3000)); 198} 199 200// DISABLED see bug 2398288 201TEST(FormatTimeInMillisAsSecondsTest, DISABLED_FormatsNegativeNumber) { 202 EXPECT_STREQ("-0.003", FormatTimeInMillisAsSeconds(-3)); 203 EXPECT_STREQ("-0.01", FormatTimeInMillisAsSeconds(-10)); 204 EXPECT_STREQ("-0.2", FormatTimeInMillisAsSeconds(-200)); 205 EXPECT_STREQ("-1.2", FormatTimeInMillisAsSeconds(-1200)); 206 EXPECT_STREQ("-3", FormatTimeInMillisAsSeconds(-3000)); 207} 208 209#if !GTEST_OS_SYMBIAN 210// NULL testing does not work with Symbian compilers. 211 212// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null 213// pointer literal. 214TEST(NullLiteralTest, IsTrueForNullLiterals) { 215 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL)); 216 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0)); 217 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1)); 218 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U)); 219 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L)); 220 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false)); 221 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false)); 222} 223 224// Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null 225// pointer literal. 226TEST(NullLiteralTest, IsFalseForNonNullLiterals) { 227 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1)); 228 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0)); 229 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a')); 230 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL))); 231} 232 233#endif // !GTEST_OS_SYMBIAN 234// 235// Tests CodePointToUtf8(). 236 237// Tests that the NUL character L'\0' is encoded correctly. 238TEST(CodePointToUtf8Test, CanEncodeNul) { 239 char buffer[32]; 240 EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer)); 241} 242 243// Tests that ASCII characters are encoded correctly. 244TEST(CodePointToUtf8Test, CanEncodeAscii) { 245 char buffer[32]; 246 EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer)); 247 EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer)); 248 EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer)); 249 EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer)); 250} 251 252// Tests that Unicode code-points that have 8 to 11 bits are encoded 253// as 110xxxxx 10xxxxxx. 254TEST(CodePointToUtf8Test, CanEncode8To11Bits) { 255 char buffer[32]; 256 // 000 1101 0011 => 110-00011 10-010011 257 EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer)); 258 259 // 101 0111 0110 => 110-10101 10-110110 260 EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer)); 261} 262 263// Tests that Unicode code-points that have 12 to 16 bits are encoded 264// as 1110xxxx 10xxxxxx 10xxxxxx. 265TEST(CodePointToUtf8Test, CanEncode12To16Bits) { 266 char buffer[32]; 267 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 268 EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer)); 269 270 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 271 EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer)); 272} 273 274#if !GTEST_WIDE_STRING_USES_UTF16_ 275// Tests in this group require a wchar_t to hold > 16 bits, and thus 276// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is 277// 16-bit wide. This code may not compile on those systems. 278 279// Tests that Unicode code-points that have 17 to 21 bits are encoded 280// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. 281TEST(CodePointToUtf8Test, CanEncode17To21Bits) { 282 char buffer[32]; 283 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 284 EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer)); 285 286 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000 287 EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer)); 288 289 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 290 EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer)); 291} 292 293// Tests that encoding an invalid code-point generates the expected result. 294TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) { 295 char buffer[32]; 296 EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)", 297 CodePointToUtf8(L'\x1234ABCD', buffer)); 298} 299 300#endif // !GTEST_WIDE_STRING_USES_UTF16_ 301 302// Tests WideStringToUtf8(). 303 304// Tests that the NUL character L'\0' is encoded correctly. 305TEST(WideStringToUtf8Test, CanEncodeNul) { 306 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str()); 307 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str()); 308} 309 310#if GTEST_HAS_STD_WSTRING 311// Tests that ASCII strings are encoded correctly. 312TEST(WideStringToUtf8Test, CanEncodeAscii) { 313 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str()); 314 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str()); 315 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str()); 316 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str()); 317} 318#endif // GTEST_HAS_STD_WSTRING 319 320// Tests that Unicode code-points that have 8 to 11 bits are encoded 321// as 110xxxxx 10xxxxxx. 322TEST(WideStringToUtf8Test, CanEncode8To11Bits) { 323 // 000 1101 0011 => 110-00011 10-010011 324 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str()); 325 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); 326 327 // 101 0111 0110 => 110-10101 10-110110 328 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str()); 329 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str()); 330} 331 332// Tests that Unicode code-points that have 12 to 16 bits are encoded 333// as 1110xxxx 10xxxxxx 10xxxxxx. 334TEST(WideStringToUtf8Test, CanEncode12To16Bits) { 335 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 336 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str()); 337 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str()); 338 339 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 340 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str()); 341 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str()); 342} 343 344// Tests that the conversion stops when the function encounters \0 character. 345TEST(WideStringToUtf8Test, StopsOnNulCharacter) { 346 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str()); 347} 348 349// Tests that the conversion stops when the function reaches the limit 350// specified by the 'length' parameter. 351TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) { 352 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str()); 353} 354 355 356#if !GTEST_WIDE_STRING_USES_UTF16_ 357// Tests that Unicode code-points that have 17 to 21 bits are encoded 358// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile 359// on the systems using UTF-16 encoding. 360TEST(WideStringToUtf8Test, CanEncode17To21Bits) { 361 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 362 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str()); 363 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str()); 364 365 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 366 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str()); 367 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str()); 368} 369 370// Tests that encoding an invalid code-point generates the expected result. 371TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { 372 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", 373 WideStringToUtf8(L"\xABCDFF", -1).c_str()); 374} 375#else // !GTEST_WIDE_STRING_USES_UTF16_ 376// Tests that surrogate pairs are encoded correctly on the systems using 377// UTF-16 encoding in the wide strings. 378TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { 379 EXPECT_STREQ("\xF0\x90\x90\x80", 380 WideStringToUtf8(L"\xD801\xDC00", -1).c_str()); 381} 382 383// Tests that encoding an invalid UTF-16 surrogate pair 384// generates the expected result. 385TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { 386 // Leading surrogate is at the end of the string. 387 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str()); 388 // Leading surrogate is not followed by the trailing surrogate. 389 EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str()); 390 // Trailing surrogate appearas without a leading surrogate. 391 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str()); 392} 393#endif // !GTEST_WIDE_STRING_USES_UTF16_ 394 395// Tests that codepoint concatenation works correctly. 396#if GTEST_HAS_STD_WSTRING 397#if !GTEST_WIDE_STRING_USES_UTF16_ 398TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { 399 EXPECT_STREQ( 400 "\xF4\x88\x98\xB4" 401 "\xEC\x9D\x8D" 402 "\n" 403 "\xD5\xB6" 404 "\xE0\xA3\x93" 405 "\xF4\x88\x98\xB4", 406 WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str()); 407} 408#else 409TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { 410 EXPECT_STREQ( 411 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", 412 WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str()); 413} 414#endif // !GTEST_WIDE_STRING_USES_UTF16_ 415#endif // GTEST_HAS_STD_WSTRING 416 417// Tests the List template class. 418 419// Tests List::PushFront(). 420TEST(ListTest, PushFront) { 421 List<int> a; 422 ASSERT_EQ(0u, a.size()); 423 424 // Calls PushFront() on an empty list. 425 a.PushFront(1); 426 ASSERT_EQ(1u, a.size()); 427 EXPECT_EQ(1, a.Head()->element()); 428 ASSERT_EQ(a.Head(), a.Last()); 429 430 // Calls PushFront() on a singleton list. 431 a.PushFront(2); 432 ASSERT_EQ(2u, a.size()); 433 EXPECT_EQ(2, a.Head()->element()); 434 EXPECT_EQ(1, a.Last()->element()); 435 436 // Calls PushFront() on a list with more than one elements. 437 a.PushFront(3); 438 ASSERT_EQ(3u, a.size()); 439 EXPECT_EQ(3, a.Head()->element()); 440 EXPECT_EQ(2, a.Head()->next()->element()); 441 EXPECT_EQ(1, a.Last()->element()); 442} 443 444// Tests List::PopFront(). 445TEST(ListTest, PopFront) { 446 List<int> a; 447 448 // Popping on an empty list should fail. 449 EXPECT_FALSE(a.PopFront(NULL)); 450 451 // Popping again on an empty list should fail, and the result element 452 // shouldn't be overwritten. 453 int element = 1; 454 EXPECT_FALSE(a.PopFront(&element)); 455 EXPECT_EQ(1, element); 456 457 a.PushFront(2); 458 a.PushFront(3); 459 460 // PopFront() should pop the element in the front of the list. 461 EXPECT_TRUE(a.PopFront(&element)); 462 EXPECT_EQ(3, element); 463 464 // After popping the last element, the list should be empty. 465 EXPECT_TRUE(a.PopFront(NULL)); 466 EXPECT_EQ(0u, a.size()); 467} 468 469// Tests inserting at the beginning using List::InsertAfter(). 470TEST(ListTest, InsertAfterAtBeginning) { 471 List<int> a; 472 ASSERT_EQ(0u, a.size()); 473 474 // Inserts into an empty list. 475 a.InsertAfter(NULL, 1); 476 ASSERT_EQ(1u, a.size()); 477 EXPECT_EQ(1, a.Head()->element()); 478 ASSERT_EQ(a.Head(), a.Last()); 479 480 // Inserts at the beginning of a singleton list. 481 a.InsertAfter(NULL, 2); 482 ASSERT_EQ(2u, a.size()); 483 EXPECT_EQ(2, a.Head()->element()); 484 EXPECT_EQ(1, a.Last()->element()); 485 486 // Inserts at the beginning of a list with more than one elements. 487 a.InsertAfter(NULL, 3); 488 ASSERT_EQ(3u, a.size()); 489 EXPECT_EQ(3, a.Head()->element()); 490 EXPECT_EQ(2, a.Head()->next()->element()); 491 EXPECT_EQ(1, a.Last()->element()); 492} 493 494// Tests inserting at a location other than the beginning using 495// List::InsertAfter(). 496TEST(ListTest, InsertAfterNotAtBeginning) { 497 // Prepares a singleton list. 498 List<int> a; 499 a.PushBack(1); 500 501 // Inserts at the end of a singleton list. 502 a.InsertAfter(a.Last(), 2); 503 ASSERT_EQ(2u, a.size()); 504 EXPECT_EQ(1, a.Head()->element()); 505 EXPECT_EQ(2, a.Last()->element()); 506 507 // Inserts at the end of a list with more than one elements. 508 a.InsertAfter(a.Last(), 3); 509 ASSERT_EQ(3u, a.size()); 510 EXPECT_EQ(1, a.Head()->element()); 511 EXPECT_EQ(2, a.Head()->next()->element()); 512 EXPECT_EQ(3, a.Last()->element()); 513 514 // Inserts in the middle of a list. 515 a.InsertAfter(a.Head(), 4); 516 ASSERT_EQ(4u, a.size()); 517 EXPECT_EQ(1, a.Head()->element()); 518 EXPECT_EQ(4, a.Head()->next()->element()); 519 EXPECT_EQ(2, a.Head()->next()->next()->element()); 520 EXPECT_EQ(3, a.Last()->element()); 521} 522 523 524// Tests the String class. 525 526// Tests String's constructors. 527TEST(StringTest, Constructors) { 528 // Default ctor. 529 String s1; 530 // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing 531 // pointers with NULL isn't supported on all platforms. 532 EXPECT_TRUE(NULL == s1.c_str()); 533 534 // Implicitly constructs from a C-string. 535 String s2 = "Hi"; 536 EXPECT_STREQ("Hi", s2.c_str()); 537 538 // Constructs from a C-string and a length. 539 String s3("hello", 3); 540 EXPECT_STREQ("hel", s3.c_str()); 541 542 // Copy ctor. 543 String s4 = s3; 544 EXPECT_STREQ("hel", s4.c_str()); 545} 546 547#if GTEST_HAS_STD_STRING 548 549TEST(StringTest, ConvertsFromStdString) { 550 // An empty std::string. 551 const std::string src1(""); 552 const String dest1 = src1; 553 EXPECT_STREQ("", dest1.c_str()); 554 555 // A normal std::string. 556 const std::string src2("Hi"); 557 const String dest2 = src2; 558 EXPECT_STREQ("Hi", dest2.c_str()); 559 560 // An std::string with an embedded NUL character. 561 const char src3[] = "Hello\0world."; 562 const String dest3 = std::string(src3, sizeof(src3)); 563 EXPECT_STREQ("Hello", dest3.c_str()); 564} 565 566TEST(StringTest, ConvertsToStdString) { 567 // An empty String. 568 const String src1(""); 569 const std::string dest1 = src1; 570 EXPECT_EQ("", dest1); 571 572 // A normal String. 573 const String src2("Hi"); 574 const std::string dest2 = src2; 575 EXPECT_EQ("Hi", dest2); 576} 577 578#endif // GTEST_HAS_STD_STRING 579 580#if GTEST_HAS_GLOBAL_STRING 581 582TEST(StringTest, ConvertsFromGlobalString) { 583 // An empty ::string. 584 const ::string src1(""); 585 const String dest1 = src1; 586 EXPECT_STREQ("", dest1.c_str()); 587 588 // A normal ::string. 589 const ::string src2("Hi"); 590 const String dest2 = src2; 591 EXPECT_STREQ("Hi", dest2.c_str()); 592 593 // An ::string with an embedded NUL character. 594 const char src3[] = "Hello\0world."; 595 const String dest3 = ::string(src3, sizeof(src3)); 596 EXPECT_STREQ("Hello", dest3.c_str()); 597} 598 599TEST(StringTest, ConvertsToGlobalString) { 600 // An empty String. 601 const String src1(""); 602 const ::string dest1 = src1; 603 EXPECT_EQ("", dest1); 604 605 // A normal String. 606 const String src2("Hi"); 607 const ::string dest2 = src2; 608 EXPECT_EQ("Hi", dest2); 609} 610 611#endif // GTEST_HAS_GLOBAL_STRING 612 613// Tests String::ShowCString(). 614TEST(StringTest, ShowCString) { 615 EXPECT_STREQ("(null)", String::ShowCString(NULL)); 616 EXPECT_STREQ("", String::ShowCString("")); 617 EXPECT_STREQ("foo", String::ShowCString("foo")); 618} 619 620// Tests String::ShowCStringQuoted(). 621TEST(StringTest, ShowCStringQuoted) { 622 EXPECT_STREQ("(null)", 623 String::ShowCStringQuoted(NULL).c_str()); 624 EXPECT_STREQ("\"\"", 625 String::ShowCStringQuoted("").c_str()); 626 EXPECT_STREQ("\"foo\"", 627 String::ShowCStringQuoted("foo").c_str()); 628} 629 630// Tests String::operator==(). 631TEST(StringTest, Equals) { 632 const String null(NULL); 633 EXPECT_TRUE(null == NULL); // NOLINT 634 EXPECT_FALSE(null == ""); // NOLINT 635 EXPECT_FALSE(null == "bar"); // NOLINT 636 637 const String empty(""); 638 EXPECT_FALSE(empty == NULL); // NOLINT 639 EXPECT_TRUE(empty == ""); // NOLINT 640 EXPECT_FALSE(empty == "bar"); // NOLINT 641 642 const String foo("foo"); 643 EXPECT_FALSE(foo == NULL); // NOLINT 644 EXPECT_FALSE(foo == ""); // NOLINT 645 EXPECT_FALSE(foo == "bar"); // NOLINT 646 EXPECT_TRUE(foo == "foo"); // NOLINT 647} 648 649// Tests String::operator!=(). 650TEST(StringTest, NotEquals) { 651 const String null(NULL); 652 EXPECT_FALSE(null != NULL); // NOLINT 653 EXPECT_TRUE(null != ""); // NOLINT 654 EXPECT_TRUE(null != "bar"); // NOLINT 655 656 const String empty(""); 657 EXPECT_TRUE(empty != NULL); // NOLINT 658 EXPECT_FALSE(empty != ""); // NOLINT 659 EXPECT_TRUE(empty != "bar"); // NOLINT 660 661 const String foo("foo"); 662 EXPECT_TRUE(foo != NULL); // NOLINT 663 EXPECT_TRUE(foo != ""); // NOLINT 664 EXPECT_TRUE(foo != "bar"); // NOLINT 665 EXPECT_FALSE(foo != "foo"); // NOLINT 666} 667 668// Tests String::EndsWith(). 669TEST(StringTest, EndsWith) { 670 EXPECT_TRUE(String("foobar").EndsWith("bar")); 671 EXPECT_TRUE(String("foobar").EndsWith("")); 672 EXPECT_TRUE(String("").EndsWith("")); 673 674 EXPECT_FALSE(String("foobar").EndsWith("foo")); 675 EXPECT_FALSE(String("").EndsWith("foo")); 676} 677 678// Tests String::EndsWithCaseInsensitive(). 679TEST(StringTest, EndsWithCaseInsensitive) { 680 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR")); 681 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar")); 682 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("")); 683 EXPECT_TRUE(String("").EndsWithCaseInsensitive("")); 684 685 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo")); 686 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo")); 687 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo")); 688} 689 690// Tests String::CaseInsensitiveWideCStringEquals 691TEST(StringTest, CaseInsensitiveWideCStringEquals) { 692 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL)); 693 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(NULL, L"")); 694 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", NULL)); 695 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(NULL, L"foobar")); 696 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", NULL)); 697 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar")); 698 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR")); 699 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar")); 700} 701 702// Tests that NULL can be assigned to a String. 703TEST(StringTest, CanBeAssignedNULL) { 704 const String src(NULL); 705 String dest; 706 707 dest = src; 708 EXPECT_STREQ(NULL, dest.c_str()); 709} 710 711// Tests that the empty string "" can be assigned to a String. 712TEST(StringTest, CanBeAssignedEmpty) { 713 const String src(""); 714 String dest; 715 716 dest = src; 717 EXPECT_STREQ("", dest.c_str()); 718} 719 720// Tests that a non-empty string can be assigned to a String. 721TEST(StringTest, CanBeAssignedNonEmpty) { 722 const String src("hello"); 723 String dest; 724 725 dest = src; 726 EXPECT_STREQ("hello", dest.c_str()); 727} 728 729// Tests that a String can be assigned to itself. 730TEST(StringTest, CanBeAssignedSelf) { 731 String dest("hello"); 732 733 dest = dest; 734 EXPECT_STREQ("hello", dest.c_str()); 735} 736 737#if GTEST_OS_WINDOWS 738 739// Tests String::ShowWideCString(). 740TEST(StringTest, ShowWideCString) { 741 EXPECT_STREQ("(null)", 742 String::ShowWideCString(NULL).c_str()); 743 EXPECT_STREQ("", String::ShowWideCString(L"").c_str()); 744 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str()); 745} 746 747// Tests String::ShowWideCStringQuoted(). 748TEST(StringTest, ShowWideCStringQuoted) { 749 EXPECT_STREQ("(null)", 750 String::ShowWideCStringQuoted(NULL).c_str()); 751 EXPECT_STREQ("L\"\"", 752 String::ShowWideCStringQuoted(L"").c_str()); 753 EXPECT_STREQ("L\"foo\"", 754 String::ShowWideCStringQuoted(L"foo").c_str()); 755} 756 757#ifdef _WIN32_WCE 758TEST(StringTest, AnsiAndUtf16Null) { 759 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL)); 760 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL)); 761} 762 763TEST(StringTest, AnsiAndUtf16ConvertBasic) { 764 const char* ansi = String::Utf16ToAnsi(L"str"); 765 EXPECT_STREQ("str", ansi); 766 delete [] ansi; 767 const WCHAR* utf16 = String::AnsiToUtf16("str"); 768 EXPECT_TRUE(wcsncmp(L"str", utf16, 3) == 0); 769 delete [] utf16; 770} 771 772TEST(StringTest, AnsiAndUtf16ConvertPathChars) { 773 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?"); 774 EXPECT_STREQ(".:\\ \"*?", ansi); 775 delete [] ansi; 776 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?"); 777 EXPECT_TRUE(wcsncmp(L".:\\ \"*?", utf16, 3) == 0); 778 delete [] utf16; 779} 780#endif // _WIN32_WCE 781 782#endif // GTEST_OS_WINDOWS 783 784// Tests TestProperty construction. 785TEST(TestPropertyTest, StringValue) { 786 TestProperty property("key", "1"); 787 EXPECT_STREQ("key", property.key()); 788 EXPECT_STREQ("1", property.value()); 789} 790 791// Tests TestProperty replacing a value. 792TEST(TestPropertyTest, ReplaceStringValue) { 793 TestProperty property("key", "1"); 794 EXPECT_STREQ("1", property.value()); 795 property.SetValue("2"); 796 EXPECT_STREQ("2", property.value()); 797} 798 799class ScopedFakeTestPartResultReporterTest : public Test { 800 protected: 801 enum FailureMode { 802 FATAL_FAILURE, 803 NONFATAL_FAILURE 804 }; 805 static void AddFailure(FailureMode failure) { 806 if (failure == FATAL_FAILURE) { 807 FAIL() << "Expected fatal failure."; 808 } else { 809 ADD_FAILURE() << "Expected non-fatal failure."; 810 } 811 } 812}; 813 814// Tests that ScopedFakeTestPartResultReporter intercepts test 815// failures. 816TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) { 817 TestPartResultArray results; 818 { 819 ScopedFakeTestPartResultReporter reporter( 820 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, 821 &results); 822 AddFailure(NONFATAL_FAILURE); 823 AddFailure(FATAL_FAILURE); 824 } 825 826 EXPECT_EQ(2, results.size()); 827 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); 828 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); 829} 830 831TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) { 832 TestPartResultArray results; 833 { 834 // Tests, that the deprecated constructor still works. 835 ScopedFakeTestPartResultReporter reporter(&results); 836 AddFailure(NONFATAL_FAILURE); 837 } 838 EXPECT_EQ(1, results.size()); 839} 840 841#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD 842 843class ScopedFakeTestPartResultReporterWithThreadsTest 844 : public ScopedFakeTestPartResultReporterTest { 845 protected: 846 static void AddFailureInOtherThread(FailureMode failure) { 847 pthread_t tid; 848 pthread_create(&tid, 849 NULL, 850 ScopedFakeTestPartResultReporterWithThreadsTest:: 851 FailureThread, 852 &failure); 853 pthread_join(tid, NULL); 854 } 855 private: 856 static void* FailureThread(void* attr) { 857 FailureMode* failure = static_cast<FailureMode*>(attr); 858 AddFailure(*failure); 859 return NULL; 860 } 861}; 862 863TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest, 864 InterceptsTestFailuresInAllThreads) { 865 TestPartResultArray results; 866 { 867 ScopedFakeTestPartResultReporter reporter( 868 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results); 869 AddFailure(NONFATAL_FAILURE); 870 AddFailure(FATAL_FAILURE); 871 AddFailureInOtherThread(NONFATAL_FAILURE); 872 AddFailureInOtherThread(FATAL_FAILURE); 873 } 874 875 EXPECT_EQ(4, results.size()); 876 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); 877 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); 878 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed()); 879 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed()); 880} 881 882#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD 883 884// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. 885 886typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest; 887 888TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) { 889 EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure."); 890} 891 892TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) { 893 // We have another test below to verify that the macro catches fatal 894 // failures generated on another thread. 895 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE), 896 "Expected fatal failure."); 897} 898 899// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void 900// function even when the statement in it contains ASSERT_*. 901 902int NonVoidFunction() { 903 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); 904 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); 905 return 0; 906} 907 908TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) { 909 NonVoidFunction(); 910} 911 912// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the 913// current function even though 'statement' generates a fatal failure. 914 915void DoesNotAbortHelper(bool* aborted) { 916 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); 917 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); 918 919 *aborted = false; 920} 921 922TEST_F(ExpectFatalFailureTest, DoesNotAbort) { 923 bool aborted = true; 924 DoesNotAbortHelper(&aborted); 925 EXPECT_FALSE(aborted); 926} 927 928// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a 929// statement that contains a macro which expands to code containing an 930// unprotected comma. 931 932static int global_var = 0; 933#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++ 934 935TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { 936 EXPECT_FATAL_FAILURE({ 937 GTEST_USE_UNPROTECTED_COMMA_; 938 AddFailure(FATAL_FAILURE); 939 }, ""); 940 941 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({ 942 GTEST_USE_UNPROTECTED_COMMA_; 943 AddFailure(FATAL_FAILURE); 944 }, ""); 945} 946 947// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}. 948 949typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest; 950 951TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { 952 EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), 953 "Expected non-fatal failure."); 954} 955 956TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { 957 // We have another test below to verify that the macro catches 958 // non-fatal failures generated on another thread. 959 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE), 960 "Expected non-fatal failure."); 961} 962 963// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a 964// statement that contains a macro which expands to code containing an 965// unprotected comma. 966TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { 967 EXPECT_NONFATAL_FAILURE({ 968 GTEST_USE_UNPROTECTED_COMMA_; 969 AddFailure(NONFATAL_FAILURE); 970 }, ""); 971 972 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({ 973 GTEST_USE_UNPROTECTED_COMMA_; 974 AddFailure(NONFATAL_FAILURE); 975 }, ""); 976} 977 978#if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD 979 980typedef ScopedFakeTestPartResultReporterWithThreadsTest 981 ExpectFailureWithThreadsTest; 982 983TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) { 984 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE), 985 "Expected fatal failure."); 986} 987 988TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) { 989 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( 990 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure."); 991} 992 993#endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD 994 995// Tests the TestResult class 996 997// The test fixture for testing TestResult. 998class TestResultTest : public Test { 999 protected: 1000 typedef List<TestPartResult> TPRList; 1001 1002 // We make use of 2 TestPartResult objects, 1003 TestPartResult * pr1, * pr2; 1004 1005 // ... and 3 TestResult objects. 1006 TestResult * r0, * r1, * r2; 1007 1008 virtual void SetUp() { 1009 // pr1 is for success. 1010 pr1 = new TestPartResult(TPRT_SUCCESS, "foo/bar.cc", 10, "Success!"); 1011 1012 // pr2 is for fatal failure. 1013 pr2 = new TestPartResult(TPRT_FATAL_FAILURE, "foo/bar.cc", 1014 -1, // This line number means "unknown" 1015 "Failure!"); 1016 1017 // Creates the TestResult objects. 1018 r0 = new TestResult(); 1019 r1 = new TestResult(); 1020 r2 = new TestResult(); 1021 1022 // In order to test TestResult, we need to modify its internal 1023 // state, in particular the TestPartResult list it holds. 1024 // test_part_results() returns a const reference to this list. 1025 // We cast it to a non-const object s.t. it can be modified (yes, 1026 // this is a hack). 1027 TPRList * list1, * list2; 1028 list1 = const_cast<List<TestPartResult> *>( 1029 & r1->test_part_results()); 1030 list2 = const_cast<List<TestPartResult> *>( 1031 & r2->test_part_results()); 1032 1033 // r0 is an empty TestResult. 1034 1035 // r1 contains a single SUCCESS TestPartResult. 1036 list1->PushBack(*pr1); 1037 1038 // r2 contains a SUCCESS, and a FAILURE. 1039 list2->PushBack(*pr1); 1040 list2->PushBack(*pr2); 1041 } 1042 1043 virtual void TearDown() { 1044 delete pr1; 1045 delete pr2; 1046 1047 delete r0; 1048 delete r1; 1049 delete r2; 1050 } 1051}; 1052 1053// Tests TestResult::test_part_results() 1054TEST_F(TestResultTest, test_part_results) { 1055 ASSERT_EQ(0u, r0->test_part_results().size()); 1056 ASSERT_EQ(1u, r1->test_part_results().size()); 1057 ASSERT_EQ(2u, r2->test_part_results().size()); 1058} 1059 1060// Tests TestResult::successful_part_count() 1061TEST_F(TestResultTest, successful_part_count) { 1062 ASSERT_EQ(0u, r0->successful_part_count()); 1063 ASSERT_EQ(1u, r1->successful_part_count()); 1064 ASSERT_EQ(1u, r2->successful_part_count()); 1065} 1066 1067// Tests TestResult::failed_part_count() 1068TEST_F(TestResultTest, failed_part_count) { 1069 ASSERT_EQ(0u, r0->failed_part_count()); 1070 ASSERT_EQ(0u, r1->failed_part_count()); 1071 ASSERT_EQ(1u, r2->failed_part_count()); 1072} 1073 1074// Tests testing::internal::GetFailedPartCount(). 1075TEST_F(TestResultTest, GetFailedPartCount) { 1076 ASSERT_EQ(0u, GetFailedPartCount(r0)); 1077 ASSERT_EQ(0u, GetFailedPartCount(r1)); 1078 ASSERT_EQ(1u, GetFailedPartCount(r2)); 1079} 1080 1081// Tests TestResult::total_part_count() 1082TEST_F(TestResultTest, total_part_count) { 1083 ASSERT_EQ(0u, r0->total_part_count()); 1084 ASSERT_EQ(1u, r1->total_part_count()); 1085 ASSERT_EQ(2u, r2->total_part_count()); 1086} 1087 1088// Tests TestResult::Passed() 1089TEST_F(TestResultTest, Passed) { 1090 ASSERT_TRUE(r0->Passed()); 1091 ASSERT_TRUE(r1->Passed()); 1092 ASSERT_FALSE(r2->Passed()); 1093} 1094 1095// Tests TestResult::Failed() 1096TEST_F(TestResultTest, Failed) { 1097 ASSERT_FALSE(r0->Failed()); 1098 ASSERT_FALSE(r1->Failed()); 1099 ASSERT_TRUE(r2->Failed()); 1100} 1101 1102// Tests TestResult::test_properties() has no properties when none are added. 1103TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) { 1104 TestResult test_result; 1105 ASSERT_EQ(0u, test_result.test_properties().size()); 1106} 1107 1108// Tests TestResult::test_properties() has the expected property when added. 1109TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) { 1110 TestResult test_result; 1111 TestProperty property("key_1", "1"); 1112 test_result.RecordProperty(property); 1113 const List<TestProperty>& properties = test_result.test_properties(); 1114 ASSERT_EQ(1u, properties.size()); 1115 TestProperty actual_property = properties.Head()->element(); 1116 EXPECT_STREQ("key_1", actual_property.key()); 1117 EXPECT_STREQ("1", actual_property.value()); 1118} 1119 1120// Tests TestResult::test_properties() has multiple properties when added. 1121TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) { 1122 TestResult test_result; 1123 TestProperty property_1("key_1", "1"); 1124 TestProperty property_2("key_2", "2"); 1125 test_result.RecordProperty(property_1); 1126 test_result.RecordProperty(property_2); 1127 const List<TestProperty>& properties = test_result.test_properties(); 1128 ASSERT_EQ(2u, properties.size()); 1129 TestProperty actual_property_1 = properties.Head()->element(); 1130 EXPECT_STREQ("key_1", actual_property_1.key()); 1131 EXPECT_STREQ("1", actual_property_1.value()); 1132 1133 TestProperty actual_property_2 = properties.Last()->element(); 1134 EXPECT_STREQ("key_2", actual_property_2.key()); 1135 EXPECT_STREQ("2", actual_property_2.value()); 1136} 1137 1138// Tests TestResult::test_properties() overrides values for duplicate keys. 1139TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) { 1140 TestResult test_result; 1141 TestProperty property_1_1("key_1", "1"); 1142 TestProperty property_2_1("key_2", "2"); 1143 TestProperty property_1_2("key_1", "12"); 1144 TestProperty property_2_2("key_2", "22"); 1145 test_result.RecordProperty(property_1_1); 1146 test_result.RecordProperty(property_2_1); 1147 test_result.RecordProperty(property_1_2); 1148 test_result.RecordProperty(property_2_2); 1149 1150 const List<TestProperty>& properties = test_result.test_properties(); 1151 ASSERT_EQ(2u, properties.size()); 1152 TestProperty actual_property_1 = properties.Head()->element(); 1153 EXPECT_STREQ("key_1", actual_property_1.key()); 1154 EXPECT_STREQ("12", actual_property_1.value()); 1155 1156 TestProperty actual_property_2 = properties.Last()->element(); 1157 EXPECT_STREQ("key_2", actual_property_2.key()); 1158 EXPECT_STREQ("22", actual_property_2.value()); 1159} 1160 1161// When a property using a reserved key is supplied to this function, it tests 1162// that a non-fatal failure is added, a fatal failure is not added, and that the 1163// property is not recorded. 1164void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) { 1165 TestResult test_result; 1166 TestProperty property(key, "1"); 1167 EXPECT_NONFATAL_FAILURE(test_result.RecordProperty(property), "Reserved key"); 1168 ASSERT_TRUE(test_result.test_properties().IsEmpty()) << "Not recorded"; 1169} 1170 1171// Attempting to recording a property with the Reserved literal "name" 1172// should add a non-fatal failure and the property should not be recorded. 1173TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) { 1174 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name"); 1175} 1176 1177// Attempting to recording a property with the Reserved literal "status" 1178// should add a non-fatal failure and the property should not be recorded. 1179TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) { 1180 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status"); 1181} 1182 1183// Attempting to recording a property with the Reserved literal "time" 1184// should add a non-fatal failure and the property should not be recorded. 1185TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) { 1186 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time"); 1187} 1188 1189// Attempting to recording a property with the Reserved literal "classname" 1190// should add a non-fatal failure and the property should not be recorded. 1191TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) { 1192 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname"); 1193} 1194 1195// Tests that GTestFlagSaver works on Windows and Mac. 1196 1197class GTestFlagSaverTest : public Test { 1198 protected: 1199 // Saves the Google Test flags such that we can restore them later, and 1200 // then sets them to their default values. This will be called 1201 // before the first test in this test case is run. 1202 static void SetUpTestCase() { 1203 saver_ = new GTestFlagSaver; 1204 1205 GTEST_FLAG(also_run_disabled_tests) = false; 1206 GTEST_FLAG(break_on_failure) = false; 1207 GTEST_FLAG(catch_exceptions) = false; 1208 GTEST_FLAG(death_test_use_fork) = false; 1209 GTEST_FLAG(color) = "auto"; 1210 GTEST_FLAG(filter) = ""; 1211 GTEST_FLAG(list_tests) = false; 1212 GTEST_FLAG(output) = ""; 1213 GTEST_FLAG(print_time) = false; 1214 GTEST_FLAG(repeat) = 1; 1215 GTEST_FLAG(throw_on_failure) = false; 1216 } 1217 1218 // Restores the Google Test flags that the tests have modified. This will 1219 // be called after the last test in this test case is run. 1220 static void TearDownTestCase() { 1221 delete saver_; 1222 saver_ = NULL; 1223 } 1224 1225 // Verifies that the Google Test flags have their default values, and then 1226 // modifies each of them. 1227 void VerifyAndModifyFlags() { 1228 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests)); 1229 EXPECT_FALSE(GTEST_FLAG(break_on_failure)); 1230 EXPECT_FALSE(GTEST_FLAG(catch_exceptions)); 1231 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str()); 1232 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork)); 1233 EXPECT_STREQ("", GTEST_FLAG(filter).c_str()); 1234 EXPECT_FALSE(GTEST_FLAG(list_tests)); 1235 EXPECT_STREQ("", GTEST_FLAG(output).c_str()); 1236 EXPECT_FALSE(GTEST_FLAG(print_time)); 1237 EXPECT_EQ(1, GTEST_FLAG(repeat)); 1238 EXPECT_FALSE(GTEST_FLAG(throw_on_failure)); 1239 1240 GTEST_FLAG(also_run_disabled_tests) = true; 1241 GTEST_FLAG(break_on_failure) = true; 1242 GTEST_FLAG(catch_exceptions) = true; 1243 GTEST_FLAG(color) = "no"; 1244 GTEST_FLAG(death_test_use_fork) = true; 1245 GTEST_FLAG(filter) = "abc"; 1246 GTEST_FLAG(list_tests) = true; 1247 GTEST_FLAG(output) = "xml:foo.xml"; 1248 GTEST_FLAG(print_time) = true; 1249 GTEST_FLAG(repeat) = 100; 1250 GTEST_FLAG(throw_on_failure) = true; 1251 } 1252 private: 1253 // For saving Google Test flags during this test case. 1254 static GTestFlagSaver* saver_; 1255}; 1256 1257GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL; 1258 1259// Google Test doesn't guarantee the order of tests. The following two 1260// tests are designed to work regardless of their order. 1261 1262// Modifies the Google Test flags in the test body. 1263TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { 1264 VerifyAndModifyFlags(); 1265} 1266 1267// Verifies that the Google Test flags in the body of the previous test were 1268// restored to their original values. 1269TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { 1270 VerifyAndModifyFlags(); 1271} 1272 1273// Sets an environment variable with the given name to the given 1274// value. If the value argument is "", unsets the environment 1275// variable. The caller must ensure that both arguments are not NULL. 1276static void SetEnv(const char* name, const char* value) { 1277#ifdef _WIN32_WCE 1278 // Environment variables are not supported on Windows CE. 1279 return; 1280#elif GTEST_OS_WINDOWS // If we are on Windows proper. 1281 _putenv((Message() << name << "=" << value).GetString().c_str()); 1282#else 1283 if (*value == '\0') { 1284 unsetenv(name); 1285 } else { 1286 setenv(name, value, 1); 1287 } 1288#endif 1289} 1290 1291#ifndef _WIN32_WCE 1292// Environment variables are not supported on Windows CE. 1293 1294using testing::internal::Int32FromGTestEnv; 1295 1296// Tests Int32FromGTestEnv(). 1297 1298// Tests that Int32FromGTestEnv() returns the default value when the 1299// environment variable is not set. 1300TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) { 1301 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", ""); 1302 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10)); 1303} 1304 1305// Tests that Int32FromGTestEnv() returns the default value when the 1306// environment variable overflows as an Int32. 1307TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) { 1308 printf("(expecting 2 warnings)\n"); 1309 1310 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321"); 1311 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20)); 1312 1313 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321"); 1314 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30)); 1315} 1316 1317// Tests that Int32FromGTestEnv() returns the default value when the 1318// environment variable does not represent a valid decimal integer. 1319TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) { 1320 printf("(expecting 2 warnings)\n"); 1321 1322 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1"); 1323 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40)); 1324 1325 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X"); 1326 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50)); 1327} 1328 1329// Tests that Int32FromGTestEnv() parses and returns the value of the 1330// environment variable when it represents a valid decimal integer in 1331// the range of an Int32. 1332TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) { 1333 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123"); 1334 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0)); 1335 1336 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321"); 1337 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0)); 1338} 1339#endif // !defined(_WIN32_WCE) 1340 1341// Tests ParseInt32Flag(). 1342 1343// Tests that ParseInt32Flag() returns false and doesn't change the 1344// output value when the flag has wrong format 1345TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { 1346 Int32 value = 123; 1347 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value)); 1348 EXPECT_EQ(123, value); 1349 1350 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value)); 1351 EXPECT_EQ(123, value); 1352} 1353 1354// Tests that ParseInt32Flag() returns false and doesn't change the 1355// output value when the flag overflows as an Int32. 1356TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { 1357 printf("(expecting 2 warnings)\n"); 1358 1359 Int32 value = 123; 1360 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value)); 1361 EXPECT_EQ(123, value); 1362 1363 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value)); 1364 EXPECT_EQ(123, value); 1365} 1366 1367// Tests that ParseInt32Flag() returns false and doesn't change the 1368// output value when the flag does not represent a valid decimal 1369// integer. 1370TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { 1371 printf("(expecting 2 warnings)\n"); 1372 1373 Int32 value = 123; 1374 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value)); 1375 EXPECT_EQ(123, value); 1376 1377 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value)); 1378 EXPECT_EQ(123, value); 1379} 1380 1381// Tests that ParseInt32Flag() parses the value of the flag and 1382// returns true when the flag represents a valid decimal integer in 1383// the range of an Int32. 1384TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) { 1385 Int32 value = 123; 1386 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); 1387 EXPECT_EQ(456, value); 1388 1389 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value)); 1390 EXPECT_EQ(-789, value); 1391} 1392 1393// Tests that Int32FromEnvOrDie() parses the value of the var or 1394// returns the correct default. 1395TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { 1396 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); 1397 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123"); 1398 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); 1399 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123"); 1400 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); 1401} 1402 1403#if GTEST_HAS_DEATH_TEST 1404 1405// Tests that Int32FromEnvOrDie() aborts with an error message 1406// if the variable is not an Int32. 1407TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { 1408 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); 1409 EXPECT_DEATH({Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123);}, 1410 ".*"); 1411} 1412 1413// Tests that Int32FromEnvOrDie() aborts with an error message 1414// if the variable cannot be represnted by an Int32. 1415TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { 1416 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); 1417 EXPECT_DEATH({Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123);}, 1418 ".*"); 1419} 1420 1421#endif // GTEST_HAS_DEATH_TEST 1422 1423 1424// Tests that ShouldRunTestOnShard() selects all tests 1425// where there is 1 shard. 1426TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) { 1427 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0)); 1428 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1)); 1429 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2)); 1430 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3)); 1431 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4)); 1432} 1433 1434class ShouldShardTest : public testing::Test { 1435 protected: 1436 virtual void SetUp() { 1437 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX"; 1438 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL"; 1439 } 1440 1441 virtual void TearDown() { 1442 SetEnv(index_var_, ""); 1443 SetEnv(total_var_, ""); 1444 } 1445 1446 const char* index_var_; 1447 const char* total_var_; 1448}; 1449 1450// Tests that sharding is disabled if neither of the environment variables 1451// are set. 1452TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) { 1453 SetEnv(index_var_, ""); 1454 SetEnv(total_var_, ""); 1455 1456 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); 1457 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1458} 1459 1460// Tests that sharding is not enabled if total_shards == 1. 1461TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) { 1462 SetEnv(index_var_, "0"); 1463 SetEnv(total_var_, "1"); 1464 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); 1465 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1466} 1467 1468// Tests that sharding is enabled if total_shards > 1 and 1469// we are not in a death test subprocess. 1470TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) { 1471 SetEnv(index_var_, "4"); 1472 SetEnv(total_var_, "22"); 1473 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); 1474 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1475 1476 SetEnv(index_var_, "8"); 1477 SetEnv(total_var_, "9"); 1478 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); 1479 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1480 1481 SetEnv(index_var_, "0"); 1482 SetEnv(total_var_, "9"); 1483 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); 1484 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); 1485} 1486 1487#if GTEST_HAS_DEATH_TEST 1488 1489// Tests that we exit in error if the sharding values are not valid. 1490TEST_F(ShouldShardTest, AbortsWhenShardingEnvVarsAreInvalid) { 1491 SetEnv(index_var_, "4"); 1492 SetEnv(total_var_, "4"); 1493 EXPECT_DEATH({ShouldShard(total_var_, index_var_, false);}, 1494 ".*"); 1495 1496 SetEnv(index_var_, "4"); 1497 SetEnv(total_var_, "-2"); 1498 EXPECT_DEATH({ShouldShard(total_var_, index_var_, false);}, 1499 ".*"); 1500 1501 SetEnv(index_var_, "5"); 1502 SetEnv(total_var_, ""); 1503 EXPECT_DEATH({ShouldShard(total_var_, index_var_, false);}, 1504 ".*"); 1505 1506 SetEnv(index_var_, ""); 1507 SetEnv(total_var_, "5"); 1508 EXPECT_DEATH({ShouldShard(total_var_, index_var_, false);}, 1509 ".*"); 1510} 1511 1512#endif // GTEST_HAS_DEATH_TEST 1513 1514// Tests that ShouldRunTestOnShard is a partition when 5 1515// shards are used. 1516TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) { 1517 // Choose an arbitrary number of tests and shards. 1518 const int num_tests = 17; 1519 const int num_shards = 5; 1520 1521 // Check partitioning: each test should be on exactly 1 shard. 1522 for (int test_id = 0; test_id < num_tests; test_id++) { 1523 int prev_selected_shard_index = -1; 1524 for (int shard_index = 0; shard_index < num_shards; shard_index++) { 1525 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) { 1526 if (prev_selected_shard_index < 0) { 1527 prev_selected_shard_index = shard_index; 1528 } else { 1529 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and " 1530 << shard_index << " are both selected to run test " << test_id; 1531 } 1532 } 1533 } 1534 } 1535 1536 // Check balance: This is not required by the sharding protocol, but is a 1537 // desirable property for performance. 1538 for (int shard_index = 0; shard_index < num_shards; shard_index++) { 1539 int num_tests_on_shard = 0; 1540 for (int test_id = 0; test_id < num_tests; test_id++) { 1541 num_tests_on_shard += 1542 ShouldRunTestOnShard(num_shards, shard_index, test_id); 1543 } 1544 EXPECT_GE(num_tests_on_shard, num_tests / num_shards); 1545 } 1546} 1547 1548// For the same reason we are not explicitly testing everything in the 1549// Test class, there are no separate tests for the following classes 1550// (except for some trivial cases): 1551// 1552// TestCase, UnitTest, UnitTestResultPrinter. 1553// 1554// Similarly, there are no separate tests for the following macros: 1555// 1556// TEST, TEST_F, RUN_ALL_TESTS 1557 1558TEST(UnitTestTest, CanGetOriginalWorkingDir) { 1559 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL); 1560 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), ""); 1561} 1562 1563// This group of tests is for predicate assertions (ASSERT_PRED*, etc) 1564// of various arities. They do not attempt to be exhaustive. Rather, 1565// view them as smoke tests that can be easily reviewed and verified. 1566// A more complete set of tests for predicate assertions can be found 1567// in gtest_pred_impl_unittest.cc. 1568 1569// First, some predicates and predicate-formatters needed by the tests. 1570 1571// Returns true iff the argument is an even number. 1572bool IsEven(int n) { 1573 return (n % 2) == 0; 1574} 1575 1576// A functor that returns true iff the argument is an even number. 1577struct IsEvenFunctor { 1578 bool operator()(int n) { return IsEven(n); } 1579}; 1580 1581// A predicate-formatter function that asserts the argument is an even 1582// number. 1583AssertionResult AssertIsEven(const char* expr, int n) { 1584 if (IsEven(n)) { 1585 return AssertionSuccess(); 1586 } 1587 1588 Message msg; 1589 msg << expr << " evaluates to " << n << ", which is not even."; 1590 return AssertionFailure(msg); 1591} 1592 1593// A predicate-formatter functor that asserts the argument is an even 1594// number. 1595struct AssertIsEvenFunctor { 1596 AssertionResult operator()(const char* expr, int n) { 1597 return AssertIsEven(expr, n); 1598 } 1599}; 1600 1601// Returns true iff the sum of the arguments is an even number. 1602bool SumIsEven2(int n1, int n2) { 1603 return IsEven(n1 + n2); 1604} 1605 1606// A functor that returns true iff the sum of the arguments is an even 1607// number. 1608struct SumIsEven3Functor { 1609 bool operator()(int n1, int n2, int n3) { 1610 return IsEven(n1 + n2 + n3); 1611 } 1612}; 1613 1614// A predicate-formatter function that asserts the sum of the 1615// arguments is an even number. 1616AssertionResult AssertSumIsEven4( 1617 const char* e1, const char* e2, const char* e3, const char* e4, 1618 int n1, int n2, int n3, int n4) { 1619 const int sum = n1 + n2 + n3 + n4; 1620 if (IsEven(sum)) { 1621 return AssertionSuccess(); 1622 } 1623 1624 Message msg; 1625 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 1626 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 1627 << ") evaluates to " << sum << ", which is not even."; 1628 return AssertionFailure(msg); 1629} 1630 1631// A predicate-formatter functor that asserts the sum of the arguments 1632// is an even number. 1633struct AssertSumIsEven5Functor { 1634 AssertionResult operator()( 1635 const char* e1, const char* e2, const char* e3, const char* e4, 1636 const char* e5, int n1, int n2, int n3, int n4, int n5) { 1637 const int sum = n1 + n2 + n3 + n4 + n5; 1638 if (IsEven(sum)) { 1639 return AssertionSuccess(); 1640 } 1641 1642 Message msg; 1643 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 1644 << " (" 1645 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5 1646 << ") evaluates to " << sum << ", which is not even."; 1647 return AssertionFailure(msg); 1648 } 1649}; 1650 1651 1652// Tests unary predicate assertions. 1653 1654// Tests unary predicate assertions that don't use a custom formatter. 1655TEST(Pred1Test, WithoutFormat) { 1656 // Success cases. 1657 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!"; 1658 ASSERT_PRED1(IsEven, 4); 1659 1660 // Failure cases. 1661 EXPECT_NONFATAL_FAILURE({ // NOLINT 1662 EXPECT_PRED1(IsEven, 5) << "This failure is expected."; 1663 }, "This failure is expected."); 1664 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), 1665 "evaluates to false"); 1666} 1667 1668// Tests unary predicate assertions that use a custom formatter. 1669TEST(Pred1Test, WithFormat) { 1670 // Success cases. 1671 EXPECT_PRED_FORMAT1(AssertIsEven, 2); 1672 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4) 1673 << "This failure is UNEXPECTED!"; 1674 1675 // Failure cases. 1676 const int n = 5; 1677 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n), 1678 "n evaluates to 5, which is not even."); 1679 EXPECT_FATAL_FAILURE({ // NOLINT 1680 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected."; 1681 }, "This failure is expected."); 1682} 1683 1684// Tests that unary predicate assertions evaluates their arguments 1685// exactly once. 1686TEST(Pred1Test, SingleEvaluationOnFailure) { 1687 // A success case. 1688 static int n = 0; 1689 EXPECT_PRED1(IsEven, n++); 1690 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once."; 1691 1692 // A failure case. 1693 EXPECT_FATAL_FAILURE({ // NOLINT 1694 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++) 1695 << "This failure is expected."; 1696 }, "This failure is expected."); 1697 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once."; 1698} 1699 1700 1701// Tests predicate assertions whose arity is >= 2. 1702 1703// Tests predicate assertions that don't use a custom formatter. 1704TEST(PredTest, WithoutFormat) { 1705 // Success cases. 1706 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!"; 1707 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8); 1708 1709 // Failure cases. 1710 const int n1 = 1; 1711 const int n2 = 2; 1712 EXPECT_NONFATAL_FAILURE({ // NOLINT 1713 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected."; 1714 }, "This failure is expected."); 1715 EXPECT_FATAL_FAILURE({ // NOLINT 1716 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4); 1717 }, "evaluates to false"); 1718} 1719 1720// Tests predicate assertions that use a custom formatter. 1721TEST(PredTest, WithFormat) { 1722 // Success cases. 1723 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) << 1724 "This failure is UNEXPECTED!"; 1725 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10); 1726 1727 // Failure cases. 1728 const int n1 = 1; 1729 const int n2 = 2; 1730 const int n3 = 4; 1731 const int n4 = 6; 1732 EXPECT_NONFATAL_FAILURE({ // NOLINT 1733 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4); 1734 }, "evaluates to 13, which is not even."); 1735 EXPECT_FATAL_FAILURE({ // NOLINT 1736 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8) 1737 << "This failure is expected."; 1738 }, "This failure is expected."); 1739} 1740 1741// Tests that predicate assertions evaluates their arguments 1742// exactly once. 1743TEST(PredTest, SingleEvaluationOnFailure) { 1744 // A success case. 1745 int n1 = 0; 1746 int n2 = 0; 1747 EXPECT_PRED2(SumIsEven2, n1++, n2++); 1748 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; 1749 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; 1750 1751 // Another success case. 1752 n1 = n2 = 0; 1753 int n3 = 0; 1754 int n4 = 0; 1755 int n5 = 0; 1756 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1757 n1++, n2++, n3++, n4++, n5++) 1758 << "This failure is UNEXPECTED!"; 1759 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; 1760 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; 1761 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; 1762 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; 1763 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once."; 1764 1765 // A failure case. 1766 n1 = n2 = n3 = 0; 1767 EXPECT_NONFATAL_FAILURE({ // NOLINT 1768 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++) 1769 << "This failure is expected."; 1770 }, "This failure is expected."); 1771 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; 1772 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; 1773 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; 1774 1775 // Another failure case. 1776 n1 = n2 = n3 = n4 = 0; 1777 EXPECT_NONFATAL_FAILURE({ // NOLINT 1778 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++); 1779 }, "evaluates to 1, which is not even."); 1780 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; 1781 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; 1782 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; 1783 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; 1784} 1785 1786 1787// Some helper functions for testing using overloaded/template 1788// functions with ASSERT_PREDn and EXPECT_PREDn. 1789 1790bool IsPositive(int n) { 1791 return n > 0; 1792} 1793 1794bool IsPositive(double x) { 1795 return x > 0; 1796} 1797 1798template <typename T> 1799bool IsNegative(T x) { 1800 return x < 0; 1801} 1802 1803template <typename T1, typename T2> 1804bool GreaterThan(T1 x1, T2 x2) { 1805 return x1 > x2; 1806} 1807 1808// Tests that overloaded functions can be used in *_PRED* as long as 1809// their types are explicitly specified. 1810TEST(PredicateAssertionTest, AcceptsOverloadedFunction) { 1811 EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5); // NOLINT 1812 ASSERT_PRED1(static_cast<bool (*)(double)>(IsPositive), 6.0); // NOLINT 1813} 1814 1815// Tests that template functions can be used in *_PRED* as long as 1816// their types are explicitly specified. 1817TEST(PredicateAssertionTest, AcceptsTemplateFunction) { 1818 EXPECT_PRED1(IsNegative<int>, -5); 1819 // Makes sure that we can handle templates with more than one 1820 // parameter. 1821 ASSERT_PRED2((GreaterThan<int, int>), 5, 0); 1822} 1823 1824 1825// Some helper functions for testing using overloaded/template 1826// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn. 1827 1828AssertionResult IsPositiveFormat(const char* /* expr */, int n) { 1829 return n > 0 ? AssertionSuccess() : 1830 AssertionFailure(Message() << "Failure"); 1831} 1832 1833AssertionResult IsPositiveFormat(const char* /* expr */, double x) { 1834 return x > 0 ? AssertionSuccess() : 1835 AssertionFailure(Message() << "Failure"); 1836} 1837 1838template <typename T> 1839AssertionResult IsNegativeFormat(const char* /* expr */, T x) { 1840 return x < 0 ? AssertionSuccess() : 1841 AssertionFailure(Message() << "Failure"); 1842} 1843 1844template <typename T1, typename T2> 1845AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */, 1846 const T1& x1, const T2& x2) { 1847 return x1 == x2 ? AssertionSuccess() : 1848 AssertionFailure(Message() << "Failure"); 1849} 1850 1851// Tests that overloaded functions can be used in *_PRED_FORMAT* 1852// without explicitly specifying their types. 1853TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) { 1854 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5); 1855 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0); 1856} 1857 1858// Tests that template functions can be used in *_PRED_FORMAT* without 1859// explicitly specifying their types. 1860TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) { 1861 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5); 1862 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3); 1863} 1864 1865 1866// Tests string assertions. 1867 1868// Tests ASSERT_STREQ with non-NULL arguments. 1869TEST(StringAssertionTest, ASSERT_STREQ) { 1870 const char * const p1 = "good"; 1871 ASSERT_STREQ(p1, p1); 1872 1873 // Let p2 have the same content as p1, but be at a different address. 1874 const char p2[] = "good"; 1875 ASSERT_STREQ(p1, p2); 1876 1877 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), 1878 "Expected: \"bad\""); 1879} 1880 1881// Tests ASSERT_STREQ with NULL arguments. 1882TEST(StringAssertionTest, ASSERT_STREQ_Null) { 1883 ASSERT_STREQ(static_cast<const char *>(NULL), NULL); 1884 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"), 1885 "non-null"); 1886} 1887 1888// Tests ASSERT_STREQ with NULL arguments. 1889TEST(StringAssertionTest, ASSERT_STREQ_Null2) { 1890 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL), 1891 "non-null"); 1892} 1893 1894// Tests ASSERT_STRNE. 1895TEST(StringAssertionTest, ASSERT_STRNE) { 1896 ASSERT_STRNE("hi", "Hi"); 1897 ASSERT_STRNE("Hi", NULL); 1898 ASSERT_STRNE(NULL, "Hi"); 1899 ASSERT_STRNE("", NULL); 1900 ASSERT_STRNE(NULL, ""); 1901 ASSERT_STRNE("", "Hi"); 1902 ASSERT_STRNE("Hi", ""); 1903 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), 1904 "\"Hi\" vs \"Hi\""); 1905} 1906 1907// Tests ASSERT_STRCASEEQ. 1908TEST(StringAssertionTest, ASSERT_STRCASEEQ) { 1909 ASSERT_STRCASEEQ("hi", "Hi"); 1910 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL); 1911 1912 ASSERT_STRCASEEQ("", ""); 1913 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), 1914 "(ignoring case)"); 1915} 1916 1917// Tests ASSERT_STRCASENE. 1918TEST(StringAssertionTest, ASSERT_STRCASENE) { 1919 ASSERT_STRCASENE("hi1", "Hi2"); 1920 ASSERT_STRCASENE("Hi", NULL); 1921 ASSERT_STRCASENE(NULL, "Hi"); 1922 ASSERT_STRCASENE("", NULL); 1923 ASSERT_STRCASENE(NULL, ""); 1924 ASSERT_STRCASENE("", "Hi"); 1925 ASSERT_STRCASENE("Hi", ""); 1926 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), 1927 "(ignoring case)"); 1928} 1929 1930#if GTEST_HAS_STD_WSTRING 1931// Tests *_STREQ on wide strings. 1932TEST(StringAssertionTest, STREQ_Wide) { 1933 // NULL strings. 1934 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL); 1935 1936 // Empty strings. 1937 ASSERT_STREQ(L"", L""); 1938 1939 // Non-null vs NULL. 1940 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL), 1941 "non-null"); 1942 1943 // Equal strings. 1944 EXPECT_STREQ(L"Hi", L"Hi"); 1945 1946 // Unequal strings. 1947 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), 1948 "Abc"); 1949 1950 // Strings containing wide characters. 1951 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), 1952 "abc"); 1953} 1954#endif // GTEST_HAS_STD_WSTRING 1955 1956// Tests *_STRNE on wide strings. 1957TEST(StringAssertionTest, STRNE_Wide) { 1958 // NULL strings. 1959 EXPECT_NONFATAL_FAILURE({ // NOLINT 1960 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL); 1961 }, ""); 1962 1963 // Empty strings. 1964 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), 1965 "L\"\""); 1966 1967 // Non-null vs NULL. 1968 ASSERT_STRNE(L"non-null", NULL); 1969 1970 // Equal strings. 1971 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), 1972 "L\"Hi\""); 1973 1974 // Unequal strings. 1975 EXPECT_STRNE(L"abc", L"Abc"); 1976 1977 // Strings containing wide characters. 1978 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), 1979 "abc"); 1980} 1981 1982// Tests for ::testing::IsSubstring(). 1983 1984// Tests that IsSubstring() returns the correct result when the input 1985// argument type is const char*. 1986TEST(IsSubstringTest, ReturnsCorrectResultForCString) { 1987 EXPECT_FALSE(IsSubstring("", "", NULL, "a")); 1988 EXPECT_FALSE(IsSubstring("", "", "b", NULL)); 1989 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack")); 1990 1991 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL)); 1992 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles")); 1993} 1994 1995#if GTEST_HAS_STD_WSTRING 1996// Tests that IsSubstring() returns the correct result when the input 1997// argument type is const wchar_t*. 1998TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) { 1999 EXPECT_FALSE(IsSubstring("", "", NULL, L"a")); 2000 EXPECT_FALSE(IsSubstring("", "", L"b", NULL)); 2001 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack")); 2002 2003 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL)); 2004 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles")); 2005} 2006#endif // GTEST_HAS_STD_WSTRING 2007 2008// Tests that IsSubstring() generates the correct message when the input 2009// argument type is const char*. 2010TEST(IsSubstringTest, GeneratesCorrectMessageForCString) { 2011 EXPECT_STREQ("Value of: needle_expr\n" 2012 " Actual: \"needle\"\n" 2013 "Expected: a substring of haystack_expr\n" 2014 "Which is: \"haystack\"", 2015 IsSubstring("needle_expr", "haystack_expr", 2016 "needle", "haystack").failure_message()); 2017} 2018 2019#if GTEST_HAS_STD_STRING 2020 2021// Tests that IsSubstring returns the correct result when the input 2022// argument type is ::std::string. 2023TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) { 2024 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob")); 2025 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world"))); 2026} 2027 2028#endif // GTEST_HAS_STD_STRING 2029 2030 2031#if GTEST_HAS_STD_WSTRING 2032// Tests that IsSubstring returns the correct result when the input 2033// argument type is ::std::wstring. 2034TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) { 2035 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles")); 2036 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack"))); 2037} 2038 2039// Tests that IsSubstring() generates the correct message when the input 2040// argument type is ::std::wstring. 2041TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) { 2042 EXPECT_STREQ("Value of: needle_expr\n" 2043 " Actual: L\"needle\"\n" 2044 "Expected: a substring of haystack_expr\n" 2045 "Which is: L\"haystack\"", 2046 IsSubstring( 2047 "needle_expr", "haystack_expr", 2048 ::std::wstring(L"needle"), L"haystack").failure_message()); 2049} 2050 2051#endif // GTEST_HAS_STD_WSTRING 2052 2053// Tests for ::testing::IsNotSubstring(). 2054 2055// Tests that IsNotSubstring() returns the correct result when the input 2056// argument type is const char*. 2057TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) { 2058 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack")); 2059 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles")); 2060} 2061 2062#if GTEST_HAS_STD_WSTRING 2063// Tests that IsNotSubstring() returns the correct result when the input 2064// argument type is const wchar_t*. 2065TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) { 2066 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack")); 2067 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles")); 2068} 2069 2070// Tests that IsNotSubstring() generates the correct message when the input 2071// argument type is const wchar_t*. 2072TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) { 2073 EXPECT_STREQ("Value of: needle_expr\n" 2074 " Actual: L\"needle\"\n" 2075 "Expected: not a substring of haystack_expr\n" 2076 "Which is: L\"two needles\"", 2077 IsNotSubstring( 2078 "needle_expr", "haystack_expr", 2079 L"needle", L"two needles").failure_message()); 2080} 2081#endif // GTEST_HAS_STD_WSTRING 2082 2083#if GTEST_HAS_STD_STRING 2084 2085// Tests that IsNotSubstring returns the correct result when the input 2086// argument type is ::std::string. 2087TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) { 2088 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob")); 2089 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world"))); 2090} 2091 2092// Tests that IsNotSubstring() generates the correct message when the input 2093// argument type is ::std::string. 2094TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) { 2095 EXPECT_STREQ("Value of: needle_expr\n" 2096 " Actual: \"needle\"\n" 2097 "Expected: not a substring of haystack_expr\n" 2098 "Which is: \"two needles\"", 2099 IsNotSubstring( 2100 "needle_expr", "haystack_expr", 2101 ::std::string("needle"), "two needles").failure_message()); 2102} 2103 2104#endif // GTEST_HAS_STD_STRING 2105 2106#if GTEST_HAS_STD_WSTRING 2107 2108// Tests that IsNotSubstring returns the correct result when the input 2109// argument type is ::std::wstring. 2110TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) { 2111 EXPECT_FALSE( 2112 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles")); 2113 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack"))); 2114} 2115 2116#endif // GTEST_HAS_STD_WSTRING 2117 2118// Tests floating-point assertions. 2119 2120template <typename RawType> 2121class FloatingPointTest : public Test { 2122 protected: 2123 typedef typename testing::internal::FloatingPoint<RawType> Floating; 2124 typedef typename Floating::Bits Bits; 2125 2126 virtual void SetUp() { 2127 const size_t max_ulps = Floating::kMaxUlps; 2128 2129 // The bits that represent 0.0. 2130 const Bits zero_bits = Floating(0).bits(); 2131 2132 // Makes some numbers close to 0.0. 2133 close_to_positive_zero_ = Floating::ReinterpretBits(zero_bits + max_ulps/2); 2134 close_to_negative_zero_ = -Floating::ReinterpretBits( 2135 zero_bits + max_ulps - max_ulps/2); 2136 further_from_negative_zero_ = -Floating::ReinterpretBits( 2137 zero_bits + max_ulps + 1 - max_ulps/2); 2138 2139 // The bits that represent 1.0. 2140 const Bits one_bits = Floating(1).bits(); 2141 2142 // Makes some numbers close to 1.0. 2143 close_to_one_ = Floating::ReinterpretBits(one_bits + max_ulps); 2144 further_from_one_ = Floating::ReinterpretBits(one_bits + max_ulps + 1); 2145 2146 // +infinity. 2147 infinity_ = Floating::Infinity(); 2148 2149 // The bits that represent +infinity. 2150 const Bits infinity_bits = Floating(infinity_).bits(); 2151 2152 // Makes some numbers close to infinity. 2153 close_to_infinity_ = Floating::ReinterpretBits(infinity_bits - max_ulps); 2154 further_from_infinity_ = Floating::ReinterpretBits( 2155 infinity_bits - max_ulps - 1); 2156 2157 // Makes some NAN's. 2158 nan1_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 1); 2159 nan2_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 200); 2160 } 2161 2162 void TestSize() { 2163 EXPECT_EQ(sizeof(RawType), sizeof(Bits)); 2164 } 2165 2166 // Pre-calculated numbers to be used by the tests. 2167 2168 static RawType close_to_positive_zero_; 2169 static RawType close_to_negative_zero_; 2170 static RawType further_from_negative_zero_; 2171 2172 static RawType close_to_one_; 2173 static RawType further_from_one_; 2174 2175 static RawType infinity_; 2176 static RawType close_to_infinity_; 2177 static RawType further_from_infinity_; 2178 2179 static RawType nan1_; 2180 static RawType nan2_; 2181}; 2182 2183template <typename RawType> 2184RawType FloatingPointTest<RawType>::close_to_positive_zero_; 2185 2186template <typename RawType> 2187RawType FloatingPointTest<RawType>::close_to_negative_zero_; 2188 2189template <typename RawType> 2190RawType FloatingPointTest<RawType>::further_from_negative_zero_; 2191 2192template <typename RawType> 2193RawType FloatingPointTest<RawType>::close_to_one_; 2194 2195template <typename RawType> 2196RawType FloatingPointTest<RawType>::further_from_one_; 2197 2198template <typename RawType> 2199RawType FloatingPointTest<RawType>::infinity_; 2200 2201template <typename RawType> 2202RawType FloatingPointTest<RawType>::close_to_infinity_; 2203 2204template <typename RawType> 2205RawType FloatingPointTest<RawType>::further_from_infinity_; 2206 2207template <typename RawType> 2208RawType FloatingPointTest<RawType>::nan1_; 2209 2210template <typename RawType> 2211RawType FloatingPointTest<RawType>::nan2_; 2212 2213// Instantiates FloatingPointTest for testing *_FLOAT_EQ. 2214typedef FloatingPointTest<float> FloatTest; 2215 2216// Tests that the size of Float::Bits matches the size of float. 2217TEST_F(FloatTest, Size) { 2218 TestSize(); 2219} 2220 2221// Tests comparing with +0 and -0. 2222TEST_F(FloatTest, Zeros) { 2223 EXPECT_FLOAT_EQ(0.0, -0.0); 2224 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), 2225 "1.0"); 2226 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), 2227 "1.5"); 2228} 2229 2230// Tests comparing numbers close to 0. 2231// 2232// This ensures that *_FLOAT_EQ handles the sign correctly and no 2233// overflow occurs when comparing numbers whose absolute value is very 2234// small. 2235TEST_F(FloatTest, AlmostZeros) { 2236 EXPECT_FLOAT_EQ(0.0, close_to_positive_zero_); 2237 EXPECT_FLOAT_EQ(-0.0, close_to_negative_zero_); 2238 EXPECT_FLOAT_EQ(close_to_positive_zero_, close_to_negative_zero_); 2239 2240 EXPECT_FATAL_FAILURE({ // NOLINT 2241 ASSERT_FLOAT_EQ(close_to_positive_zero_, further_from_negative_zero_); 2242 }, "further_from_negative_zero_"); 2243} 2244 2245// Tests comparing numbers close to each other. 2246TEST_F(FloatTest, SmallDiff) { 2247 EXPECT_FLOAT_EQ(1.0, close_to_one_); 2248 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, further_from_one_), 2249 "further_from_one_"); 2250} 2251 2252// Tests comparing numbers far apart. 2253TEST_F(FloatTest, LargeDiff) { 2254 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), 2255 "3.0"); 2256} 2257 2258// Tests comparing with infinity. 2259// 2260// This ensures that no overflow occurs when comparing numbers whose 2261// absolute value is very large. 2262TEST_F(FloatTest, Infinity) { 2263 EXPECT_FLOAT_EQ(infinity_, close_to_infinity_); 2264 EXPECT_FLOAT_EQ(-infinity_, -close_to_infinity_); 2265#if !GTEST_OS_SYMBIAN 2266 // Nokia's STLport crashes if we try to output infinity or NaN. 2267 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(infinity_, -infinity_), 2268 "-infinity_"); 2269 2270 // This is interesting as the representations of infinity_ and nan1_ 2271 // are only 1 DLP apart. 2272 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(infinity_, nan1_), 2273 "nan1_"); 2274#endif // !GTEST_OS_SYMBIAN 2275} 2276 2277// Tests that comparing with NAN always returns false. 2278TEST_F(FloatTest, NaN) { 2279#if !GTEST_OS_SYMBIAN 2280// Nokia's STLport crashes if we try to output infinity or NaN. 2281 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(nan1_, nan1_), 2282 "nan1_"); 2283 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(nan1_, nan2_), 2284 "nan2_"); 2285 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, nan1_), 2286 "nan1_"); 2287 2288 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(nan1_, infinity_), 2289 "infinity_"); 2290#endif // !GTEST_OS_SYMBIAN 2291} 2292 2293// Tests that *_FLOAT_EQ are reflexive. 2294TEST_F(FloatTest, Reflexive) { 2295 EXPECT_FLOAT_EQ(0.0, 0.0); 2296 EXPECT_FLOAT_EQ(1.0, 1.0); 2297 ASSERT_FLOAT_EQ(infinity_, infinity_); 2298} 2299 2300// Tests that *_FLOAT_EQ are commutative. 2301TEST_F(FloatTest, Commutative) { 2302 // We already tested EXPECT_FLOAT_EQ(1.0, close_to_one_). 2303 EXPECT_FLOAT_EQ(close_to_one_, 1.0); 2304 2305 // We already tested EXPECT_FLOAT_EQ(1.0, further_from_one_). 2306 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(further_from_one_, 1.0), 2307 "1.0"); 2308} 2309 2310// DISABLED see bug 2398288 2311// Tests EXPECT_NEAR. 2312TEST_F(FloatTest, DISABLED_EXPECT_NEAR) { 2313 EXPECT_NEAR(-1.0f, -1.1f, 0.2f); 2314 EXPECT_NEAR(2.0f, 3.0f, 1.0f); 2315 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.2f, 0.1f), // NOLINT 2316 "The difference between 1.0f and 1.2f is 0.2, " 2317 "which exceeds 0.1f"); 2318 // To work around a bug in gcc 2.95.0, there is intentionally no 2319 // space after the first comma in the previous line. 2320} 2321 2322// DISABLED see bug 2398288 2323// Tests ASSERT_NEAR. 2324TEST_F(FloatTest, DISABLED_ASSERT_NEAR) { 2325 ASSERT_NEAR(-1.0f, -1.1f, 0.2f); 2326 ASSERT_NEAR(2.0f, 3.0f, 1.0f); 2327 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.2f, 0.1f), // NOLINT 2328 "The difference between 1.0f and 1.2f is 0.2, " 2329 "which exceeds 0.1f"); 2330 // To work around a bug in gcc 2.95.0, there is intentionally no 2331 // space after the first comma in the previous line. 2332} 2333 2334// Tests the cases where FloatLE() should succeed. 2335TEST_F(FloatTest, FloatLESucceeds) { 2336 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2, 2337 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2, 2338 2339 // or when val1 is greater than, but almost equals to, val2. 2340 EXPECT_PRED_FORMAT2(FloatLE, close_to_positive_zero_, 0.0f); 2341} 2342 2343// Tests the cases where FloatLE() should fail. 2344TEST_F(FloatTest, FloatLEFails) { 2345 // When val1 is greater than val2 by a large margin, 2346 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f), 2347 "(2.0f) <= (1.0f)"); 2348 2349 // or by a small yet non-negligible margin, 2350 EXPECT_NONFATAL_FAILURE({ // NOLINT 2351 EXPECT_PRED_FORMAT2(FloatLE, further_from_one_, 1.0f); 2352 }, "(further_from_one_) <= (1.0f)"); 2353 2354#if !GTEST_OS_SYMBIAN 2355 // Nokia's STLport crashes if we try to output infinity or NaN. 2356 // or when either val1 or val2 is NaN. 2357 EXPECT_NONFATAL_FAILURE({ // NOLINT 2358 EXPECT_PRED_FORMAT2(FloatLE, nan1_, infinity_); 2359 }, "(nan1_) <= (infinity_)"); 2360 EXPECT_NONFATAL_FAILURE({ // NOLINT 2361 EXPECT_PRED_FORMAT2(FloatLE, -infinity_, nan1_); 2362 }, "(-infinity_) <= (nan1_)"); 2363 2364 EXPECT_FATAL_FAILURE({ // NOLINT 2365 ASSERT_PRED_FORMAT2(FloatLE, nan1_, nan1_); 2366 }, "(nan1_) <= (nan1_)"); 2367#endif // !GTEST_OS_SYMBIAN 2368} 2369 2370// Instantiates FloatingPointTest for testing *_DOUBLE_EQ. 2371typedef FloatingPointTest<double> DoubleTest; 2372 2373// Tests that the size of Double::Bits matches the size of double. 2374TEST_F(DoubleTest, Size) { 2375 TestSize(); 2376} 2377 2378// Tests comparing with +0 and -0. 2379TEST_F(DoubleTest, Zeros) { 2380 EXPECT_DOUBLE_EQ(0.0, -0.0); 2381 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), 2382 "1.0"); 2383 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), 2384 "1.0"); 2385} 2386 2387// Tests comparing numbers close to 0. 2388// 2389// This ensures that *_DOUBLE_EQ handles the sign correctly and no 2390// overflow occurs when comparing numbers whose absolute value is very 2391// small. 2392TEST_F(DoubleTest, AlmostZeros) { 2393 EXPECT_DOUBLE_EQ(0.0, close_to_positive_zero_); 2394 EXPECT_DOUBLE_EQ(-0.0, close_to_negative_zero_); 2395 EXPECT_DOUBLE_EQ(close_to_positive_zero_, close_to_negative_zero_); 2396 2397 EXPECT_FATAL_FAILURE({ // NOLINT 2398 ASSERT_DOUBLE_EQ(close_to_positive_zero_, further_from_negative_zero_); 2399 }, "further_from_negative_zero_"); 2400} 2401 2402// Tests comparing numbers close to each other. 2403TEST_F(DoubleTest, SmallDiff) { 2404 EXPECT_DOUBLE_EQ(1.0, close_to_one_); 2405 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, further_from_one_), 2406 "further_from_one_"); 2407} 2408 2409// Tests comparing numbers far apart. 2410TEST_F(DoubleTest, LargeDiff) { 2411 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), 2412 "3.0"); 2413} 2414 2415// Tests comparing with infinity. 2416// 2417// This ensures that no overflow occurs when comparing numbers whose 2418// absolute value is very large. 2419TEST_F(DoubleTest, Infinity) { 2420 EXPECT_DOUBLE_EQ(infinity_, close_to_infinity_); 2421 EXPECT_DOUBLE_EQ(-infinity_, -close_to_infinity_); 2422#if !GTEST_OS_SYMBIAN 2423 // Nokia's STLport crashes if we try to output infinity or NaN. 2424 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(infinity_, -infinity_), 2425 "-infinity_"); 2426 2427 // This is interesting as the representations of infinity_ and nan1_ 2428 // are only 1 DLP apart. 2429 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(infinity_, nan1_), 2430 "nan1_"); 2431#endif // !GTEST_OS_SYMBIAN 2432} 2433 2434// Tests that comparing with NAN always returns false. 2435TEST_F(DoubleTest, NaN) { 2436#if !GTEST_OS_SYMBIAN 2437 // Nokia's STLport crashes if we try to output infinity or NaN. 2438 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(nan1_, nan1_), 2439 "nan1_"); 2440 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(nan1_, nan2_), "nan2_"); 2441 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, nan1_), "nan1_"); 2442 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(nan1_, infinity_), "infinity_"); 2443#endif // !GTEST_OS_SYMBIAN 2444} 2445 2446// Tests that *_DOUBLE_EQ are reflexive. 2447TEST_F(DoubleTest, Reflexive) { 2448 EXPECT_DOUBLE_EQ(0.0, 0.0); 2449 EXPECT_DOUBLE_EQ(1.0, 1.0); 2450#if !GTEST_OS_SYMBIAN 2451 // Nokia's STLport crashes if we try to output infinity or NaN. 2452 ASSERT_DOUBLE_EQ(infinity_, infinity_); 2453#endif // !GTEST_OS_SYMBIAN 2454} 2455 2456// Tests that *_DOUBLE_EQ are commutative. 2457TEST_F(DoubleTest, Commutative) { 2458 // We already tested EXPECT_DOUBLE_EQ(1.0, close_to_one_). 2459 EXPECT_DOUBLE_EQ(close_to_one_, 1.0); 2460 2461 // We already tested EXPECT_DOUBLE_EQ(1.0, further_from_one_). 2462 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(further_from_one_, 1.0), "1.0"); 2463} 2464 2465// DISABLED see bug 2398288 2466// Tests EXPECT_NEAR. 2467TEST_F(DoubleTest, DISABLED_EXPECT_NEAR) { 2468 EXPECT_NEAR(-1.0, -1.1, 0.2); 2469 EXPECT_NEAR(2.0, 3.0, 1.0); 2470 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.2, 0.1), // NOLINT 2471 "The difference between 1.0 and 1.2 is 0.2, " 2472 "which exceeds 0.1"); 2473 // To work around a bug in gcc 2.95.0, there is intentionally no 2474 // space after the first comma in the previous statement. 2475} 2476 2477// DISABLED see bug 2398288 2478// Tests ASSERT_NEAR. 2479TEST_F(DoubleTest, DISABLED_ASSERT_NEAR) { 2480 ASSERT_NEAR(-1.0, -1.1, 0.2); 2481 ASSERT_NEAR(2.0, 3.0, 1.0); 2482 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.2, 0.1), // NOLINT 2483 "The difference between 1.0 and 1.2 is 0.2, " 2484 "which exceeds 0.1"); 2485 // To work around a bug in gcc 2.95.0, there is intentionally no 2486 // space after the first comma in the previous statement. 2487} 2488 2489// Tests the cases where DoubleLE() should succeed. 2490TEST_F(DoubleTest, DoubleLESucceeds) { 2491 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2, 2492 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2, 2493 2494 // or when val1 is greater than, but almost equals to, val2. 2495 EXPECT_PRED_FORMAT2(DoubleLE, close_to_positive_zero_, 0.0); 2496} 2497 2498// Tests the cases where DoubleLE() should fail. 2499TEST_F(DoubleTest, DoubleLEFails) { 2500 // When val1 is greater than val2 by a large margin, 2501 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0), 2502 "(2.0) <= (1.0)"); 2503 2504 // or by a small yet non-negligible margin, 2505 EXPECT_NONFATAL_FAILURE({ // NOLINT 2506 EXPECT_PRED_FORMAT2(DoubleLE, further_from_one_, 1.0); 2507 }, "(further_from_one_) <= (1.0)"); 2508 2509#if !GTEST_OS_SYMBIAN 2510 // Nokia's STLport crashes if we try to output infinity or NaN. 2511 // or when either val1 or val2 is NaN. 2512 EXPECT_NONFATAL_FAILURE({ // NOLINT 2513 EXPECT_PRED_FORMAT2(DoubleLE, nan1_, infinity_); 2514 }, "(nan1_) <= (infinity_)"); 2515 EXPECT_NONFATAL_FAILURE({ // NOLINT 2516 EXPECT_PRED_FORMAT2(DoubleLE, -infinity_, nan1_); 2517 }, " (-infinity_) <= (nan1_)"); 2518 EXPECT_FATAL_FAILURE({ // NOLINT 2519 ASSERT_PRED_FORMAT2(DoubleLE, nan1_, nan1_); 2520 }, "(nan1_) <= (nan1_)"); 2521#endif // !GTEST_OS_SYMBIAN 2522} 2523 2524 2525// Verifies that a test or test case whose name starts with DISABLED_ is 2526// not run. 2527 2528// A test whose name starts with DISABLED_. 2529// Should not run. 2530TEST(DisabledTest, DISABLED_TestShouldNotRun) { 2531 FAIL() << "Unexpected failure: Disabled test should not be run."; 2532} 2533 2534// A test whose name does not start with DISABLED_. 2535// Should run. 2536TEST(DisabledTest, NotDISABLED_TestShouldRun) { 2537 EXPECT_EQ(1, 1); 2538} 2539 2540// A test case whose name starts with DISABLED_. 2541// Should not run. 2542TEST(DISABLED_TestCase, TestShouldNotRun) { 2543 FAIL() << "Unexpected failure: Test in disabled test case should not be run."; 2544} 2545 2546// A test case and test whose names start with DISABLED_. 2547// Should not run. 2548TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) { 2549 FAIL() << "Unexpected failure: Test in disabled test case should not be run."; 2550} 2551 2552// Check that when all tests in a test case are disabled, SetupTestCase() and 2553// TearDownTestCase() are not called. 2554class DisabledTestsTest : public Test { 2555 protected: 2556 static void SetUpTestCase() { 2557 FAIL() << "Unexpected failure: All tests disabled in test case. " 2558 "SetupTestCase() should not be called."; 2559 } 2560 2561 static void TearDownTestCase() { 2562 FAIL() << "Unexpected failure: All tests disabled in test case. " 2563 "TearDownTestCase() should not be called."; 2564 } 2565}; 2566 2567TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) { 2568 FAIL() << "Unexpected failure: Disabled test should not be run."; 2569} 2570 2571TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) { 2572 FAIL() << "Unexpected failure: Disabled test should not be run."; 2573} 2574 2575// Tests that disabled typed tests aren't run. 2576 2577#if GTEST_HAS_TYPED_TEST 2578 2579template <typename T> 2580class TypedTest : public Test { 2581}; 2582 2583typedef testing::Types<int, double> NumericTypes; 2584TYPED_TEST_CASE(TypedTest, NumericTypes); 2585 2586TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { 2587 FAIL() << "Unexpected failure: Disabled typed test should not run."; 2588} 2589 2590template <typename T> 2591class DISABLED_TypedTest : public Test { 2592}; 2593 2594TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes); 2595 2596TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { 2597 FAIL() << "Unexpected failure: Disabled typed test should not run."; 2598} 2599 2600#endif // GTEST_HAS_TYPED_TEST 2601 2602// Tests that disabled type-parameterized tests aren't run. 2603 2604#if GTEST_HAS_TYPED_TEST_P 2605 2606template <typename T> 2607class TypedTestP : public Test { 2608}; 2609 2610TYPED_TEST_CASE_P(TypedTestP); 2611 2612TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) { 2613 FAIL() << "Unexpected failure: " 2614 << "Disabled type-parameterized test should not run."; 2615} 2616 2617REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun); 2618 2619INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes); 2620 2621template <typename T> 2622class DISABLED_TypedTestP : public Test { 2623}; 2624 2625TYPED_TEST_CASE_P(DISABLED_TypedTestP); 2626 2627TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) { 2628 FAIL() << "Unexpected failure: " 2629 << "Disabled type-parameterized test should not run."; 2630} 2631 2632REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun); 2633 2634INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes); 2635 2636#endif // GTEST_HAS_TYPED_TEST_P 2637 2638// Tests that assertion macros evaluate their arguments exactly once. 2639 2640class SingleEvaluationTest : public Test { 2641 protected: 2642 SingleEvaluationTest() { 2643 p1_ = s1_; 2644 p2_ = s2_; 2645 a_ = 0; 2646 b_ = 0; 2647 } 2648 2649 // This helper function is needed by the FailedASSERT_STREQ test 2650 // below. 2651 static void CompareAndIncrementCharPtrs() { 2652 ASSERT_STREQ(p1_++, p2_++); 2653 } 2654 2655 // This helper function is needed by the FailedASSERT_NE test below. 2656 static void CompareAndIncrementInts() { 2657 ASSERT_NE(a_++, b_++); 2658 } 2659 2660 static const char* const s1_; 2661 static const char* const s2_; 2662 static const char* p1_; 2663 static const char* p2_; 2664 2665 static int a_; 2666 static int b_; 2667}; 2668 2669const char* const SingleEvaluationTest::s1_ = "01234"; 2670const char* const SingleEvaluationTest::s2_ = "abcde"; 2671const char* SingleEvaluationTest::p1_; 2672const char* SingleEvaluationTest::p2_; 2673int SingleEvaluationTest::a_; 2674int SingleEvaluationTest::b_; 2675 2676// Tests that when ASSERT_STREQ fails, it evaluates its arguments 2677// exactly once. 2678TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) { 2679 EXPECT_FATAL_FAILURE(CompareAndIncrementCharPtrs(), 2680 "p2_++"); 2681 EXPECT_EQ(s1_ + 1, p1_); 2682 EXPECT_EQ(s2_ + 1, p2_); 2683} 2684 2685// Tests that string assertion arguments are evaluated exactly once. 2686TEST_F(SingleEvaluationTest, ASSERT_STR) { 2687 // successful EXPECT_STRNE 2688 EXPECT_STRNE(p1_++, p2_++); 2689 EXPECT_EQ(s1_ + 1, p1_); 2690 EXPECT_EQ(s2_ + 1, p2_); 2691 2692 // failed EXPECT_STRCASEEQ 2693 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), 2694 "ignoring case"); 2695 EXPECT_EQ(s1_ + 2, p1_); 2696 EXPECT_EQ(s2_ + 2, p2_); 2697} 2698 2699// Tests that when ASSERT_NE fails, it evaluates its arguments exactly 2700// once. 2701TEST_F(SingleEvaluationTest, FailedASSERT_NE) { 2702 EXPECT_FATAL_FAILURE(CompareAndIncrementInts(), "(a_++) != (b_++)"); 2703 EXPECT_EQ(1, a_); 2704 EXPECT_EQ(1, b_); 2705} 2706 2707// Tests that assertion arguments are evaluated exactly once. 2708TEST_F(SingleEvaluationTest, OtherCases) { 2709 // successful EXPECT_TRUE 2710 EXPECT_TRUE(0 == a_++); // NOLINT 2711 EXPECT_EQ(1, a_); 2712 2713 // failed EXPECT_TRUE 2714 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++"); 2715 EXPECT_EQ(2, a_); 2716 2717 // successful EXPECT_GT 2718 EXPECT_GT(a_++, b_++); 2719 EXPECT_EQ(3, a_); 2720 EXPECT_EQ(1, b_); 2721 2722 // failed EXPECT_LT 2723 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)"); 2724 EXPECT_EQ(4, a_); 2725 EXPECT_EQ(2, b_); 2726 2727 // successful ASSERT_TRUE 2728 ASSERT_TRUE(0 < a_++); // NOLINT 2729 EXPECT_EQ(5, a_); 2730 2731 // successful ASSERT_GT 2732 ASSERT_GT(a_++, b_++); 2733 EXPECT_EQ(6, a_); 2734 EXPECT_EQ(3, b_); 2735} 2736 2737#if GTEST_HAS_EXCEPTIONS 2738 2739void ThrowAnInteger() { 2740 throw 1; 2741} 2742 2743// Tests that assertion arguments are evaluated exactly once. 2744TEST_F(SingleEvaluationTest, ExceptionTests) { 2745 // successful EXPECT_THROW 2746 EXPECT_THROW({ // NOLINT 2747 a_++; 2748 ThrowAnInteger(); 2749 }, int); 2750 EXPECT_EQ(1, a_); 2751 2752 // failed EXPECT_THROW, throws different 2753 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT 2754 a_++; 2755 ThrowAnInteger(); 2756 }, bool), "throws a different type"); 2757 EXPECT_EQ(2, a_); 2758 2759 // failed EXPECT_THROW, throws nothing 2760 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing"); 2761 EXPECT_EQ(3, a_); 2762 2763 // successful EXPECT_NO_THROW 2764 EXPECT_NO_THROW(a_++); 2765 EXPECT_EQ(4, a_); 2766 2767 // failed EXPECT_NO_THROW 2768 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT 2769 a_++; 2770 ThrowAnInteger(); 2771 }), "it throws"); 2772 EXPECT_EQ(5, a_); 2773 2774 // successful EXPECT_ANY_THROW 2775 EXPECT_ANY_THROW({ // NOLINT 2776 a_++; 2777 ThrowAnInteger(); 2778 }); 2779 EXPECT_EQ(6, a_); 2780 2781 // failed EXPECT_ANY_THROW 2782 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't"); 2783 EXPECT_EQ(7, a_); 2784} 2785 2786#endif // GTEST_HAS_EXCEPTIONS 2787 2788// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE. 2789class NoFatalFailureTest : public Test { 2790 protected: 2791 void Succeeds() {} 2792 void FailsNonFatal() { 2793 ADD_FAILURE() << "some non-fatal failure"; 2794 } 2795 void Fails() { 2796 FAIL() << "some fatal failure"; 2797 } 2798 2799 void DoAssertNoFatalFailureOnFails() { 2800 ASSERT_NO_FATAL_FAILURE(Fails()); 2801 ADD_FAILURE() << "shold not reach here."; 2802 } 2803 2804 void DoExpectNoFatalFailureOnFails() { 2805 EXPECT_NO_FATAL_FAILURE(Fails()); 2806 ADD_FAILURE() << "other failure"; 2807 } 2808}; 2809 2810TEST_F(NoFatalFailureTest, NoFailure) { 2811 EXPECT_NO_FATAL_FAILURE(Succeeds()); 2812 ASSERT_NO_FATAL_FAILURE(Succeeds()); 2813} 2814 2815TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) { 2816 EXPECT_NONFATAL_FAILURE( 2817 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()), 2818 "some non-fatal failure"); 2819 EXPECT_NONFATAL_FAILURE( 2820 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()), 2821 "some non-fatal failure"); 2822} 2823 2824TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) { 2825 TestPartResultArray gtest_failures; 2826 { 2827 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); 2828 DoAssertNoFatalFailureOnFails(); 2829 } 2830 ASSERT_EQ(2, gtest_failures.size()); 2831 EXPECT_EQ(testing::TPRT_FATAL_FAILURE, 2832 gtest_failures.GetTestPartResult(0).type()); 2833 EXPECT_EQ(testing::TPRT_FATAL_FAILURE, 2834 gtest_failures.GetTestPartResult(1).type()); 2835 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", 2836 gtest_failures.GetTestPartResult(0).message()); 2837 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", 2838 gtest_failures.GetTestPartResult(1).message()); 2839} 2840 2841TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) { 2842 TestPartResultArray gtest_failures; 2843 { 2844 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); 2845 DoExpectNoFatalFailureOnFails(); 2846 } 2847 ASSERT_EQ(3, gtest_failures.size()); 2848 EXPECT_EQ(testing::TPRT_FATAL_FAILURE, 2849 gtest_failures.GetTestPartResult(0).type()); 2850 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE, 2851 gtest_failures.GetTestPartResult(1).type()); 2852 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE, 2853 gtest_failures.GetTestPartResult(2).type()); 2854 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", 2855 gtest_failures.GetTestPartResult(0).message()); 2856 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", 2857 gtest_failures.GetTestPartResult(1).message()); 2858 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure", 2859 gtest_failures.GetTestPartResult(2).message()); 2860} 2861 2862TEST_F(NoFatalFailureTest, MessageIsStreamable) { 2863 TestPartResultArray gtest_failures; 2864 { 2865 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); 2866 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message"; 2867 } 2868 ASSERT_EQ(2, gtest_failures.size()); 2869 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE, 2870 gtest_failures.GetTestPartResult(0).type()); 2871 EXPECT_EQ(testing::TPRT_NONFATAL_FAILURE, 2872 gtest_failures.GetTestPartResult(1).type()); 2873 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo", 2874 gtest_failures.GetTestPartResult(0).message()); 2875 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message", 2876 gtest_failures.GetTestPartResult(1).message()); 2877} 2878 2879// Tests non-string assertions. 2880 2881// Tests EqFailure(), used for implementing *EQ* assertions. 2882TEST(AssertionTest, EqFailure) { 2883 const String foo_val("5"), bar_val("6"); 2884 const String msg1( 2885 EqFailure("foo", "bar", foo_val, bar_val, false) 2886 .failure_message()); 2887 EXPECT_STREQ( 2888 "Value of: bar\n" 2889 " Actual: 6\n" 2890 "Expected: foo\n" 2891 "Which is: 5", 2892 msg1.c_str()); 2893 2894 const String msg2( 2895 EqFailure("foo", "6", foo_val, bar_val, false) 2896 .failure_message()); 2897 EXPECT_STREQ( 2898 "Value of: 6\n" 2899 "Expected: foo\n" 2900 "Which is: 5", 2901 msg2.c_str()); 2902 2903 const String msg3( 2904 EqFailure("5", "bar", foo_val, bar_val, false) 2905 .failure_message()); 2906 EXPECT_STREQ( 2907 "Value of: bar\n" 2908 " Actual: 6\n" 2909 "Expected: 5", 2910 msg3.c_str()); 2911 2912 const String msg4( 2913 EqFailure("5", "6", foo_val, bar_val, false).failure_message()); 2914 EXPECT_STREQ( 2915 "Value of: 6\n" 2916 "Expected: 5", 2917 msg4.c_str()); 2918 2919 const String msg5( 2920 EqFailure("foo", "bar", 2921 String("\"x\""), String("\"y\""), 2922 true).failure_message()); 2923 EXPECT_STREQ( 2924 "Value of: bar\n" 2925 " Actual: \"y\"\n" 2926 "Expected: foo (ignoring case)\n" 2927 "Which is: \"x\"", 2928 msg5.c_str()); 2929} 2930 2931// Tests AppendUserMessage(), used for implementing the *EQ* macros. 2932TEST(AssertionTest, AppendUserMessage) { 2933 const String foo("foo"); 2934 2935 Message msg; 2936 EXPECT_STREQ("foo", 2937 AppendUserMessage(foo, msg).c_str()); 2938 2939 msg << "bar"; 2940 EXPECT_STREQ("foo\nbar", 2941 AppendUserMessage(foo, msg).c_str()); 2942} 2943 2944// Tests ASSERT_TRUE. 2945TEST(AssertionTest, ASSERT_TRUE) { 2946 ASSERT_TRUE(2 > 1); // NOLINT 2947 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), 2948 "2 < 1"); 2949} 2950 2951// Tests ASSERT_FALSE. 2952TEST(AssertionTest, ASSERT_FALSE) { 2953 ASSERT_FALSE(2 < 1); // NOLINT 2954 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1), 2955 "Value of: 2 > 1\n" 2956 " Actual: true\n" 2957 "Expected: false"); 2958} 2959 2960// Tests using ASSERT_EQ on double values. The purpose is to make 2961// sure that the specialization we did for integer and anonymous enums 2962// isn't used for double arguments. 2963TEST(ExpectTest, ASSERT_EQ_Double) { 2964 // A success. 2965 ASSERT_EQ(5.6, 5.6); 2966 2967 // A failure. 2968 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), 2969 "5.1"); 2970} 2971 2972// Tests ASSERT_EQ. 2973TEST(AssertionTest, ASSERT_EQ) { 2974 ASSERT_EQ(5, 2 + 3); 2975 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), 2976 "Value of: 2*3\n" 2977 " Actual: 6\n" 2978 "Expected: 5"); 2979} 2980 2981// Tests ASSERT_EQ(NULL, pointer). 2982#if !GTEST_OS_SYMBIAN 2983// The NULL-detection template magic fails to compile with 2984// the Nokia compiler and crashes the ARM compiler, hence 2985// not testing on Symbian. 2986TEST(AssertionTest, ASSERT_EQ_NULL) { 2987 // A success. 2988 const char* p = NULL; 2989 ASSERT_EQ(NULL, p); 2990 2991 // A failure. 2992 static int n = 0; 2993 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n), 2994 "Value of: &n\n"); 2995} 2996#endif // !GTEST_OS_SYMBIAN 2997 2998// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be 2999// treated as a null pointer by the compiler, we need to make sure 3000// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as 3001// ASSERT_EQ(static_cast<void*>(NULL), non_pointer). 3002TEST(ExpectTest, ASSERT_EQ_0) { 3003 int n = 0; 3004 3005 // A success. 3006 ASSERT_EQ(0, n); 3007 3008 // A failure. 3009 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), 3010 "Expected: 0"); 3011} 3012 3013// Tests ASSERT_NE. 3014TEST(AssertionTest, ASSERT_NE) { 3015 ASSERT_NE(6, 7); 3016 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'), 3017 "Expected: ('a') != ('a'), " 3018 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); 3019} 3020 3021// Tests ASSERT_LE. 3022TEST(AssertionTest, ASSERT_LE) { 3023 ASSERT_LE(2, 3); 3024 ASSERT_LE(2, 2); 3025 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), 3026 "Expected: (2) <= (0), actual: 2 vs 0"); 3027} 3028 3029// Tests ASSERT_LT. 3030TEST(AssertionTest, ASSERT_LT) { 3031 ASSERT_LT(2, 3); 3032 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), 3033 "Expected: (2) < (2), actual: 2 vs 2"); 3034} 3035 3036// Tests ASSERT_GE. 3037TEST(AssertionTest, ASSERT_GE) { 3038 ASSERT_GE(2, 1); 3039 ASSERT_GE(2, 2); 3040 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), 3041 "Expected: (2) >= (3), actual: 2 vs 3"); 3042} 3043 3044// Tests ASSERT_GT. 3045TEST(AssertionTest, ASSERT_GT) { 3046 ASSERT_GT(2, 1); 3047 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), 3048 "Expected: (2) > (2), actual: 2 vs 2"); 3049} 3050 3051#if GTEST_HAS_EXCEPTIONS 3052 3053void ThrowNothing() {} 3054 3055 3056// Tests ASSERT_THROW. 3057TEST(AssertionTest, ASSERT_THROW) { 3058 ASSERT_THROW(ThrowAnInteger(), int); 3059 EXPECT_FATAL_FAILURE( 3060 ASSERT_THROW(ThrowAnInteger(), bool), 3061 "Expected: ThrowAnInteger() throws an exception of type bool.\n" 3062 " Actual: it throws a different type."); 3063 EXPECT_FATAL_FAILURE( 3064 ASSERT_THROW(ThrowNothing(), bool), 3065 "Expected: ThrowNothing() throws an exception of type bool.\n" 3066 " Actual: it throws nothing."); 3067} 3068 3069// Tests ASSERT_NO_THROW. 3070TEST(AssertionTest, ASSERT_NO_THROW) { 3071 ASSERT_NO_THROW(ThrowNothing()); 3072 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()), 3073 "Expected: ThrowAnInteger() doesn't throw an exception." 3074 "\n Actual: it throws."); 3075} 3076 3077// Tests ASSERT_ANY_THROW. 3078TEST(AssertionTest, ASSERT_ANY_THROW) { 3079 ASSERT_ANY_THROW(ThrowAnInteger()); 3080 EXPECT_FATAL_FAILURE( 3081 ASSERT_ANY_THROW(ThrowNothing()), 3082 "Expected: ThrowNothing() throws an exception.\n" 3083 " Actual: it doesn't."); 3084} 3085 3086#endif // GTEST_HAS_EXCEPTIONS 3087 3088// Makes sure we deal with the precedence of <<. This test should 3089// compile. 3090TEST(AssertionTest, AssertPrecedence) { 3091 ASSERT_EQ(1 < 2, true); 3092 ASSERT_EQ(true && false, false); 3093} 3094 3095// A subroutine used by the following test. 3096void TestEq1(int x) { 3097 ASSERT_EQ(1, x); 3098} 3099 3100// Tests calling a test subroutine that's not part of a fixture. 3101TEST(AssertionTest, NonFixtureSubroutine) { 3102 EXPECT_FATAL_FAILURE(TestEq1(2), 3103 "Value of: x"); 3104} 3105 3106// An uncopyable class. 3107class Uncopyable { 3108 public: 3109 explicit Uncopyable(int value) : value_(value) {} 3110 3111 int value() const { return value_; } 3112 bool operator==(const Uncopyable& rhs) const { 3113 return value() == rhs.value(); 3114 } 3115 private: 3116 // This constructor deliberately has no implementation, as we don't 3117 // want this class to be copyable. 3118 Uncopyable(const Uncopyable&); // NOLINT 3119 3120 int value_; 3121}; 3122 3123::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) { 3124 return os << value.value(); 3125} 3126 3127 3128bool IsPositiveUncopyable(const Uncopyable& x) { 3129 return x.value() > 0; 3130} 3131 3132// A subroutine used by the following test. 3133void TestAssertNonPositive() { 3134 Uncopyable y(-1); 3135 ASSERT_PRED1(IsPositiveUncopyable, y); 3136} 3137// A subroutine used by the following test. 3138void TestAssertEqualsUncopyable() { 3139 Uncopyable x(5); 3140 Uncopyable y(-1); 3141 ASSERT_EQ(x, y); 3142} 3143 3144// Tests that uncopyable objects can be used in assertions. 3145TEST(AssertionTest, AssertWorksWithUncopyableObject) { 3146 Uncopyable x(5); 3147 ASSERT_PRED1(IsPositiveUncopyable, x); 3148 ASSERT_EQ(x, x); 3149 EXPECT_FATAL_FAILURE(TestAssertNonPositive(), 3150 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); 3151 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(), 3152 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5"); 3153} 3154 3155// Tests that uncopyable objects can be used in expects. 3156TEST(AssertionTest, ExpectWorksWithUncopyableObject) { 3157 Uncopyable x(5); 3158 EXPECT_PRED1(IsPositiveUncopyable, x); 3159 Uncopyable y(-1); 3160 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y), 3161 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); 3162 EXPECT_EQ(x, x); 3163 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), 3164 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5"); 3165} 3166 3167 3168// The version of gcc used in XCode 2.2 has a bug and doesn't allow 3169// anonymous enums in assertions. Therefore the following test is 3170// done only on Linux and Windows. 3171#if GTEST_OS_LINUX || GTEST_OS_WINDOWS 3172 3173// Tests using assertions with anonymous enums. 3174enum { 3175 CASE_A = -1, 3176#if GTEST_OS_LINUX 3177 // We want to test the case where the size of the anonymous enum is 3178 // larger than sizeof(int), to make sure our implementation of the 3179 // assertions doesn't truncate the enums. However, MSVC 3180 // (incorrectly) doesn't allow an enum value to exceed the range of 3181 // an int, so this has to be conditionally compiled. 3182 // 3183 // On Linux, CASE_B and CASE_A have the same value when truncated to 3184 // int size. We want to test whether this will confuse the 3185 // assertions. 3186 CASE_B = testing::internal::kMaxBiggestInt, 3187#else 3188 CASE_B = INT_MAX, 3189#endif // GTEST_OS_LINUX 3190}; 3191 3192TEST(AssertionTest, AnonymousEnum) { 3193#if GTEST_OS_LINUX 3194 EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B)); 3195#endif // GTEST_OS_LINUX 3196 3197 EXPECT_EQ(CASE_A, CASE_A); 3198 EXPECT_NE(CASE_A, CASE_B); 3199 EXPECT_LT(CASE_A, CASE_B); 3200 EXPECT_LE(CASE_A, CASE_B); 3201 EXPECT_GT(CASE_B, CASE_A); 3202 EXPECT_GE(CASE_A, CASE_A); 3203 EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B), 3204 "(CASE_A) >= (CASE_B)"); 3205 3206 ASSERT_EQ(CASE_A, CASE_A); 3207 ASSERT_NE(CASE_A, CASE_B); 3208 ASSERT_LT(CASE_A, CASE_B); 3209 ASSERT_LE(CASE_A, CASE_B); 3210 ASSERT_GT(CASE_B, CASE_A); 3211 ASSERT_GE(CASE_A, CASE_A); 3212 EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B), 3213 "Value of: CASE_B"); 3214} 3215 3216#endif // GTEST_OS_LINUX || GTEST_OS_WINDOWS 3217 3218#if GTEST_OS_WINDOWS 3219 3220static HRESULT UnexpectedHRESULTFailure() { 3221 return E_UNEXPECTED; 3222} 3223 3224static HRESULT OkHRESULTSuccess() { 3225 return S_OK; 3226} 3227 3228static HRESULT FalseHRESULTSuccess() { 3229 return S_FALSE; 3230} 3231 3232// HRESULT assertion tests test both zero and non-zero 3233// success codes as well as failure message for each. 3234// 3235// Windows CE doesn't support message texts. 3236TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) { 3237 EXPECT_HRESULT_SUCCEEDED(S_OK); 3238 EXPECT_HRESULT_SUCCEEDED(S_FALSE); 3239 3240 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), 3241 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" 3242 " Actual: 0x8000FFFF"); 3243} 3244 3245TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) { 3246 ASSERT_HRESULT_SUCCEEDED(S_OK); 3247 ASSERT_HRESULT_SUCCEEDED(S_FALSE); 3248 3249 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), 3250 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" 3251 " Actual: 0x8000FFFF"); 3252} 3253 3254TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) { 3255 EXPECT_HRESULT_FAILED(E_UNEXPECTED); 3256 3257 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()), 3258 "Expected: (OkHRESULTSuccess()) fails.\n" 3259 " Actual: 0x00000000"); 3260 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()), 3261 "Expected: (FalseHRESULTSuccess()) fails.\n" 3262 " Actual: 0x00000001"); 3263} 3264 3265TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) { 3266 ASSERT_HRESULT_FAILED(E_UNEXPECTED); 3267 3268 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()), 3269 "Expected: (OkHRESULTSuccess()) fails.\n" 3270 " Actual: 0x00000000"); 3271 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()), 3272 "Expected: (FalseHRESULTSuccess()) fails.\n" 3273 " Actual: 0x00000001"); 3274} 3275 3276// Tests that streaming to the HRESULT macros works. 3277TEST(HRESULTAssertionTest, Streaming) { 3278 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; 3279 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; 3280 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; 3281 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; 3282 3283 EXPECT_NONFATAL_FAILURE( 3284 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", 3285 "expected failure"); 3286 3287 EXPECT_FATAL_FAILURE( 3288 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", 3289 "expected failure"); 3290 3291 EXPECT_NONFATAL_FAILURE( 3292 EXPECT_HRESULT_FAILED(S_OK) << "expected failure", 3293 "expected failure"); 3294 3295 EXPECT_FATAL_FAILURE( 3296 ASSERT_HRESULT_FAILED(S_OK) << "expected failure", 3297 "expected failure"); 3298} 3299 3300#endif // GTEST_OS_WINDOWS 3301 3302// Tests that the assertion macros behave like single statements. 3303TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) { 3304 if (false) 3305 ASSERT_TRUE(false) << "This should never be executed; " 3306 "It's a compilation test only."; 3307 3308 if (true) 3309 EXPECT_FALSE(false); 3310 else 3311 ; 3312 3313 if (false) 3314 ASSERT_LT(1, 3); 3315 3316 if (false) 3317 ; 3318 else 3319 EXPECT_GT(3, 2) << ""; 3320} 3321 3322#if GTEST_HAS_EXCEPTIONS 3323// Tests that the compiler will not complain about unreachable code in the 3324// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros. 3325TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { 3326 int n = 0; 3327 3328 EXPECT_THROW(throw 1, int); 3329 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), ""); 3330 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), ""); 3331 EXPECT_NO_THROW(n++); 3332 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), ""); 3333 EXPECT_ANY_THROW(throw 1); 3334 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), ""); 3335} 3336 3337TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { 3338 if (false) 3339 EXPECT_THROW(ThrowNothing(), bool); 3340 3341 if (true) 3342 EXPECT_THROW(ThrowAnInteger(), int); 3343 else 3344 ; 3345 3346 if (false) 3347 EXPECT_NO_THROW(ThrowAnInteger()); 3348 3349 if (true) 3350 EXPECT_NO_THROW(ThrowNothing()); 3351 else 3352 ; 3353 3354 if (false) 3355 EXPECT_ANY_THROW(ThrowNothing()); 3356 3357 if (true) 3358 EXPECT_ANY_THROW(ThrowAnInteger()); 3359 else 3360 ; 3361} 3362#endif // GTEST_HAS_EXCEPTIONS 3363 3364TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) { 3365 if (false) 3366 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. " 3367 << "It's a compilation test only."; 3368 else 3369 ; 3370 3371 if (false) 3372 ASSERT_NO_FATAL_FAILURE(FAIL()) << ""; 3373 else 3374 ; 3375 3376 if (true) 3377 EXPECT_NO_FATAL_FAILURE(SUCCEED()); 3378 else 3379 ; 3380 3381 if (false) 3382 ; 3383 else 3384 ASSERT_NO_FATAL_FAILURE(SUCCEED()); 3385} 3386 3387// Tests that the assertion macros work well with switch statements. 3388TEST(AssertionSyntaxTest, WorksWithSwitch) { 3389 switch (0) { 3390 case 1: 3391 break; 3392 default: 3393 ASSERT_TRUE(true); 3394 } 3395 3396 switch (0) 3397 case 0: 3398 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case"; 3399 3400 // Binary assertions are implemented using a different code path 3401 // than the Boolean assertions. Hence we test them separately. 3402 switch (0) { 3403 case 1: 3404 default: 3405 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler"; 3406 } 3407 3408 switch (0) 3409 case 0: 3410 EXPECT_NE(1, 2); 3411} 3412 3413#if GTEST_HAS_EXCEPTIONS 3414 3415void ThrowAString() { 3416 throw "String"; 3417} 3418 3419// Test that the exception assertion macros compile and work with const 3420// type qualifier. 3421TEST(AssertionSyntaxTest, WorksWithConst) { 3422 ASSERT_THROW(ThrowAString(), const char*); 3423 3424 EXPECT_THROW(ThrowAString(), const char*); 3425} 3426 3427#endif // GTEST_HAS_EXCEPTIONS 3428 3429} // namespace 3430 3431// Returns the number of successful parts in the current test. 3432static size_t GetSuccessfulPartCount() { 3433 return UnitTest::GetInstance()->impl()->current_test_result()-> 3434 successful_part_count(); 3435} 3436 3437namespace testing { 3438 3439// Tests that Google Test tracks SUCCEED*. 3440TEST(SuccessfulAssertionTest, SUCCEED) { 3441 SUCCEED(); 3442 SUCCEED() << "OK"; 3443 EXPECT_EQ(2u, GetSuccessfulPartCount()); 3444} 3445 3446// Tests that Google Test doesn't track successful EXPECT_*. 3447TEST(SuccessfulAssertionTest, EXPECT) { 3448 EXPECT_TRUE(true); 3449 EXPECT_EQ(0u, GetSuccessfulPartCount()); 3450} 3451 3452// Tests that Google Test doesn't track successful EXPECT_STR*. 3453TEST(SuccessfulAssertionTest, EXPECT_STR) { 3454 EXPECT_STREQ("", ""); 3455 EXPECT_EQ(0u, GetSuccessfulPartCount()); 3456} 3457 3458// Tests that Google Test doesn't track successful ASSERT_*. 3459TEST(SuccessfulAssertionTest, ASSERT) { 3460 ASSERT_TRUE(true); 3461 EXPECT_EQ(0u, GetSuccessfulPartCount()); 3462} 3463 3464// Tests that Google Test doesn't track successful ASSERT_STR*. 3465TEST(SuccessfulAssertionTest, ASSERT_STR) { 3466 ASSERT_STREQ("", ""); 3467 EXPECT_EQ(0u, GetSuccessfulPartCount()); 3468} 3469 3470} // namespace testing 3471 3472namespace { 3473 3474// Tests EXPECT_TRUE. 3475TEST(ExpectTest, EXPECT_TRUE) { 3476 EXPECT_TRUE(2 > 1); // NOLINT 3477 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1), 3478 "Value of: 2 < 1\n" 3479 " Actual: false\n" 3480 "Expected: true"); 3481 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), 3482 "2 > 3"); 3483} 3484 3485// Tests EXPECT_FALSE. 3486TEST(ExpectTest, EXPECT_FALSE) { 3487 EXPECT_FALSE(2 < 1); // NOLINT 3488 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1), 3489 "Value of: 2 > 1\n" 3490 " Actual: true\n" 3491 "Expected: false"); 3492 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), 3493 "2 < 3"); 3494} 3495 3496// Tests EXPECT_EQ. 3497TEST(ExpectTest, EXPECT_EQ) { 3498 EXPECT_EQ(5, 2 + 3); 3499 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3), 3500 "Value of: 2*3\n" 3501 " Actual: 6\n" 3502 "Expected: 5"); 3503 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), 3504 "2 - 3"); 3505} 3506 3507// Tests using EXPECT_EQ on double values. The purpose is to make 3508// sure that the specialization we did for integer and anonymous enums 3509// isn't used for double arguments. 3510TEST(ExpectTest, EXPECT_EQ_Double) { 3511 // A success. 3512 EXPECT_EQ(5.6, 5.6); 3513 3514 // A failure. 3515 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), 3516 "5.1"); 3517} 3518 3519#if !GTEST_OS_SYMBIAN 3520// Tests EXPECT_EQ(NULL, pointer). 3521TEST(ExpectTest, EXPECT_EQ_NULL) { 3522 // A success. 3523 const char* p = NULL; 3524 EXPECT_EQ(NULL, p); 3525 3526 // A failure. 3527 int n = 0; 3528 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n), 3529 "Value of: &n\n"); 3530} 3531#endif // !GTEST_OS_SYMBIAN 3532 3533// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be 3534// treated as a null pointer by the compiler, we need to make sure 3535// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as 3536// EXPECT_EQ(static_cast<void*>(NULL), non_pointer). 3537TEST(ExpectTest, EXPECT_EQ_0) { 3538 int n = 0; 3539 3540 // A success. 3541 EXPECT_EQ(0, n); 3542 3543 // A failure. 3544 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), 3545 "Expected: 0"); 3546} 3547 3548// Tests EXPECT_NE. 3549TEST(ExpectTest, EXPECT_NE) { 3550 EXPECT_NE(6, 7); 3551 3552 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'), 3553 "Expected: ('a') != ('a'), " 3554 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); 3555 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), 3556 "2"); 3557 char* const p0 = NULL; 3558 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), 3559 "p0"); 3560 // Only way to get the Nokia compiler to compile the cast 3561 // is to have a separate void* variable first. Putting 3562 // the two casts on the same line doesn't work, neither does 3563 // a direct C-style to char*. 3564 void* pv1 = (void*)0x1234; // NOLINT 3565 char* const p1 = reinterpret_cast<char*>(pv1); 3566 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), 3567 "p1"); 3568} 3569 3570// Tests EXPECT_LE. 3571TEST(ExpectTest, EXPECT_LE) { 3572 EXPECT_LE(2, 3); 3573 EXPECT_LE(2, 2); 3574 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0), 3575 "Expected: (2) <= (0), actual: 2 vs 0"); 3576 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), 3577 "(1.1) <= (0.9)"); 3578} 3579 3580// Tests EXPECT_LT. 3581TEST(ExpectTest, EXPECT_LT) { 3582 EXPECT_LT(2, 3); 3583 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2), 3584 "Expected: (2) < (2), actual: 2 vs 2"); 3585 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), 3586 "(2) < (1)"); 3587} 3588 3589// Tests EXPECT_GE. 3590TEST(ExpectTest, EXPECT_GE) { 3591 EXPECT_GE(2, 1); 3592 EXPECT_GE(2, 2); 3593 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3), 3594 "Expected: (2) >= (3), actual: 2 vs 3"); 3595 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), 3596 "(0.9) >= (1.1)"); 3597} 3598 3599// Tests EXPECT_GT. 3600TEST(ExpectTest, EXPECT_GT) { 3601 EXPECT_GT(2, 1); 3602 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2), 3603 "Expected: (2) > (2), actual: 2 vs 2"); 3604 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), 3605 "(2) > (3)"); 3606} 3607 3608#if GTEST_HAS_EXCEPTIONS 3609 3610// Tests EXPECT_THROW. 3611TEST(ExpectTest, EXPECT_THROW) { 3612 EXPECT_THROW(ThrowAnInteger(), int); 3613 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool), 3614 "Expected: ThrowAnInteger() throws an exception of " 3615 "type bool.\n Actual: it throws a different type."); 3616 EXPECT_NONFATAL_FAILURE( 3617 EXPECT_THROW(ThrowNothing(), bool), 3618 "Expected: ThrowNothing() throws an exception of type bool.\n" 3619 " Actual: it throws nothing."); 3620} 3621 3622// Tests EXPECT_NO_THROW. 3623TEST(ExpectTest, EXPECT_NO_THROW) { 3624 EXPECT_NO_THROW(ThrowNothing()); 3625 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()), 3626 "Expected: ThrowAnInteger() doesn't throw an " 3627 "exception.\n Actual: it throws."); 3628} 3629 3630// Tests EXPECT_ANY_THROW. 3631TEST(ExpectTest, EXPECT_ANY_THROW) { 3632 EXPECT_ANY_THROW(ThrowAnInteger()); 3633 EXPECT_NONFATAL_FAILURE( 3634 EXPECT_ANY_THROW(ThrowNothing()), 3635 "Expected: ThrowNothing() throws an exception.\n" 3636 " Actual: it doesn't."); 3637} 3638 3639#endif // GTEST_HAS_EXCEPTIONS 3640 3641// Make sure we deal with the precedence of <<. 3642TEST(ExpectTest, ExpectPrecedence) { 3643 EXPECT_EQ(1 < 2, true); 3644 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false), 3645 "Value of: true && false"); 3646} 3647 3648 3649// Tests the StreamableToString() function. 3650 3651// Tests using StreamableToString() on a scalar. 3652TEST(StreamableToStringTest, Scalar) { 3653 EXPECT_STREQ("5", StreamableToString(5).c_str()); 3654} 3655 3656// Tests using StreamableToString() on a non-char pointer. 3657TEST(StreamableToStringTest, Pointer) { 3658 int n = 0; 3659 int* p = &n; 3660 EXPECT_STRNE("(null)", StreamableToString(p).c_str()); 3661} 3662 3663// Tests using StreamableToString() on a NULL non-char pointer. 3664TEST(StreamableToStringTest, NullPointer) { 3665 int* p = NULL; 3666 EXPECT_STREQ("(null)", StreamableToString(p).c_str()); 3667} 3668 3669// Tests using StreamableToString() on a C string. 3670TEST(StreamableToStringTest, CString) { 3671 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str()); 3672} 3673 3674// Tests using StreamableToString() on a NULL C string. 3675TEST(StreamableToStringTest, NullCString) { 3676 char* p = NULL; 3677 EXPECT_STREQ("(null)", StreamableToString(p).c_str()); 3678} 3679 3680// Tests using streamable values as assertion messages. 3681 3682#if GTEST_HAS_STD_STRING 3683// Tests using std::string as an assertion message. 3684TEST(StreamableTest, string) { 3685 static const std::string str( 3686 "This failure message is a std::string, and is expected."); 3687 EXPECT_FATAL_FAILURE(FAIL() << str, 3688 str.c_str()); 3689} 3690 3691// Tests that we can output strings containing embedded NULs. 3692// Limited to Linux because we can only do this with std::string's. 3693TEST(StreamableTest, stringWithEmbeddedNUL) { 3694 static const char char_array_with_nul[] = 3695 "Here's a NUL\0 and some more string"; 3696 static const std::string string_with_nul(char_array_with_nul, 3697 sizeof(char_array_with_nul) 3698 - 1); // drops the trailing NUL 3699 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul, 3700 "Here's a NUL\\0 and some more string"); 3701} 3702 3703#endif // GTEST_HAS_STD_STRING 3704 3705// Tests that we can output a NUL char. 3706TEST(StreamableTest, NULChar) { 3707 EXPECT_FATAL_FAILURE({ // NOLINT 3708 FAIL() << "A NUL" << '\0' << " and some more string"; 3709 }, "A NUL\\0 and some more string"); 3710} 3711 3712// Tests using int as an assertion message. 3713TEST(StreamableTest, int) { 3714 EXPECT_FATAL_FAILURE(FAIL() << 900913, 3715 "900913"); 3716} 3717 3718// Tests using NULL char pointer as an assertion message. 3719// 3720// In MSVC, streaming a NULL char * causes access violation. Google Test 3721// implemented a workaround (substituting "(null)" for NULL). This 3722// tests whether the workaround works. 3723TEST(StreamableTest, NullCharPtr) { 3724 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL), 3725 "(null)"); 3726} 3727 3728// Tests that basic IO manipulators (endl, ends, and flush) can be 3729// streamed to testing::Message. 3730TEST(StreamableTest, BasicIoManip) { 3731 EXPECT_FATAL_FAILURE({ // NOLINT 3732 FAIL() << "Line 1." << std::endl 3733 << "A NUL char " << std::ends << std::flush << " in line 2."; 3734 }, "Line 1.\nA NUL char \\0 in line 2."); 3735} 3736 3737// Tests the macros that haven't been covered so far. 3738 3739void AddFailureHelper(bool* aborted) { 3740 *aborted = true; 3741 ADD_FAILURE() << "Failure"; 3742 *aborted = false; 3743} 3744 3745// Tests ADD_FAILURE. 3746TEST(MacroTest, ADD_FAILURE) { 3747 bool aborted = true; 3748 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), 3749 "Failure"); 3750 EXPECT_FALSE(aborted); 3751} 3752 3753// Tests FAIL. 3754TEST(MacroTest, FAIL) { 3755 EXPECT_FATAL_FAILURE(FAIL(), 3756 "Failed"); 3757 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.", 3758 "Intentional failure."); 3759} 3760 3761// Tests SUCCEED 3762TEST(MacroTest, SUCCEED) { 3763 SUCCEED(); 3764 SUCCEED() << "Explicit success."; 3765} 3766 3767 3768// Tests for EXPECT_EQ() and ASSERT_EQ(). 3769// 3770// These tests fail *intentionally*, s.t. the failure messages can be 3771// generated and tested. 3772// 3773// We have different tests for different argument types. 3774 3775// Tests using bool values in {EXPECT|ASSERT}_EQ. 3776TEST(EqAssertionTest, Bool) { 3777 EXPECT_EQ(true, true); 3778 EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true), 3779 "Value of: true"); 3780} 3781 3782// Tests using int values in {EXPECT|ASSERT}_EQ. 3783TEST(EqAssertionTest, Int) { 3784 ASSERT_EQ(32, 32); 3785 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), 3786 "33"); 3787} 3788 3789// Tests using time_t values in {EXPECT|ASSERT}_EQ. 3790TEST(EqAssertionTest, Time_T) { 3791 EXPECT_EQ(static_cast<time_t>(0), 3792 static_cast<time_t>(0)); 3793 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0), 3794 static_cast<time_t>(1234)), 3795 "1234"); 3796} 3797 3798// Tests using char values in {EXPECT|ASSERT}_EQ. 3799TEST(EqAssertionTest, Char) { 3800 ASSERT_EQ('z', 'z'); 3801 const char ch = 'b'; 3802 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), 3803 "ch"); 3804 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), 3805 "ch"); 3806} 3807 3808#if GTEST_HAS_STD_WSTRING 3809// Tests using wchar_t values in {EXPECT|ASSERT}_EQ. 3810TEST(EqAssertionTest, WideChar) { 3811 EXPECT_EQ(L'b', L'b'); 3812 3813 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'), 3814 "Value of: L'x'\n" 3815 " Actual: L'x' (120, 0x78)\n" 3816 "Expected: L'\0'\n" 3817 "Which is: L'\0' (0, 0x0)"); 3818 3819 static wchar_t wchar; 3820 wchar = L'b'; 3821 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), 3822 "wchar"); 3823 wchar = L'\x8119'; 3824 EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar), 3825 "Value of: wchar"); 3826} 3827#endif // GTEST_HAS_STD_WSTRING 3828 3829#if GTEST_HAS_STD_STRING 3830// Tests using ::std::string values in {EXPECT|ASSERT}_EQ. 3831TEST(EqAssertionTest, StdString) { 3832 // Compares a const char* to an std::string that has identical 3833 // content. 3834 ASSERT_EQ("Test", ::std::string("Test")); 3835 3836 // Compares two identical std::strings. 3837 static const ::std::string str1("A * in the middle"); 3838 static const ::std::string str2(str1); 3839 EXPECT_EQ(str1, str2); 3840 3841 // Compares a const char* to an std::string that has different 3842 // content 3843 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), 3844 "::std::string(\"test\")"); 3845 3846 // Compares an std::string to a char* that has different content. 3847 char* const p1 = const_cast<char*>("foo"); 3848 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), 3849 "p1"); 3850 3851 // Compares two std::strings that have different contents, one of 3852 // which having a NUL character in the middle. This should fail. 3853 static ::std::string str3(str1); 3854 str3.at(2) = '\0'; 3855 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3), 3856 "Value of: str3\n" 3857 " Actual: \"A \\0 in the middle\""); 3858} 3859 3860#endif // GTEST_HAS_STD_STRING 3861 3862#if GTEST_HAS_STD_WSTRING 3863 3864// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ. 3865TEST(EqAssertionTest, StdWideString) { 3866 // Compares an std::wstring to a const wchar_t* that has identical 3867 // content. 3868 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119"); 3869 3870 // Compares two identical std::wstrings. 3871 const ::std::wstring wstr1(L"A * in the middle"); 3872 const ::std::wstring wstr2(wstr1); 3873 ASSERT_EQ(wstr1, wstr2); 3874 3875 // Compares an std::wstring to a const wchar_t* that has different 3876 // content. 3877 EXPECT_NONFATAL_FAILURE({ // NOLINT 3878 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120"); 3879 }, "L\"Test\\x8120\""); 3880 3881 // Compares two std::wstrings that have different contents, one of 3882 // which having a NUL character in the middle. 3883 ::std::wstring wstr3(wstr1); 3884 wstr3.at(2) = L'\0'; 3885 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), 3886 "wstr3"); 3887 3888 // Compares a wchar_t* to an std::wstring that has different 3889 // content. 3890 EXPECT_FATAL_FAILURE({ // NOLINT 3891 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar")); 3892 }, ""); 3893} 3894 3895#endif // GTEST_HAS_STD_WSTRING 3896 3897#if GTEST_HAS_GLOBAL_STRING 3898// Tests using ::string values in {EXPECT|ASSERT}_EQ. 3899TEST(EqAssertionTest, GlobalString) { 3900 // Compares a const char* to a ::string that has identical content. 3901 EXPECT_EQ("Test", ::string("Test")); 3902 3903 // Compares two identical ::strings. 3904 const ::string str1("A * in the middle"); 3905 const ::string str2(str1); 3906 ASSERT_EQ(str1, str2); 3907 3908 // Compares a ::string to a const char* that has different content. 3909 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"), 3910 "test"); 3911 3912 // Compares two ::strings that have different contents, one of which 3913 // having a NUL character in the middle. 3914 ::string str3(str1); 3915 str3.at(2) = '\0'; 3916 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3), 3917 "str3"); 3918 3919 // Compares a ::string to a char* that has different content. 3920 EXPECT_FATAL_FAILURE({ // NOLINT 3921 ASSERT_EQ(::string("bar"), const_cast<char*>("foo")); 3922 }, ""); 3923} 3924 3925#endif // GTEST_HAS_GLOBAL_STRING 3926 3927#if GTEST_HAS_GLOBAL_WSTRING 3928 3929// Tests using ::wstring values in {EXPECT|ASSERT}_EQ. 3930TEST(EqAssertionTest, GlobalWideString) { 3931 // Compares a const wchar_t* to a ::wstring that has identical content. 3932 ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119")); 3933 3934 // Compares two identical ::wstrings. 3935 static const ::wstring wstr1(L"A * in the middle"); 3936 static const ::wstring wstr2(wstr1); 3937 EXPECT_EQ(wstr1, wstr2); 3938 3939 // Compares a const wchar_t* to a ::wstring that has different 3940 // content. 3941 EXPECT_NONFATAL_FAILURE({ // NOLINT 3942 EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119")); 3943 }, "Test\\x8119"); 3944 3945 // Compares a wchar_t* to a ::wstring that has different content. 3946 wchar_t* const p1 = const_cast<wchar_t*>(L"foo"); 3947 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")), 3948 "bar"); 3949 3950 // Compares two ::wstrings that have different contents, one of which 3951 // having a NUL character in the middle. 3952 static ::wstring wstr3; 3953 wstr3 = wstr1; 3954 wstr3.at(2) = L'\0'; 3955 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3), 3956 "wstr3"); 3957} 3958 3959#endif // GTEST_HAS_GLOBAL_WSTRING 3960 3961// Tests using char pointers in {EXPECT|ASSERT}_EQ. 3962TEST(EqAssertionTest, CharPointer) { 3963 char* const p0 = NULL; 3964 // Only way to get the Nokia compiler to compile the cast 3965 // is to have a separate void* variable first. Putting 3966 // the two casts on the same line doesn't work, neither does 3967 // a direct C-style to char*. 3968 void* pv1 = (void*)0x1234; // NOLINT 3969 void* pv2 = (void*)0xABC0; // NOLINT 3970 char* const p1 = reinterpret_cast<char*>(pv1); 3971 char* const p2 = reinterpret_cast<char*>(pv2); 3972 ASSERT_EQ(p1, p1); 3973 3974 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), 3975 "Value of: p2"); 3976 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), 3977 "p2"); 3978 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234), 3979 reinterpret_cast<char*>(0xABC0)), 3980 "ABC0"); 3981} 3982 3983// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ. 3984TEST(EqAssertionTest, WideCharPointer) { 3985 wchar_t* const p0 = NULL; 3986 // Only way to get the Nokia compiler to compile the cast 3987 // is to have a separate void* variable first. Putting 3988 // the two casts on the same line doesn't work, neither does 3989 // a direct C-style to char*. 3990 void* pv1 = (void*)0x1234; // NOLINT 3991 void* pv2 = (void*)0xABC0; // NOLINT 3992 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1); 3993 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2); 3994 EXPECT_EQ(p0, p0); 3995 3996 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), 3997 "Value of: p2"); 3998 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), 3999 "p2"); 4000 void* pv3 = (void*)0x1234; // NOLINT 4001 void* pv4 = (void*)0xABC0; // NOLINT 4002 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3); 4003 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4); 4004 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), 4005 "p4"); 4006} 4007 4008// Tests using other types of pointers in {EXPECT|ASSERT}_EQ. 4009TEST(EqAssertionTest, OtherPointer) { 4010 ASSERT_EQ(static_cast<const int*>(NULL), 4011 static_cast<const int*>(NULL)); 4012 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL), 4013 reinterpret_cast<const int*>(0x1234)), 4014 "0x1234"); 4015} 4016 4017// Tests the FRIEND_TEST macro. 4018 4019// This class has a private member we want to test. We will test it 4020// both in a TEST and in a TEST_F. 4021class Foo { 4022 public: 4023 Foo() {} 4024 4025 private: 4026 int Bar() const { return 1; } 4027 4028 // Declares the friend tests that can access the private member 4029 // Bar(). 4030 FRIEND_TEST(FRIEND_TEST_Test, TEST); 4031 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F); 4032}; 4033 4034// Tests that the FRIEND_TEST declaration allows a TEST to access a 4035// class's private members. This should compile. 4036TEST(FRIEND_TEST_Test, TEST) { 4037 ASSERT_EQ(1, Foo().Bar()); 4038} 4039 4040// The fixture needed to test using FRIEND_TEST with TEST_F. 4041class FRIEND_TEST_Test2 : public Test { 4042 protected: 4043 Foo foo; 4044}; 4045 4046// Tests that the FRIEND_TEST declaration allows a TEST_F to access a 4047// class's private members. This should compile. 4048TEST_F(FRIEND_TEST_Test2, TEST_F) { 4049 ASSERT_EQ(1, foo.Bar()); 4050} 4051 4052// Tests the life cycle of Test objects. 4053 4054// The test fixture for testing the life cycle of Test objects. 4055// 4056// This class counts the number of live test objects that uses this 4057// fixture. 4058class TestLifeCycleTest : public Test { 4059 protected: 4060 // Constructor. Increments the number of test objects that uses 4061 // this fixture. 4062 TestLifeCycleTest() { count_++; } 4063 4064 // Destructor. Decrements the number of test objects that uses this 4065 // fixture. 4066 ~TestLifeCycleTest() { count_--; } 4067 4068 // Returns the number of live test objects that uses this fixture. 4069 int count() const { return count_; } 4070 4071 private: 4072 static int count_; 4073}; 4074 4075int TestLifeCycleTest::count_ = 0; 4076 4077// Tests the life cycle of test objects. 4078TEST_F(TestLifeCycleTest, Test1) { 4079 // There should be only one test object in this test case that's 4080 // currently alive. 4081 ASSERT_EQ(1, count()); 4082} 4083 4084// Tests the life cycle of test objects. 4085TEST_F(TestLifeCycleTest, Test2) { 4086 // After Test1 is done and Test2 is started, there should still be 4087 // only one live test object, as the object for Test1 should've been 4088 // deleted. 4089 ASSERT_EQ(1, count()); 4090} 4091 4092} // namespace 4093 4094// Tests streaming a user type whose definition and operator << are 4095// both in the global namespace. 4096class Base { 4097 public: 4098 explicit Base(int x) : x_(x) {} 4099 int x() const { return x_; } 4100 private: 4101 int x_; 4102}; 4103std::ostream& operator<<(std::ostream& os, 4104 const Base& val) { 4105 return os << val.x(); 4106} 4107std::ostream& operator<<(std::ostream& os, 4108 const Base* pointer) { 4109 return os << "(" << pointer->x() << ")"; 4110} 4111 4112TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) { 4113 Message msg; 4114 Base a(1); 4115 4116 msg << a << &a; // Uses ::operator<<. 4117 EXPECT_STREQ("1(1)", msg.GetString().c_str()); 4118} 4119 4120// Tests streaming a user type whose definition and operator<< are 4121// both in an unnamed namespace. 4122namespace { 4123class MyTypeInUnnamedNameSpace : public Base { 4124 public: 4125 explicit MyTypeInUnnamedNameSpace(int x): Base(x) {} 4126}; 4127std::ostream& operator<<(std::ostream& os, 4128 const MyTypeInUnnamedNameSpace& val) { 4129 return os << val.x(); 4130} 4131std::ostream& operator<<(std::ostream& os, 4132 const MyTypeInUnnamedNameSpace* pointer) { 4133 return os << "(" << pointer->x() << ")"; 4134} 4135} // namespace 4136 4137TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) { 4138 Message msg; 4139 MyTypeInUnnamedNameSpace a(1); 4140 4141 msg << a << &a; // Uses <unnamed_namespace>::operator<<. 4142 EXPECT_STREQ("1(1)", msg.GetString().c_str()); 4143} 4144 4145// Tests streaming a user type whose definition and operator<< are 4146// both in a user namespace. 4147namespace namespace1 { 4148class MyTypeInNameSpace1 : public Base { 4149 public: 4150 explicit MyTypeInNameSpace1(int x): Base(x) {} 4151}; 4152std::ostream& operator<<(std::ostream& os, 4153 const MyTypeInNameSpace1& val) { 4154 return os << val.x(); 4155} 4156std::ostream& operator<<(std::ostream& os, 4157 const MyTypeInNameSpace1* pointer) { 4158 return os << "(" << pointer->x() << ")"; 4159} 4160} // namespace namespace1 4161 4162TEST(MessageTest, CanStreamUserTypeInUserNameSpace) { 4163 Message msg; 4164 namespace1::MyTypeInNameSpace1 a(1); 4165 4166 msg << a << &a; // Uses namespace1::operator<<. 4167 EXPECT_STREQ("1(1)", msg.GetString().c_str()); 4168} 4169 4170// Tests streaming a user type whose definition is in a user namespace 4171// but whose operator<< is in the global namespace. 4172namespace namespace2 { 4173class MyTypeInNameSpace2 : public ::Base { 4174 public: 4175 explicit MyTypeInNameSpace2(int x): Base(x) {} 4176}; 4177} // namespace namespace2 4178std::ostream& operator<<(std::ostream& os, 4179 const namespace2::MyTypeInNameSpace2& val) { 4180 return os << val.x(); 4181} 4182std::ostream& operator<<(std::ostream& os, 4183 const namespace2::MyTypeInNameSpace2* pointer) { 4184 return os << "(" << pointer->x() << ")"; 4185} 4186 4187TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) { 4188 Message msg; 4189 namespace2::MyTypeInNameSpace2 a(1); 4190 4191 msg << a << &a; // Uses ::operator<<. 4192 EXPECT_STREQ("1(1)", msg.GetString().c_str()); 4193} 4194 4195// Tests streaming NULL pointers to testing::Message. 4196TEST(MessageTest, NullPointers) { 4197 Message msg; 4198 char* const p1 = NULL; 4199 unsigned char* const p2 = NULL; 4200 int* p3 = NULL; 4201 double* p4 = NULL; 4202 bool* p5 = NULL; 4203 Message* p6 = NULL; 4204 4205 msg << p1 << p2 << p3 << p4 << p5 << p6; 4206 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", 4207 msg.GetString().c_str()); 4208} 4209 4210#if GTEST_HAS_STD_WSTRING 4211// Tests streaming wide strings to testing::Message. 4212TEST(MessageTest, WideStrings) { 4213 // Streams a NULL of type const wchar_t*. 4214 const wchar_t* const_wstr = NULL; 4215 EXPECT_STREQ("(null)", 4216 (Message() << const_wstr).GetString().c_str()); 4217 4218 // Streams a NULL of type wchar_t*. 4219 wchar_t* wstr = NULL; 4220 EXPECT_STREQ("(null)", 4221 (Message() << wstr).GetString().c_str()); 4222 4223 // Streams a non-NULL of type const wchar_t*. 4224 const_wstr = L"abc\x8119"; 4225 EXPECT_STREQ("abc\xe8\x84\x99", 4226 (Message() << const_wstr).GetString().c_str()); 4227 4228 // Streams a non-NULL of type wchar_t*. 4229 wstr = const_cast<wchar_t*>(const_wstr); 4230 EXPECT_STREQ("abc\xe8\x84\x99", 4231 (Message() << wstr).GetString().c_str()); 4232} 4233#endif // GTEST_HAS_STD_WSTRING 4234 4235// This line tests that we can define tests in the testing namespace. 4236namespace testing { 4237 4238// Tests the TestInfo class. 4239 4240class TestInfoTest : public Test { 4241 protected: 4242 static TestInfo * GetTestInfo(const char* test_name) { 4243 return UnitTest::GetInstance()->impl()-> 4244 GetTestCase("TestInfoTest", "", NULL, NULL)-> 4245 GetTestInfo(test_name); 4246 } 4247 4248 static const TestResult* GetTestResult( 4249 const TestInfo* test_info) { 4250 return test_info->result(); 4251 } 4252}; 4253 4254// Tests TestInfo::test_case_name() and TestInfo::name(). 4255TEST_F(TestInfoTest, Names) { 4256 TestInfo * const test_info = GetTestInfo("Names"); 4257 4258 ASSERT_STREQ("TestInfoTest", test_info->test_case_name()); 4259 ASSERT_STREQ("Names", test_info->name()); 4260} 4261 4262// Tests TestInfo::result(). 4263TEST_F(TestInfoTest, result) { 4264 TestInfo * const test_info = GetTestInfo("result"); 4265 4266 // Initially, there is no TestPartResult for this test. 4267 ASSERT_EQ(0u, GetTestResult(test_info)->total_part_count()); 4268 4269 // After the previous assertion, there is still none. 4270 ASSERT_EQ(0u, GetTestResult(test_info)->total_part_count()); 4271} 4272 4273// Tests setting up and tearing down a test case. 4274 4275class SetUpTestCaseTest : public Test { 4276 protected: 4277 // This will be called once before the first test in this test case 4278 // is run. 4279 static void SetUpTestCase() { 4280 printf("Setting up the test case . . .\n"); 4281 4282 // Initializes some shared resource. In this simple example, we 4283 // just create a C string. More complex stuff can be done if 4284 // desired. 4285 shared_resource_ = "123"; 4286 4287 // Increments the number of test cases that have been set up. 4288 counter_++; 4289 4290 // SetUpTestCase() should be called only once. 4291 EXPECT_EQ(1, counter_); 4292 } 4293 4294 // This will be called once after the last test in this test case is 4295 // run. 4296 static void TearDownTestCase() { 4297 printf("Tearing down the test case . . .\n"); 4298 4299 // Decrements the number of test cases that have been set up. 4300 counter_--; 4301 4302 // TearDownTestCase() should be called only once. 4303 EXPECT_EQ(0, counter_); 4304 4305 // Cleans up the shared resource. 4306 shared_resource_ = NULL; 4307 } 4308 4309 // This will be called before each test in this test case. 4310 virtual void SetUp() { 4311 // SetUpTestCase() should be called only once, so counter_ should 4312 // always be 1. 4313 EXPECT_EQ(1, counter_); 4314 } 4315 4316 // Number of test cases that have been set up. 4317 static int counter_; 4318 4319 // Some resource to be shared by all tests in this test case. 4320 static const char* shared_resource_; 4321}; 4322 4323int SetUpTestCaseTest::counter_ = 0; 4324const char* SetUpTestCaseTest::shared_resource_ = NULL; 4325 4326// A test that uses the shared resource. 4327TEST_F(SetUpTestCaseTest, Test1) { 4328 EXPECT_STRNE(NULL, shared_resource_); 4329} 4330 4331// Another test that uses the shared resource. 4332TEST_F(SetUpTestCaseTest, Test2) { 4333 EXPECT_STREQ("123", shared_resource_); 4334} 4335 4336// The InitGoogleTestTest test case tests testing::InitGoogleTest(). 4337 4338// The Flags struct stores a copy of all Google Test flags. 4339struct Flags { 4340 // Constructs a Flags struct where each flag has its default value. 4341 Flags() : also_run_disabled_tests(false), 4342 break_on_failure(false), 4343 catch_exceptions(false), 4344 death_test_use_fork(false), 4345 filter(""), 4346 list_tests(false), 4347 output(""), 4348 print_time(false), 4349 repeat(1), 4350 throw_on_failure(false) {} 4351 4352 // Factory methods. 4353 4354 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has 4355 // the given value. 4356 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) { 4357 Flags flags; 4358 flags.also_run_disabled_tests = also_run_disabled_tests; 4359 return flags; 4360 } 4361 4362 // Creates a Flags struct where the gtest_break_on_failure flag has 4363 // the given value. 4364 static Flags BreakOnFailure(bool break_on_failure) { 4365 Flags flags; 4366 flags.break_on_failure = break_on_failure; 4367 return flags; 4368 } 4369 4370 // Creates a Flags struct where the gtest_catch_exceptions flag has 4371 // the given value. 4372 static Flags CatchExceptions(bool catch_exceptions) { 4373 Flags flags; 4374 flags.catch_exceptions = catch_exceptions; 4375 return flags; 4376 } 4377 4378 // Creates a Flags struct where the gtest_death_test_use_fork flag has 4379 // the given value. 4380 static Flags DeathTestUseFork(bool death_test_use_fork) { 4381 Flags flags; 4382 flags.death_test_use_fork = death_test_use_fork; 4383 return flags; 4384 } 4385 4386 // Creates a Flags struct where the gtest_filter flag has the given 4387 // value. 4388 static Flags Filter(const char* filter) { 4389 Flags flags; 4390 flags.filter = filter; 4391 return flags; 4392 } 4393 4394 // Creates a Flags struct where the gtest_list_tests flag has the 4395 // given value. 4396 static Flags ListTests(bool list_tests) { 4397 Flags flags; 4398 flags.list_tests = list_tests; 4399 return flags; 4400 } 4401 4402 // Creates a Flags struct where the gtest_output flag has the given 4403 // value. 4404 static Flags Output(const char* output) { 4405 Flags flags; 4406 flags.output = output; 4407 return flags; 4408 } 4409 4410 // Creates a Flags struct where the gtest_print_time flag has the given 4411 // value. 4412 static Flags PrintTime(bool print_time) { 4413 Flags flags; 4414 flags.print_time = print_time; 4415 return flags; 4416 } 4417 4418 // Creates a Flags struct where the gtest_repeat flag has the given 4419 // value. 4420 static Flags Repeat(Int32 repeat) { 4421 Flags flags; 4422 flags.repeat = repeat; 4423 return flags; 4424 } 4425 4426 // Creates a Flags struct where the gtest_throw_on_failure flag has 4427 // the given value. 4428 static Flags ThrowOnFailure(bool throw_on_failure) { 4429 Flags flags; 4430 flags.throw_on_failure = throw_on_failure; 4431 return flags; 4432 } 4433 4434 // These fields store the flag values. 4435 bool also_run_disabled_tests; 4436 bool break_on_failure; 4437 bool catch_exceptions; 4438 bool death_test_use_fork; 4439 const char* filter; 4440 bool list_tests; 4441 const char* output; 4442 bool print_time; 4443 Int32 repeat; 4444 bool throw_on_failure; 4445}; 4446 4447// Fixture for testing InitGoogleTest(). 4448class InitGoogleTestTest : public Test { 4449 protected: 4450 // Clears the flags before each test. 4451 virtual void SetUp() { 4452 GTEST_FLAG(also_run_disabled_tests) = false; 4453 GTEST_FLAG(break_on_failure) = false; 4454 GTEST_FLAG(catch_exceptions) = false; 4455 GTEST_FLAG(death_test_use_fork) = false; 4456 GTEST_FLAG(filter) = ""; 4457 GTEST_FLAG(list_tests) = false; 4458 GTEST_FLAG(output) = ""; 4459 GTEST_FLAG(print_time) = false; 4460 GTEST_FLAG(repeat) = 1; 4461 GTEST_FLAG(throw_on_failure) = false; 4462 } 4463 4464 // Asserts that two narrow or wide string arrays are equal. 4465 template <typename CharType> 4466 static void AssertStringArrayEq(size_t size1, CharType** array1, 4467 size_t size2, CharType** array2) { 4468 ASSERT_EQ(size1, size2) << " Array sizes different."; 4469 4470 for (size_t i = 0; i != size1; i++) { 4471 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i; 4472 } 4473 } 4474 4475 // Verifies that the flag values match the expected values. 4476 static void CheckFlags(const Flags& expected) { 4477 EXPECT_EQ(expected.also_run_disabled_tests, 4478 GTEST_FLAG(also_run_disabled_tests)); 4479 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure)); 4480 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions)); 4481 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork)); 4482 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str()); 4483 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests)); 4484 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str()); 4485 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time)); 4486 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat)); 4487 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure)); 4488 } 4489 4490 // Parses a command line (specified by argc1 and argv1), then 4491 // verifies that the flag values are expected and that the 4492 // recognized flags are removed from the command line. 4493 template <typename CharType> 4494 static void TestParsingFlags(int argc1, const CharType** argv1, 4495 int argc2, const CharType** argv2, 4496 const Flags& expected) { 4497 // Parses the command line. 4498 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1)); 4499 4500 // Verifies the flag values. 4501 CheckFlags(expected); 4502 4503 // Verifies that the recognized flags are removed from the command 4504 // line. 4505 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2); 4506 } 4507 4508 // This macro wraps TestParsingFlags s.t. the user doesn't need 4509 // to specify the array sizes. 4510#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected) \ 4511 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \ 4512 sizeof(argv2)/sizeof(*argv2) - 1, argv2, expected) 4513}; 4514 4515// Tests parsing an empty command line. 4516TEST_F(InitGoogleTestTest, Empty) { 4517 const char* argv[] = { 4518 NULL 4519 }; 4520 4521 const char* argv2[] = { 4522 NULL 4523 }; 4524 4525 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags()); 4526} 4527 4528// Tests parsing a command line that has no flag. 4529TEST_F(InitGoogleTestTest, NoFlag) { 4530 const char* argv[] = { 4531 "foo.exe", 4532 NULL 4533 }; 4534 4535 const char* argv2[] = { 4536 "foo.exe", 4537 NULL 4538 }; 4539 4540 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags()); 4541} 4542 4543// Tests parsing a bad --gtest_filter flag. 4544TEST_F(InitGoogleTestTest, FilterBad) { 4545 const char* argv[] = { 4546 "foo.exe", 4547 "--gtest_filter", 4548 NULL 4549 }; 4550 4551 const char* argv2[] = { 4552 "foo.exe", 4553 "--gtest_filter", 4554 NULL 4555 }; 4556 4557 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("")); 4558} 4559 4560// Tests parsing an empty --gtest_filter flag. 4561TEST_F(InitGoogleTestTest, FilterEmpty) { 4562 const char* argv[] = { 4563 "foo.exe", 4564 "--gtest_filter=", 4565 NULL 4566 }; 4567 4568 const char* argv2[] = { 4569 "foo.exe", 4570 NULL 4571 }; 4572 4573 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("")); 4574} 4575 4576// Tests parsing a non-empty --gtest_filter flag. 4577TEST_F(InitGoogleTestTest, FilterNonEmpty) { 4578 const char* argv[] = { 4579 "foo.exe", 4580 "--gtest_filter=abc", 4581 NULL 4582 }; 4583 4584 const char* argv2[] = { 4585 "foo.exe", 4586 NULL 4587 }; 4588 4589 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc")); 4590} 4591 4592// Tests parsing --gtest_break_on_failure. 4593TEST_F(InitGoogleTestTest, BreakOnFailureNoDef) { 4594 const char* argv[] = { 4595 "foo.exe", 4596 "--gtest_break_on_failure", 4597 NULL 4598}; 4599 4600 const char* argv2[] = { 4601 "foo.exe", 4602 NULL 4603 }; 4604 4605 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true)); 4606} 4607 4608// Tests parsing --gtest_break_on_failure=0. 4609TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) { 4610 const char* argv[] = { 4611 "foo.exe", 4612 "--gtest_break_on_failure=0", 4613 NULL 4614 }; 4615 4616 const char* argv2[] = { 4617 "foo.exe", 4618 NULL 4619 }; 4620 4621 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false)); 4622} 4623 4624// Tests parsing --gtest_break_on_failure=f. 4625TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) { 4626 const char* argv[] = { 4627 "foo.exe", 4628 "--gtest_break_on_failure=f", 4629 NULL 4630 }; 4631 4632 const char* argv2[] = { 4633 "foo.exe", 4634 NULL 4635 }; 4636 4637 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false)); 4638} 4639 4640// Tests parsing --gtest_break_on_failure=F. 4641TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) { 4642 const char* argv[] = { 4643 "foo.exe", 4644 "--gtest_break_on_failure=F", 4645 NULL 4646 }; 4647 4648 const char* argv2[] = { 4649 "foo.exe", 4650 NULL 4651 }; 4652 4653 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false)); 4654} 4655 4656// Tests parsing a --gtest_break_on_failure flag that has a "true" 4657// definition. 4658TEST_F(InitGoogleTestTest, BreakOnFailureTrue) { 4659 const char* argv[] = { 4660 "foo.exe", 4661 "--gtest_break_on_failure=1", 4662 NULL 4663 }; 4664 4665 const char* argv2[] = { 4666 "foo.exe", 4667 NULL 4668 }; 4669 4670 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true)); 4671} 4672 4673// Tests parsing --gtest_catch_exceptions. 4674TEST_F(InitGoogleTestTest, CatchExceptions) { 4675 const char* argv[] = { 4676 "foo.exe", 4677 "--gtest_catch_exceptions", 4678 NULL 4679 }; 4680 4681 const char* argv2[] = { 4682 "foo.exe", 4683 NULL 4684 }; 4685 4686 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true)); 4687} 4688 4689// Tests parsing --gtest_death_test_use_fork. 4690TEST_F(InitGoogleTestTest, DeathTestUseFork) { 4691 const char* argv[] = { 4692 "foo.exe", 4693 "--gtest_death_test_use_fork", 4694 NULL 4695 }; 4696 4697 const char* argv2[] = { 4698 "foo.exe", 4699 NULL 4700 }; 4701 4702 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true)); 4703} 4704 4705// Tests having the same flag twice with different values. The 4706// expected behavior is that the one coming last takes precedence. 4707TEST_F(InitGoogleTestTest, DuplicatedFlags) { 4708 const char* argv[] = { 4709 "foo.exe", 4710 "--gtest_filter=a", 4711 "--gtest_filter=b", 4712 NULL 4713 }; 4714 4715 const char* argv2[] = { 4716 "foo.exe", 4717 NULL 4718 }; 4719 4720 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b")); 4721} 4722 4723// Tests having an unrecognized flag on the command line. 4724TEST_F(InitGoogleTestTest, UnrecognizedFlag) { 4725 const char* argv[] = { 4726 "foo.exe", 4727 "--gtest_break_on_failure", 4728 "bar", // Unrecognized by Google Test. 4729 "--gtest_filter=b", 4730 NULL 4731 }; 4732 4733 const char* argv2[] = { 4734 "foo.exe", 4735 "bar", 4736 NULL 4737 }; 4738 4739 Flags flags; 4740 flags.break_on_failure = true; 4741 flags.filter = "b"; 4742 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags); 4743} 4744 4745// Tests having a --gtest_list_tests flag 4746TEST_F(InitGoogleTestTest, ListTestsFlag) { 4747 const char* argv[] = { 4748 "foo.exe", 4749 "--gtest_list_tests", 4750 NULL 4751 }; 4752 4753 const char* argv2[] = { 4754 "foo.exe", 4755 NULL 4756 }; 4757 4758 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true)); 4759} 4760 4761// Tests having a --gtest_list_tests flag with a "true" value 4762TEST_F(InitGoogleTestTest, ListTestsTrue) { 4763 const char* argv[] = { 4764 "foo.exe", 4765 "--gtest_list_tests=1", 4766 NULL 4767 }; 4768 4769 const char* argv2[] = { 4770 "foo.exe", 4771 NULL 4772 }; 4773 4774 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true)); 4775} 4776 4777// Tests having a --gtest_list_tests flag with a "false" value 4778TEST_F(InitGoogleTestTest, ListTestsFalse) { 4779 const char* argv[] = { 4780 "foo.exe", 4781 "--gtest_list_tests=0", 4782 NULL 4783 }; 4784 4785 const char* argv2[] = { 4786 "foo.exe", 4787 NULL 4788 }; 4789 4790 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false)); 4791} 4792 4793// Tests parsing --gtest_list_tests=f. 4794TEST_F(InitGoogleTestTest, ListTestsFalse_f) { 4795 const char* argv[] = { 4796 "foo.exe", 4797 "--gtest_list_tests=f", 4798 NULL 4799 }; 4800 4801 const char* argv2[] = { 4802 "foo.exe", 4803 NULL 4804 }; 4805 4806 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false)); 4807} 4808 4809// Tests parsing --gtest_break_on_failure=F. 4810TEST_F(InitGoogleTestTest, ListTestsFalse_F) { 4811 const char* argv[] = { 4812 "foo.exe", 4813 "--gtest_list_tests=F", 4814 NULL 4815 }; 4816 4817 const char* argv2[] = { 4818 "foo.exe", 4819 NULL 4820 }; 4821 4822 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false)); 4823} 4824 4825// Tests parsing --gtest_output (invalid). 4826TEST_F(InitGoogleTestTest, OutputEmpty) { 4827 const char* argv[] = { 4828 "foo.exe", 4829 "--gtest_output", 4830 NULL 4831 }; 4832 4833 const char* argv2[] = { 4834 "foo.exe", 4835 "--gtest_output", 4836 NULL 4837 }; 4838 4839 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags()); 4840} 4841 4842// Tests parsing --gtest_output=xml 4843TEST_F(InitGoogleTestTest, OutputXml) { 4844 const char* argv[] = { 4845 "foo.exe", 4846 "--gtest_output=xml", 4847 NULL 4848 }; 4849 4850 const char* argv2[] = { 4851 "foo.exe", 4852 NULL 4853 }; 4854 4855 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml")); 4856} 4857 4858// Tests parsing --gtest_output=xml:file 4859TEST_F(InitGoogleTestTest, OutputXmlFile) { 4860 const char* argv[] = { 4861 "foo.exe", 4862 "--gtest_output=xml:file", 4863 NULL 4864 }; 4865 4866 const char* argv2[] = { 4867 "foo.exe", 4868 NULL 4869 }; 4870 4871 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file")); 4872} 4873 4874// Tests parsing --gtest_output=xml:directory/path/ 4875TEST_F(InitGoogleTestTest, OutputXmlDirectory) { 4876 const char* argv[] = { 4877 "foo.exe", 4878 "--gtest_output=xml:directory/path/", 4879 NULL 4880 }; 4881 4882 const char* argv2[] = { 4883 "foo.exe", 4884 NULL 4885 }; 4886 4887 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/")); 4888} 4889 4890// Tests having a --gtest_print_time flag 4891TEST_F(InitGoogleTestTest, PrintTimeFlag) { 4892 const char* argv[] = { 4893 "foo.exe", 4894 "--gtest_print_time", 4895 NULL 4896 }; 4897 4898 const char* argv2[] = { 4899 "foo.exe", 4900 NULL 4901 }; 4902 4903 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true)); 4904} 4905 4906// Tests having a --gtest_print_time flag with a "true" value 4907TEST_F(InitGoogleTestTest, PrintTimeTrue) { 4908 const char* argv[] = { 4909 "foo.exe", 4910 "--gtest_print_time=1", 4911 NULL 4912 }; 4913 4914 const char* argv2[] = { 4915 "foo.exe", 4916 NULL 4917 }; 4918 4919 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true)); 4920} 4921 4922// Tests having a --gtest_print_time flag with a "false" value 4923TEST_F(InitGoogleTestTest, PrintTimeFalse) { 4924 const char* argv[] = { 4925 "foo.exe", 4926 "--gtest_print_time=0", 4927 NULL 4928 }; 4929 4930 const char* argv2[] = { 4931 "foo.exe", 4932 NULL 4933 }; 4934 4935 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false)); 4936} 4937 4938// Tests parsing --gtest_print_time=f. 4939TEST_F(InitGoogleTestTest, PrintTimeFalse_f) { 4940 const char* argv[] = { 4941 "foo.exe", 4942 "--gtest_print_time=f", 4943 NULL 4944 }; 4945 4946 const char* argv2[] = { 4947 "foo.exe", 4948 NULL 4949 }; 4950 4951 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false)); 4952} 4953 4954// Tests parsing --gtest_print_time=F. 4955TEST_F(InitGoogleTestTest, PrintTimeFalse_F) { 4956 const char* argv[] = { 4957 "foo.exe", 4958 "--gtest_print_time=F", 4959 NULL 4960 }; 4961 4962 const char* argv2[] = { 4963 "foo.exe", 4964 NULL 4965 }; 4966 4967 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false)); 4968} 4969 4970// Tests parsing --gtest_repeat=number 4971TEST_F(InitGoogleTestTest, Repeat) { 4972 const char* argv[] = { 4973 "foo.exe", 4974 "--gtest_repeat=1000", 4975 NULL 4976 }; 4977 4978 const char* argv2[] = { 4979 "foo.exe", 4980 NULL 4981 }; 4982 4983 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000)); 4984} 4985 4986// Tests having a --gtest_also_run_disabled_tests flag 4987TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) { 4988 const char* argv[] = { 4989 "foo.exe", 4990 "--gtest_also_run_disabled_tests", 4991 NULL 4992 }; 4993 4994 const char* argv2[] = { 4995 "foo.exe", 4996 NULL 4997 }; 4998 4999 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true)); 5000} 5001 5002// Tests having a --gtest_also_run_disabled_tests flag with a "true" value 5003TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) { 5004 const char* argv[] = { 5005 "foo.exe", 5006 "--gtest_also_run_disabled_tests=1", 5007 NULL 5008 }; 5009 5010 const char* argv2[] = { 5011 "foo.exe", 5012 NULL 5013 }; 5014 5015 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true)); 5016} 5017 5018// Tests having a --gtest_also_run_disabled_tests flag with a "false" value 5019TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) { 5020 const char* argv[] = { 5021 "foo.exe", 5022 "--gtest_also_run_disabled_tests=0", 5023 NULL 5024 }; 5025 5026 const char* argv2[] = { 5027 "foo.exe", 5028 NULL 5029 }; 5030 5031 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false)); 5032} 5033 5034 5035// Tests parsing --gtest_throw_on_failure. 5036TEST_F(InitGoogleTestTest, ThrowOnFailureNoDef) { 5037 const char* argv[] = { 5038 "foo.exe", 5039 "--gtest_throw_on_failure", 5040 NULL 5041}; 5042 5043 const char* argv2[] = { 5044 "foo.exe", 5045 NULL 5046 }; 5047 5048 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true)); 5049} 5050 5051// Tests parsing --gtest_throw_on_failure=0. 5052TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) { 5053 const char* argv[] = { 5054 "foo.exe", 5055 "--gtest_throw_on_failure=0", 5056 NULL 5057 }; 5058 5059 const char* argv2[] = { 5060 "foo.exe", 5061 NULL 5062 }; 5063 5064 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false)); 5065} 5066 5067// Tests parsing a --gtest_throw_on_failure flag that has a "true" 5068// definition. 5069TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) { 5070 const char* argv[] = { 5071 "foo.exe", 5072 "--gtest_throw_on_failure=1", 5073 NULL 5074 }; 5075 5076 const char* argv2[] = { 5077 "foo.exe", 5078 NULL 5079 }; 5080 5081 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true)); 5082} 5083 5084#if GTEST_OS_WINDOWS 5085// Tests parsing wide strings. 5086TEST_F(InitGoogleTestTest, WideStrings) { 5087 const wchar_t* argv[] = { 5088 L"foo.exe", 5089 L"--gtest_filter=Foo*", 5090 L"--gtest_list_tests=1", 5091 L"--gtest_break_on_failure", 5092 L"--non_gtest_flag", 5093 NULL 5094 }; 5095 5096 const wchar_t* argv2[] = { 5097 L"foo.exe", 5098 L"--non_gtest_flag", 5099 NULL 5100 }; 5101 5102 Flags expected_flags; 5103 expected_flags.break_on_failure = true; 5104 expected_flags.filter = "Foo*"; 5105 expected_flags.list_tests = true; 5106 5107 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags); 5108} 5109#endif // GTEST_OS_WINDOWS 5110 5111// Tests current_test_info() in UnitTest. 5112class CurrentTestInfoTest : public Test { 5113 protected: 5114 // Tests that current_test_info() returns NULL before the first test in 5115 // the test case is run. 5116 static void SetUpTestCase() { 5117 // There should be no tests running at this point. 5118 const TestInfo* test_info = 5119 UnitTest::GetInstance()->current_test_info(); 5120 EXPECT_EQ(NULL, test_info) 5121 << "There should be no tests running at this point."; 5122 } 5123 5124 // Tests that current_test_info() returns NULL after the last test in 5125 // the test case has run. 5126 static void TearDownTestCase() { 5127 const TestInfo* test_info = 5128 UnitTest::GetInstance()->current_test_info(); 5129 EXPECT_EQ(NULL, test_info) 5130 << "There should be no tests running at this point."; 5131 } 5132}; 5133 5134// Tests that current_test_info() returns TestInfo for currently running 5135// test by checking the expected test name against the actual one. 5136TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) { 5137 const TestInfo* test_info = 5138 UnitTest::GetInstance()->current_test_info(); 5139 ASSERT_TRUE(NULL != test_info) 5140 << "There is a test running so we should have a valid TestInfo."; 5141 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) 5142 << "Expected the name of the currently running test case."; 5143 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name()) 5144 << "Expected the name of the currently running test."; 5145} 5146 5147// Tests that current_test_info() returns TestInfo for currently running 5148// test by checking the expected test name against the actual one. We 5149// use this test to see that the TestInfo object actually changed from 5150// the previous invocation. 5151TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) { 5152 const TestInfo* test_info = 5153 UnitTest::GetInstance()->current_test_info(); 5154 ASSERT_TRUE(NULL != test_info) 5155 << "There is a test running so we should have a valid TestInfo."; 5156 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) 5157 << "Expected the name of the currently running test case."; 5158 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name()) 5159 << "Expected the name of the currently running test."; 5160} 5161 5162} // namespace testing 5163 5164// These two lines test that we can define tests in a namespace that 5165// has the name "testing" and is nested in another namespace. 5166namespace my_namespace { 5167namespace testing { 5168 5169// Makes sure that TEST knows to use ::testing::Test instead of 5170// ::my_namespace::testing::Test. 5171class Test {}; 5172 5173// Makes sure that an assertion knows to use ::testing::Message instead of 5174// ::my_namespace::testing::Message. 5175class Message {}; 5176 5177// Makes sure that an assertion knows to use 5178// ::testing::AssertionResult instead of 5179// ::my_namespace::testing::AssertionResult. 5180class AssertionResult {}; 5181 5182// Tests that an assertion that should succeed works as expected. 5183TEST(NestedTestingNamespaceTest, Success) { 5184 EXPECT_EQ(1, 1) << "This shouldn't fail."; 5185} 5186 5187// Tests that an assertion that should fail works as expected. 5188TEST(NestedTestingNamespaceTest, Failure) { 5189 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.", 5190 "This failure is expected."); 5191} 5192 5193} // namespace testing 5194} // namespace my_namespace 5195 5196// Tests that one can call superclass SetUp and TearDown methods-- 5197// that is, that they are not private. 5198// No tests are based on this fixture; the test "passes" if it compiles 5199// successfully. 5200class ProtectedFixtureMethodsTest : public Test { 5201 protected: 5202 virtual void SetUp() { 5203 Test::SetUp(); 5204 } 5205 virtual void TearDown() { 5206 Test::TearDown(); 5207 } 5208}; 5209 5210// StreamingAssertionsTest tests the streaming versions of a representative 5211// sample of assertions. 5212TEST(StreamingAssertionsTest, Unconditional) { 5213 SUCCEED() << "expected success"; 5214 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure", 5215 "expected failure"); 5216 EXPECT_FATAL_FAILURE(FAIL() << "expected failure", 5217 "expected failure"); 5218} 5219 5220TEST(StreamingAssertionsTest, Truth) { 5221 EXPECT_TRUE(true) << "unexpected failure"; 5222 ASSERT_TRUE(true) << "unexpected failure"; 5223 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure", 5224 "expected failure"); 5225 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure", 5226 "expected failure"); 5227} 5228 5229TEST(StreamingAssertionsTest, Truth2) { 5230 EXPECT_FALSE(false) << "unexpected failure"; 5231 ASSERT_FALSE(false) << "unexpected failure"; 5232 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure", 5233 "expected failure"); 5234 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure", 5235 "expected failure"); 5236} 5237 5238TEST(StreamingAssertionsTest, IntegerEquals) { 5239 EXPECT_EQ(1, 1) << "unexpected failure"; 5240 ASSERT_EQ(1, 1) << "unexpected failure"; 5241 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure", 5242 "expected failure"); 5243 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure", 5244 "expected failure"); 5245} 5246 5247TEST(StreamingAssertionsTest, IntegerLessThan) { 5248 EXPECT_LT(1, 2) << "unexpected failure"; 5249 ASSERT_LT(1, 2) << "unexpected failure"; 5250 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure", 5251 "expected failure"); 5252 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure", 5253 "expected failure"); 5254} 5255 5256TEST(StreamingAssertionsTest, StringsEqual) { 5257 EXPECT_STREQ("foo", "foo") << "unexpected failure"; 5258 ASSERT_STREQ("foo", "foo") << "unexpected failure"; 5259 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure", 5260 "expected failure"); 5261 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure", 5262 "expected failure"); 5263} 5264 5265TEST(StreamingAssertionsTest, StringsNotEqual) { 5266 EXPECT_STRNE("foo", "bar") << "unexpected failure"; 5267 ASSERT_STRNE("foo", "bar") << "unexpected failure"; 5268 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure", 5269 "expected failure"); 5270 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure", 5271 "expected failure"); 5272} 5273 5274TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) { 5275 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure"; 5276 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure"; 5277 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure", 5278 "expected failure"); 5279 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure", 5280 "expected failure"); 5281} 5282 5283TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) { 5284 EXPECT_STRCASENE("foo", "bar") << "unexpected failure"; 5285 ASSERT_STRCASENE("foo", "bar") << "unexpected failure"; 5286 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure", 5287 "expected failure"); 5288 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure", 5289 "expected failure"); 5290} 5291 5292TEST(StreamingAssertionsTest, FloatingPointEquals) { 5293 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; 5294 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; 5295 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure", 5296 "expected failure"); 5297 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure", 5298 "expected failure"); 5299} 5300 5301#if GTEST_HAS_EXCEPTIONS 5302 5303TEST(StreamingAssertionsTest, Throw) { 5304 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure"; 5305 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure"; 5306 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) << 5307 "expected failure", "expected failure"); 5308 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) << 5309 "expected failure", "expected failure"); 5310} 5311 5312TEST(StreamingAssertionsTest, NoThrow) { 5313 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure"; 5314 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure"; 5315 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) << 5316 "expected failure", "expected failure"); 5317 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << 5318 "expected failure", "expected failure"); 5319} 5320 5321TEST(StreamingAssertionsTest, AnyThrow) { 5322 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; 5323 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; 5324 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) << 5325 "expected failure", "expected failure"); 5326 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << 5327 "expected failure", "expected failure"); 5328} 5329 5330#endif // GTEST_HAS_EXCEPTIONS 5331 5332// Tests that Google Test correctly decides whether to use colors in the output. 5333 5334TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { 5335 GTEST_FLAG(color) = "yes"; 5336 5337 SetEnv("TERM", "xterm"); // TERM supports colors. 5338 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 5339 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 5340 5341 SetEnv("TERM", "dumb"); // TERM doesn't support colors. 5342 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 5343 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 5344} 5345 5346TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { 5347 SetEnv("TERM", "dumb"); // TERM doesn't support colors. 5348 5349 GTEST_FLAG(color) = "True"; 5350 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 5351 5352 GTEST_FLAG(color) = "t"; 5353 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 5354 5355 GTEST_FLAG(color) = "1"; 5356 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. 5357} 5358 5359TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { 5360 GTEST_FLAG(color) = "no"; 5361 5362 SetEnv("TERM", "xterm"); // TERM supports colors. 5363 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 5364 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. 5365 5366 SetEnv("TERM", "dumb"); // TERM doesn't support colors. 5367 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 5368 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. 5369} 5370 5371TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { 5372 SetEnv("TERM", "xterm"); // TERM supports colors. 5373 5374 GTEST_FLAG(color) = "F"; 5375 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 5376 5377 GTEST_FLAG(color) = "0"; 5378 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 5379 5380 GTEST_FLAG(color) = "unknown"; 5381 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 5382} 5383 5384TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { 5385 GTEST_FLAG(color) = "auto"; 5386 5387 SetEnv("TERM", "xterm"); // TERM supports colors. 5388 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. 5389 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 5390} 5391 5392TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { 5393 GTEST_FLAG(color) = "auto"; 5394 5395#if GTEST_OS_WINDOWS 5396 // On Windows, we ignore the TERM variable as it's usually not set. 5397 5398 SetEnv("TERM", "dumb"); 5399 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 5400 5401 SetEnv("TERM", ""); 5402 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 5403 5404 SetEnv("TERM", "xterm"); 5405 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 5406#else 5407 // On non-Windows platforms, we rely on TERM to determine if the 5408 // terminal supports colors. 5409 5410 SetEnv("TERM", "dumb"); // TERM doesn't support colors. 5411 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 5412 5413 SetEnv("TERM", "emacs"); // TERM doesn't support colors. 5414 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 5415 5416 SetEnv("TERM", "vt100"); // TERM doesn't support colors. 5417 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 5418 5419 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. 5420 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. 5421 5422 SetEnv("TERM", "xterm"); // TERM supports colors. 5423 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 5424 5425 SetEnv("TERM", "xterm-color"); // TERM supports colors. 5426 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. 5427#endif // GTEST_OS_WINDOWS 5428} 5429 5430// Verifies that StaticAssertTypeEq works in a namespace scope. 5431 5432static bool dummy1 = StaticAssertTypeEq<bool, bool>(); 5433static bool dummy2 = StaticAssertTypeEq<const int, const int>(); 5434 5435// Verifies that StaticAssertTypeEq works in a class. 5436 5437template <typename T> 5438class StaticAssertTypeEqTestHelper { 5439 public: 5440 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); } 5441}; 5442 5443TEST(StaticAssertTypeEqTest, WorksInClass) { 5444 StaticAssertTypeEqTestHelper<bool>(); 5445} 5446 5447// Verifies that StaticAssertTypeEq works inside a function. 5448 5449typedef int IntAlias; 5450 5451TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) { 5452 StaticAssertTypeEq<int, IntAlias>(); 5453 StaticAssertTypeEq<int*, IntAlias*>(); 5454} 5455 5456TEST(ThreadLocalTest, DefaultConstructor) { 5457 ThreadLocal<int> t1; 5458 EXPECT_EQ(0, t1.get()); 5459 5460 ThreadLocal<void*> t2; 5461 EXPECT_TRUE(t2.get() == NULL); 5462} 5463 5464TEST(ThreadLocalTest, Init) { 5465 ThreadLocal<int> t1(123); 5466 EXPECT_EQ(123, t1.get()); 5467 5468 int i = 0; 5469 ThreadLocal<int*> t2(&i); 5470 EXPECT_EQ(&i, t2.get()); 5471} 5472 5473TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) { 5474 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance(); 5475 5476 // We don't have a stack walker in Google Test yet. 5477 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str()); 5478 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str()); 5479} 5480