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