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