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