yaml-cpp

FORK: A YAML parser and emitter in C++
git clone https://git.neptards.moe/neptards/yaml-cpp.git
Log | Files | Refs | README | LICENSE

gtest_unittest.cc (249846B)


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