gtest_unittest.cc
Go to the documentation of this file.
00001 // Copyright 2005, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Author: wan@google.com (Zhanyong Wan)
00031 //
00032 // Tests for Google Test itself.  This verifies that the basic constructs of
00033 // Google Test work.
00034 
00035 #include "gtest/gtest.h"
00036 
00037 // Verifies that the command line flag variables can be accessed
00038 // in code once <gtest/gtest.h> has been #included.
00039 // Do not move it after other #includes.
00040 TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
00041   bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
00042       || testing::GTEST_FLAG(break_on_failure)
00043       || testing::GTEST_FLAG(catch_exceptions)
00044       || testing::GTEST_FLAG(color) != "unknown"
00045       || testing::GTEST_FLAG(filter) != "unknown"
00046       || testing::GTEST_FLAG(list_tests)
00047       || testing::GTEST_FLAG(output) != "unknown"
00048       || testing::GTEST_FLAG(print_time)
00049       || testing::GTEST_FLAG(random_seed)
00050       || testing::GTEST_FLAG(repeat) > 0
00051       || testing::GTEST_FLAG(show_internal_stack_frames)
00052       || testing::GTEST_FLAG(shuffle)
00053       || testing::GTEST_FLAG(stack_trace_depth) > 0
00054       || testing::GTEST_FLAG(stream_result_to) != "unknown"
00055       || testing::GTEST_FLAG(throw_on_failure);
00056   EXPECT_TRUE(dummy || !dummy);  // Suppresses warning that dummy is unused.
00057 }
00058 
00059 #include <limits.h>  // For INT_MAX.
00060 #include <stdlib.h>
00061 #include <string.h>
00062 #include <time.h>
00063 
00064 #include <map>
00065 #include <vector>
00066 #include <ostream>
00067 
00068 #include "gtest/gtest-spi.h"
00069 
00070 // Indicates that this translation unit is part of Google Test's
00071 // implementation.  It must come before gtest-internal-inl.h is
00072 // included, or there will be a compiler error.  This trick is to
00073 // prevent a user from accidentally including gtest-internal-inl.h in
00074 // his code.
00075 #define GTEST_IMPLEMENTATION_ 1
00076 #include "src/gtest-internal-inl.h"
00077 #undef GTEST_IMPLEMENTATION_
00078 
00079 namespace testing {
00080 namespace internal {
00081 
00082 #if GTEST_CAN_STREAM_RESULTS_
00083 
00084 class StreamingListenerTest : public Test {
00085  public:
00086   class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
00087    public:
00088     // Sends a string to the socket.
00089     virtual void Send(const string& message) { output_ += message; }
00090 
00091     string output_;
00092   };
00093 
00094   StreamingListenerTest()
00095       : fake_sock_writer_(new FakeSocketWriter),
00096         streamer_(fake_sock_writer_),
00097         test_info_obj_("FooTest", "Bar", NULL, NULL, 0, NULL) {}
00098 
00099  protected:
00100   string* output() { return &(fake_sock_writer_->output_); }
00101 
00102   FakeSocketWriter* const fake_sock_writer_;
00103   StreamingListener streamer_;
00104   UnitTest unit_test_;
00105   TestInfo test_info_obj_;  // The name test_info_ was taken by testing::Test.
00106 };
00107 
00108 TEST_F(StreamingListenerTest, OnTestProgramEnd) {
00109   *output() = "";
00110   streamer_.OnTestProgramEnd(unit_test_);
00111   EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
00112 }
00113 
00114 TEST_F(StreamingListenerTest, OnTestIterationEnd) {
00115   *output() = "";
00116   streamer_.OnTestIterationEnd(unit_test_, 42);
00117   EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
00118 }
00119 
00120 TEST_F(StreamingListenerTest, OnTestCaseStart) {
00121   *output() = "";
00122   streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", NULL, NULL));
00123   EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
00124 }
00125 
00126 TEST_F(StreamingListenerTest, OnTestCaseEnd) {
00127   *output() = "";
00128   streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", NULL, NULL));
00129   EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
00130 }
00131 
00132 TEST_F(StreamingListenerTest, OnTestStart) {
00133   *output() = "";
00134   streamer_.OnTestStart(test_info_obj_);
00135   EXPECT_EQ("event=TestStart&name=Bar\n", *output());
00136 }
00137 
00138 TEST_F(StreamingListenerTest, OnTestEnd) {
00139   *output() = "";
00140   streamer_.OnTestEnd(test_info_obj_);
00141   EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
00142 }
00143 
00144 TEST_F(StreamingListenerTest, OnTestPartResult) {
00145   *output() = "";
00146   streamer_.OnTestPartResult(TestPartResult(
00147       TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
00148 
00149   // Meta characters in the failure message should be properly escaped.
00150   EXPECT_EQ(
00151       "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
00152       *output());
00153 }
00154 
00155 #endif  // GTEST_CAN_STREAM_RESULTS_
00156 
00157 // Provides access to otherwise private parts of the TestEventListeners class
00158 // that are needed to test it.
00159 class TestEventListenersAccessor {
00160  public:
00161   static TestEventListener* GetRepeater(TestEventListeners* listeners) {
00162     return listeners->repeater();
00163   }
00164 
00165   static void SetDefaultResultPrinter(TestEventListeners* listeners,
00166                                       TestEventListener* listener) {
00167     listeners->SetDefaultResultPrinter(listener);
00168   }
00169   static void SetDefaultXmlGenerator(TestEventListeners* listeners,
00170                                      TestEventListener* listener) {
00171     listeners->SetDefaultXmlGenerator(listener);
00172   }
00173 
00174   static bool EventForwardingEnabled(const TestEventListeners& listeners) {
00175     return listeners.EventForwardingEnabled();
00176   }
00177 
00178   static void SuppressEventForwarding(TestEventListeners* listeners) {
00179     listeners->SuppressEventForwarding();
00180   }
00181 };
00182 
00183 class UnitTestRecordPropertyTestHelper : public Test {
00184  protected:
00185   UnitTestRecordPropertyTestHelper() {}
00186 
00187   // Forwards to UnitTest::RecordProperty() to bypass access controls.
00188   void UnitTestRecordProperty(const char* key, const std::string& value) {
00189     unit_test_.RecordProperty(key, value);
00190   }
00191 
00192   UnitTest unit_test_;
00193 };
00194 
00195 }  // namespace internal
00196 }  // namespace testing
00197 
00198 using testing::AssertionFailure;
00199 using testing::AssertionResult;
00200 using testing::AssertionSuccess;
00201 using testing::DoubleLE;
00202 using testing::EmptyTestEventListener;
00203 using testing::Environment;
00204 using testing::FloatLE;
00205 using testing::GTEST_FLAG(also_run_disabled_tests);
00206 using testing::GTEST_FLAG(break_on_failure);
00207 using testing::GTEST_FLAG(catch_exceptions);
00208 using testing::GTEST_FLAG(color);
00209 using testing::GTEST_FLAG(death_test_use_fork);
00210 using testing::GTEST_FLAG(filter);
00211 using testing::GTEST_FLAG(list_tests);
00212 using testing::GTEST_FLAG(output);
00213 using testing::GTEST_FLAG(print_time);
00214 using testing::GTEST_FLAG(random_seed);
00215 using testing::GTEST_FLAG(repeat);
00216 using testing::GTEST_FLAG(show_internal_stack_frames);
00217 using testing::GTEST_FLAG(shuffle);
00218 using testing::GTEST_FLAG(stack_trace_depth);
00219 using testing::GTEST_FLAG(stream_result_to);
00220 using testing::GTEST_FLAG(throw_on_failure);
00221 using testing::IsNotSubstring;
00222 using testing::IsSubstring;
00223 using testing::Message;
00224 using testing::ScopedFakeTestPartResultReporter;
00225 using testing::StaticAssertTypeEq;
00226 using testing::Test;
00227 using testing::TestCase;
00228 using testing::TestEventListeners;
00229 using testing::TestInfo;
00230 using testing::TestPartResult;
00231 using testing::TestPartResultArray;
00232 using testing::TestProperty;
00233 using testing::TestResult;
00234 using testing::TimeInMillis;
00235 using testing::UnitTest;
00236 using testing::kMaxStackTraceDepth;
00237 using testing::internal::AddReference;
00238 using testing::internal::AlwaysFalse;
00239 using testing::internal::AlwaysTrue;
00240 using testing::internal::AppendUserMessage;
00241 using testing::internal::ArrayAwareFind;
00242 using testing::internal::ArrayEq;
00243 using testing::internal::CodePointToUtf8;
00244 using testing::internal::CompileAssertTypesEqual;
00245 using testing::internal::CopyArray;
00246 using testing::internal::CountIf;
00247 using testing::internal::EqFailure;
00248 using testing::internal::FloatingPoint;
00249 using testing::internal::ForEach;
00250 using testing::internal::FormatEpochTimeInMillisAsIso8601;
00251 using testing::internal::FormatTimeInMillisAsSeconds;
00252 using testing::internal::GTestFlagSaver;
00253 using testing::internal::GetCurrentOsStackTraceExceptTop;
00254 using testing::internal::GetElementOr;
00255 using testing::internal::GetNextRandomSeed;
00256 using testing::internal::GetRandomSeedFromFlag;
00257 using testing::internal::GetTestTypeId;
00258 using testing::internal::GetTimeInMillis;
00259 using testing::internal::GetTypeId;
00260 using testing::internal::GetUnitTestImpl;
00261 using testing::internal::ImplicitlyConvertible;
00262 using testing::internal::Int32;
00263 using testing::internal::Int32FromEnvOrDie;
00264 using testing::internal::IsAProtocolMessage;
00265 using testing::internal::IsContainer;
00266 using testing::internal::IsContainerTest;
00267 using testing::internal::IsNotContainer;
00268 using testing::internal::NativeArray;
00269 using testing::internal::ParseInt32Flag;
00270 using testing::internal::RemoveConst;
00271 using testing::internal::RemoveReference;
00272 using testing::internal::ShouldRunTestOnShard;
00273 using testing::internal::ShouldShard;
00274 using testing::internal::ShouldUseColor;
00275 using testing::internal::Shuffle;
00276 using testing::internal::ShuffleRange;
00277 using testing::internal::SkipPrefix;
00278 using testing::internal::StreamableToString;
00279 using testing::internal::String;
00280 using testing::internal::TestEventListenersAccessor;
00281 using testing::internal::TestResultAccessor;
00282 using testing::internal::UInt32;
00283 using testing::internal::WideStringToUtf8;
00284 using testing::internal::kCopy;
00285 using testing::internal::kMaxRandomSeed;
00286 using testing::internal::kReference;
00287 using testing::internal::kTestTypeIdInGoogleTest;
00288 using testing::internal::scoped_ptr;
00289 
00290 #if GTEST_HAS_STREAM_REDIRECTION
00291 using testing::internal::CaptureStdout;
00292 using testing::internal::GetCapturedStdout;
00293 #endif
00294 
00295 #if GTEST_IS_THREADSAFE
00296 using testing::internal::ThreadWithParam;
00297 #endif
00298 
00299 class TestingVector : public std::vector<int> {
00300 };
00301 
00302 ::std::ostream& operator<<(::std::ostream& os,
00303                            const TestingVector& vector) {
00304   os << "{ ";
00305   for (size_t i = 0; i < vector.size(); i++) {
00306     os << vector[i] << " ";
00307   }
00308   os << "}";
00309   return os;
00310 }
00311 
00312 // This line tests that we can define tests in an unnamed namespace.
00313 namespace {
00314 
00315 TEST(GetRandomSeedFromFlagTest, HandlesZero) {
00316   const int seed = GetRandomSeedFromFlag(0);
00317   EXPECT_LE(1, seed);
00318   EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
00319 }
00320 
00321 TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
00322   EXPECT_EQ(1, GetRandomSeedFromFlag(1));
00323   EXPECT_EQ(2, GetRandomSeedFromFlag(2));
00324   EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
00325   EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
00326             GetRandomSeedFromFlag(kMaxRandomSeed));
00327 }
00328 
00329 TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
00330   const int seed1 = GetRandomSeedFromFlag(-1);
00331   EXPECT_LE(1, seed1);
00332   EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
00333 
00334   const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
00335   EXPECT_LE(1, seed2);
00336   EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
00337 }
00338 
00339 TEST(GetNextRandomSeedTest, WorksForValidInput) {
00340   EXPECT_EQ(2, GetNextRandomSeed(1));
00341   EXPECT_EQ(3, GetNextRandomSeed(2));
00342   EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
00343             GetNextRandomSeed(kMaxRandomSeed - 1));
00344   EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
00345 
00346   // We deliberately don't test GetNextRandomSeed() with invalid
00347   // inputs, as that requires death tests, which are expensive.  This
00348   // is fine as GetNextRandomSeed() is internal and has a
00349   // straightforward definition.
00350 }
00351 
00352 static void ClearCurrentTestPartResults() {
00353   TestResultAccessor::ClearTestPartResults(
00354       GetUnitTestImpl()->current_test_result());
00355 }
00356 
00357 // Tests GetTypeId.
00358 
00359 TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
00360   EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
00361   EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
00362 }
00363 
00364 class SubClassOfTest : public Test {};
00365 class AnotherSubClassOfTest : public Test {};
00366 
00367 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
00368   EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
00369   EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
00370   EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
00371   EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
00372   EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
00373   EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
00374 }
00375 
00376 // Verifies that GetTestTypeId() returns the same value, no matter it
00377 // is called from inside Google Test or outside of it.
00378 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
00379   EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
00380 }
00381 
00382 // Tests FormatTimeInMillisAsSeconds().
00383 
00384 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
00385   EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
00386 }
00387 
00388 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
00389   EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
00390   EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
00391   EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
00392   EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
00393   EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
00394 }
00395 
00396 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
00397   EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
00398   EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
00399   EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
00400   EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
00401   EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
00402 }
00403 
00404 // Tests FormatEpochTimeInMillisAsIso8601().  The correctness of conversion
00405 // for particular dates below was verified in Python using
00406 // datetime.datetime.fromutctimestamp(<timetamp>/1000).
00407 
00408 // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
00409 // have to set up a particular timezone to obtain predictable results.
00410 class FormatEpochTimeInMillisAsIso8601Test : public Test {
00411  public:
00412   // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
00413   // 32 bits, even when 64-bit integer types are available.  We have to
00414   // force the constants to have a 64-bit type here.
00415   static const TimeInMillis kMillisPerSec = 1000;
00416 
00417  private:
00418   virtual void SetUp() {
00419     saved_tz_ = NULL;
00420 #if _MSC_VER
00421 # pragma warning(push)          // Saves the current warning state.
00422 # pragma warning(disable:4996)  // Temporarily disables warning 4996
00423                                 // (function or variable may be unsafe
00424                                 // for getenv, function is deprecated for
00425                                 // strdup).
00426     if (getenv("TZ"))
00427       saved_tz_ = strdup(getenv("TZ"));
00428 # pragma warning(pop)           // Restores the warning state again.
00429 #else
00430     if (getenv("TZ"))
00431       saved_tz_ = strdup(getenv("TZ"));
00432 #endif
00433 
00434     // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use.  We
00435     // cannot use the local time zone because the function's output depends
00436     // on the time zone.
00437     SetTimeZone("UTC+00");
00438   }
00439 
00440   virtual void TearDown() {
00441     SetTimeZone(saved_tz_);
00442     free(const_cast<char*>(saved_tz_));
00443     saved_tz_ = NULL;
00444   }
00445 
00446   static void SetTimeZone(const char* time_zone) {
00447     // tzset() distinguishes between the TZ variable being present and empty
00448     // and not being present, so we have to consider the case of time_zone
00449     // being NULL.
00450 #if _MSC_VER
00451     // ...Unless it's MSVC, whose standard library's _putenv doesn't
00452     // distinguish between an empty and a missing variable.
00453     const std::string env_var =
00454         std::string("TZ=") + (time_zone ? time_zone : "");
00455     _putenv(env_var.c_str());
00456 # pragma warning(push)          // Saves the current warning state.
00457 # pragma warning(disable:4996)  // Temporarily disables warning 4996
00458                                 // (function is deprecated).
00459     tzset();
00460 # pragma warning(pop)           // Restores the warning state again.
00461 #else
00462     if (time_zone) {
00463       setenv(("TZ"), time_zone, 1);
00464     } else {
00465       unsetenv("TZ");
00466     }
00467     tzset();
00468 #endif
00469   }
00470 
00471   const char* saved_tz_;
00472 };
00473 
00474 const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
00475 
00476 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
00477   EXPECT_EQ("2011-10-31T18:52:42",
00478             FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
00479 }
00480 
00481 TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
00482   EXPECT_EQ(
00483       "2011-10-31T18:52:42",
00484       FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
00485 }
00486 
00487 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
00488   EXPECT_EQ("2011-09-03T05:07:02",
00489             FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
00490 }
00491 
00492 TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
00493   EXPECT_EQ("2011-09-28T17:08:22",
00494             FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
00495 }
00496 
00497 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
00498   EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
00499 }
00500 
00501 #if GTEST_CAN_COMPARE_NULL
00502 
00503 # ifdef __BORLANDC__
00504 // Silences warnings: "Condition is always true", "Unreachable code"
00505 #  pragma option push -w-ccc -w-rch
00506 # endif
00507 
00508 // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
00509 // pointer literal.
00510 TEST(NullLiteralTest, IsTrueForNullLiterals) {
00511   EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
00512   EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
00513   EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
00514   EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
00515 }
00516 
00517 // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
00518 // pointer literal.
00519 TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
00520   EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
00521   EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
00522   EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
00523   EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
00524 }
00525 
00526 # ifdef __BORLANDC__
00527 // Restores warnings after previous "#pragma option push" suppressed them.
00528 #  pragma option pop
00529 # endif
00530 
00531 #endif  // GTEST_CAN_COMPARE_NULL
00532 //
00533 // Tests CodePointToUtf8().
00534 
00535 // Tests that the NUL character L'\0' is encoded correctly.
00536 TEST(CodePointToUtf8Test, CanEncodeNul) {
00537   EXPECT_EQ("", CodePointToUtf8(L'\0'));
00538 }
00539 
00540 // Tests that ASCII characters are encoded correctly.
00541 TEST(CodePointToUtf8Test, CanEncodeAscii) {
00542   EXPECT_EQ("a", CodePointToUtf8(L'a'));
00543   EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
00544   EXPECT_EQ("&", CodePointToUtf8(L'&'));
00545   EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
00546 }
00547 
00548 // Tests that Unicode code-points that have 8 to 11 bits are encoded
00549 // as 110xxxxx 10xxxxxx.
00550 TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
00551   // 000 1101 0011 => 110-00011 10-010011
00552   EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
00553 
00554   // 101 0111 0110 => 110-10101 10-110110
00555   // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
00556   // in wide strings and wide chars. In order to accomodate them, we have to
00557   // introduce such character constants as integers.
00558   EXPECT_EQ("\xD5\xB6",
00559             CodePointToUtf8(static_cast<wchar_t>(0x576)));
00560 }
00561 
00562 // Tests that Unicode code-points that have 12 to 16 bits are encoded
00563 // as 1110xxxx 10xxxxxx 10xxxxxx.
00564 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
00565   // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
00566   EXPECT_EQ("\xE0\xA3\x93",
00567             CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
00568 
00569   // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
00570   EXPECT_EQ("\xEC\x9D\x8D",
00571             CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
00572 }
00573 
00574 #if !GTEST_WIDE_STRING_USES_UTF16_
00575 // Tests in this group require a wchar_t to hold > 16 bits, and thus
00576 // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
00577 // 16-bit wide. This code may not compile on those systems.
00578 
00579 // Tests that Unicode code-points that have 17 to 21 bits are encoded
00580 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
00581 TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
00582   // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
00583   EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
00584 
00585   // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
00586   EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
00587 
00588   // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
00589   EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
00590 }
00591 
00592 // Tests that encoding an invalid code-point generates the expected result.
00593 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
00594   EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
00595 }
00596 
00597 #endif  // !GTEST_WIDE_STRING_USES_UTF16_
00598 
00599 // Tests WideStringToUtf8().
00600 
00601 // Tests that the NUL character L'\0' is encoded correctly.
00602 TEST(WideStringToUtf8Test, CanEncodeNul) {
00603   EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
00604   EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
00605 }
00606 
00607 // Tests that ASCII strings are encoded correctly.
00608 TEST(WideStringToUtf8Test, CanEncodeAscii) {
00609   EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
00610   EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
00611   EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
00612   EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
00613 }
00614 
00615 // Tests that Unicode code-points that have 8 to 11 bits are encoded
00616 // as 110xxxxx 10xxxxxx.
00617 TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
00618   // 000 1101 0011 => 110-00011 10-010011
00619   EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
00620   EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
00621 
00622   // 101 0111 0110 => 110-10101 10-110110
00623   const wchar_t s[] = { 0x576, '\0' };
00624   EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
00625   EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
00626 }
00627 
00628 // Tests that Unicode code-points that have 12 to 16 bits are encoded
00629 // as 1110xxxx 10xxxxxx 10xxxxxx.
00630 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
00631   // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
00632   const wchar_t s1[] = { 0x8D3, '\0' };
00633   EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
00634   EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
00635 
00636   // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
00637   const wchar_t s2[] = { 0xC74D, '\0' };
00638   EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
00639   EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
00640 }
00641 
00642 // Tests that the conversion stops when the function encounters \0 character.
00643 TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
00644   EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
00645 }
00646 
00647 // Tests that the conversion stops when the function reaches the limit
00648 // specified by the 'length' parameter.
00649 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
00650   EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
00651 }
00652 
00653 #if !GTEST_WIDE_STRING_USES_UTF16_
00654 // Tests that Unicode code-points that have 17 to 21 bits are encoded
00655 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
00656 // on the systems using UTF-16 encoding.
00657 TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
00658   // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
00659   EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
00660   EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
00661 
00662   // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
00663   EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
00664   EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
00665 }
00666 
00667 // Tests that encoding an invalid code-point generates the expected result.
00668 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
00669   EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
00670                WideStringToUtf8(L"\xABCDFF", -1).c_str());
00671 }
00672 #else  // !GTEST_WIDE_STRING_USES_UTF16_
00673 // Tests that surrogate pairs are encoded correctly on the systems using
00674 // UTF-16 encoding in the wide strings.
00675 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
00676   const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
00677   EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
00678 }
00679 
00680 // Tests that encoding an invalid UTF-16 surrogate pair
00681 // generates the expected result.
00682 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
00683   // Leading surrogate is at the end of the string.
00684   const wchar_t s1[] = { 0xD800, '\0' };
00685   EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
00686   // Leading surrogate is not followed by the trailing surrogate.
00687   const wchar_t s2[] = { 0xD800, 'M', '\0' };
00688   EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
00689   // Trailing surrogate appearas without a leading surrogate.
00690   const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
00691   EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
00692 }
00693 #endif  // !GTEST_WIDE_STRING_USES_UTF16_
00694 
00695 // Tests that codepoint concatenation works correctly.
00696 #if !GTEST_WIDE_STRING_USES_UTF16_
00697 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
00698   const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
00699   EXPECT_STREQ(
00700       "\xF4\x88\x98\xB4"
00701           "\xEC\x9D\x8D"
00702           "\n"
00703           "\xD5\xB6"
00704           "\xE0\xA3\x93"
00705           "\xF4\x88\x98\xB4",
00706       WideStringToUtf8(s, -1).c_str());
00707 }
00708 #else
00709 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
00710   const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
00711   EXPECT_STREQ(
00712       "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
00713       WideStringToUtf8(s, -1).c_str());
00714 }
00715 #endif  // !GTEST_WIDE_STRING_USES_UTF16_
00716 
00717 // Tests the Random class.
00718 
00719 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
00720   testing::internal::Random random(42);
00721   EXPECT_DEATH_IF_SUPPORTED(
00722       random.Generate(0),
00723       "Cannot generate a number in the range \\[0, 0\\)");
00724   EXPECT_DEATH_IF_SUPPORTED(
00725       random.Generate(testing::internal::Random::kMaxRange + 1),
00726       "Generation of a number in \\[0, 2147483649\\) was requested, "
00727       "but this can only generate numbers in \\[0, 2147483648\\)");
00728 }
00729 
00730 TEST(RandomTest, GeneratesNumbersWithinRange) {
00731   const UInt32 kRange = 10000;
00732   testing::internal::Random random(12345);
00733   for (int i = 0; i < 10; i++) {
00734     EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
00735   }
00736 
00737   testing::internal::Random random2(testing::internal::Random::kMaxRange);
00738   for (int i = 0; i < 10; i++) {
00739     EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
00740   }
00741 }
00742 
00743 TEST(RandomTest, RepeatsWhenReseeded) {
00744   const int kSeed = 123;
00745   const int kArraySize = 10;
00746   const UInt32 kRange = 10000;
00747   UInt32 values[kArraySize];
00748 
00749   testing::internal::Random random(kSeed);
00750   for (int i = 0; i < kArraySize; i++) {
00751     values[i] = random.Generate(kRange);
00752   }
00753 
00754   random.Reseed(kSeed);
00755   for (int i = 0; i < kArraySize; i++) {
00756     EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
00757   }
00758 }
00759 
00760 // Tests STL container utilities.
00761 
00762 // Tests CountIf().
00763 
00764 static bool IsPositive(int n) { return n > 0; }
00765 
00766 TEST(ContainerUtilityTest, CountIf) {
00767   std::vector<int> v;
00768   EXPECT_EQ(0, CountIf(v, IsPositive));  // Works for an empty container.
00769 
00770   v.push_back(-1);
00771   v.push_back(0);
00772   EXPECT_EQ(0, CountIf(v, IsPositive));  // Works when no value satisfies.
00773 
00774   v.push_back(2);
00775   v.push_back(-10);
00776   v.push_back(10);
00777   EXPECT_EQ(2, CountIf(v, IsPositive));
00778 }
00779 
00780 // Tests ForEach().
00781 
00782 static int g_sum = 0;
00783 static void Accumulate(int n) { g_sum += n; }
00784 
00785 TEST(ContainerUtilityTest, ForEach) {
00786   std::vector<int> v;
00787   g_sum = 0;
00788   ForEach(v, Accumulate);
00789   EXPECT_EQ(0, g_sum);  // Works for an empty container;
00790 
00791   g_sum = 0;
00792   v.push_back(1);
00793   ForEach(v, Accumulate);
00794   EXPECT_EQ(1, g_sum);  // Works for a container with one element.
00795 
00796   g_sum = 0;
00797   v.push_back(20);
00798   v.push_back(300);
00799   ForEach(v, Accumulate);
00800   EXPECT_EQ(321, g_sum);
00801 }
00802 
00803 // Tests GetElementOr().
00804 TEST(ContainerUtilityTest, GetElementOr) {
00805   std::vector<char> a;
00806   EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
00807 
00808   a.push_back('a');
00809   a.push_back('b');
00810   EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
00811   EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
00812   EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
00813   EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
00814 }
00815 
00816 TEST(ContainerUtilityDeathTest, ShuffleRange) {
00817   std::vector<int> a;
00818   a.push_back(0);
00819   a.push_back(1);
00820   a.push_back(2);
00821   testing::internal::Random random(1);
00822 
00823   EXPECT_DEATH_IF_SUPPORTED(
00824       ShuffleRange(&random, -1, 1, &a),
00825       "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
00826   EXPECT_DEATH_IF_SUPPORTED(
00827       ShuffleRange(&random, 4, 4, &a),
00828       "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
00829   EXPECT_DEATH_IF_SUPPORTED(
00830       ShuffleRange(&random, 3, 2, &a),
00831       "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
00832   EXPECT_DEATH_IF_SUPPORTED(
00833       ShuffleRange(&random, 3, 4, &a),
00834       "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
00835 }
00836 
00837 class VectorShuffleTest : public Test {
00838  protected:
00839   static const int kVectorSize = 20;
00840 
00841   VectorShuffleTest() : random_(1) {
00842     for (int i = 0; i < kVectorSize; i++) {
00843       vector_.push_back(i);
00844     }
00845   }
00846 
00847   static bool VectorIsCorrupt(const TestingVector& vector) {
00848     if (kVectorSize != static_cast<int>(vector.size())) {
00849       return true;
00850     }
00851 
00852     bool found_in_vector[kVectorSize] = { false };
00853     for (size_t i = 0; i < vector.size(); i++) {
00854       const int e = vector[i];
00855       if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
00856         return true;
00857       }
00858       found_in_vector[e] = true;
00859     }
00860 
00861     // Vector size is correct, elements' range is correct, no
00862     // duplicate elements.  Therefore no corruption has occurred.
00863     return false;
00864   }
00865 
00866   static bool VectorIsNotCorrupt(const TestingVector& vector) {
00867     return !VectorIsCorrupt(vector);
00868   }
00869 
00870   static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
00871     for (int i = begin; i < end; i++) {
00872       if (i != vector[i]) {
00873         return true;
00874       }
00875     }
00876     return false;
00877   }
00878 
00879   static bool RangeIsUnshuffled(
00880       const TestingVector& vector, int begin, int end) {
00881     return !RangeIsShuffled(vector, begin, end);
00882   }
00883 
00884   static bool VectorIsShuffled(const TestingVector& vector) {
00885     return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
00886   }
00887 
00888   static bool VectorIsUnshuffled(const TestingVector& vector) {
00889     return !VectorIsShuffled(vector);
00890   }
00891 
00892   testing::internal::Random random_;
00893   TestingVector vector_;
00894 };  // class VectorShuffleTest
00895 
00896 const int VectorShuffleTest::kVectorSize;
00897 
00898 TEST_F(VectorShuffleTest, HandlesEmptyRange) {
00899   // Tests an empty range at the beginning...
00900   ShuffleRange(&random_, 0, 0, &vector_);
00901   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00902   ASSERT_PRED1(VectorIsUnshuffled, vector_);
00903 
00904   // ...in the middle...
00905   ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
00906   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00907   ASSERT_PRED1(VectorIsUnshuffled, vector_);
00908 
00909   // ...at the end...
00910   ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
00911   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00912   ASSERT_PRED1(VectorIsUnshuffled, vector_);
00913 
00914   // ...and past the end.
00915   ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
00916   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00917   ASSERT_PRED1(VectorIsUnshuffled, vector_);
00918 }
00919 
00920 TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
00921   // Tests a size one range at the beginning...
00922   ShuffleRange(&random_, 0, 1, &vector_);
00923   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00924   ASSERT_PRED1(VectorIsUnshuffled, vector_);
00925 
00926   // ...in the middle...
00927   ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
00928   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00929   ASSERT_PRED1(VectorIsUnshuffled, vector_);
00930 
00931   // ...and at the end.
00932   ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
00933   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00934   ASSERT_PRED1(VectorIsUnshuffled, vector_);
00935 }
00936 
00937 // Because we use our own random number generator and a fixed seed,
00938 // we can guarantee that the following "random" tests will succeed.
00939 
00940 TEST_F(VectorShuffleTest, ShufflesEntireVector) {
00941   Shuffle(&random_, &vector_);
00942   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00943   EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
00944 
00945   // Tests the first and last elements in particular to ensure that
00946   // there are no off-by-one problems in our shuffle algorithm.
00947   EXPECT_NE(0, vector_[0]);
00948   EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
00949 }
00950 
00951 TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
00952   const int kRangeSize = kVectorSize/2;
00953 
00954   ShuffleRange(&random_, 0, kRangeSize, &vector_);
00955 
00956   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00957   EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
00958   EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
00959 }
00960 
00961 TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
00962   const int kRangeSize = kVectorSize / 2;
00963   ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
00964 
00965   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00966   EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
00967   EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
00968 }
00969 
00970 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
00971   int kRangeSize = kVectorSize/3;
00972   ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
00973 
00974   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00975   EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
00976   EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
00977   EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
00978 }
00979 
00980 TEST_F(VectorShuffleTest, ShufflesRepeatably) {
00981   TestingVector vector2;
00982   for (int i = 0; i < kVectorSize; i++) {
00983     vector2.push_back(i);
00984   }
00985 
00986   random_.Reseed(1234);
00987   Shuffle(&random_, &vector_);
00988   random_.Reseed(1234);
00989   Shuffle(&random_, &vector2);
00990 
00991   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
00992   ASSERT_PRED1(VectorIsNotCorrupt, vector2);
00993 
00994   for (int i = 0; i < kVectorSize; i++) {
00995     EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
00996   }
00997 }
00998 
00999 // Tests the size of the AssertHelper class.
01000 
01001 TEST(AssertHelperTest, AssertHelperIsSmall) {
01002   // To avoid breaking clients that use lots of assertions in one
01003   // function, we cannot grow the size of AssertHelper.
01004   EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
01005 }
01006 
01007 // Tests String::EndsWithCaseInsensitive().
01008 TEST(StringTest, EndsWithCaseInsensitive) {
01009   EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
01010   EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
01011   EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
01012   EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
01013 
01014   EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
01015   EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
01016   EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
01017 }
01018 
01019 // C++Builder's preprocessor is buggy; it fails to expand macros that
01020 // appear in macro parameters after wide char literals.  Provide an alias
01021 // for NULL as a workaround.
01022 static const wchar_t* const kNull = NULL;
01023 
01024 // Tests String::CaseInsensitiveWideCStringEquals
01025 TEST(StringTest, CaseInsensitiveWideCStringEquals) {
01026   EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
01027   EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
01028   EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
01029   EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
01030   EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
01031   EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
01032   EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
01033   EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
01034 }
01035 
01036 #if GTEST_OS_WINDOWS
01037 
01038 // Tests String::ShowWideCString().
01039 TEST(StringTest, ShowWideCString) {
01040   EXPECT_STREQ("(null)",
01041                String::ShowWideCString(NULL).c_str());
01042   EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
01043   EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
01044 }
01045 
01046 # if GTEST_OS_WINDOWS_MOBILE
01047 TEST(StringTest, AnsiAndUtf16Null) {
01048   EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
01049   EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
01050 }
01051 
01052 TEST(StringTest, AnsiAndUtf16ConvertBasic) {
01053   const char* ansi = String::Utf16ToAnsi(L"str");
01054   EXPECT_STREQ("str", ansi);
01055   delete [] ansi;
01056   const WCHAR* utf16 = String::AnsiToUtf16("str");
01057   EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
01058   delete [] utf16;
01059 }
01060 
01061 TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
01062   const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
01063   EXPECT_STREQ(".:\\ \"*?", ansi);
01064   delete [] ansi;
01065   const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
01066   EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
01067   delete [] utf16;
01068 }
01069 # endif  // GTEST_OS_WINDOWS_MOBILE
01070 
01071 #endif  // GTEST_OS_WINDOWS
01072 
01073 // Tests TestProperty construction.
01074 TEST(TestPropertyTest, StringValue) {
01075   TestProperty property("key", "1");
01076   EXPECT_STREQ("key", property.key());
01077   EXPECT_STREQ("1", property.value());
01078 }
01079 
01080 // Tests TestProperty replacing a value.
01081 TEST(TestPropertyTest, ReplaceStringValue) {
01082   TestProperty property("key", "1");
01083   EXPECT_STREQ("1", property.value());
01084   property.SetValue("2");
01085   EXPECT_STREQ("2", property.value());
01086 }
01087 
01088 // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
01089 // functions (i.e. their definitions cannot be inlined at the call
01090 // sites), or C++Builder won't compile the code.
01091 static void AddFatalFailure() {
01092   FAIL() << "Expected fatal failure.";
01093 }
01094 
01095 static void AddNonfatalFailure() {
01096   ADD_FAILURE() << "Expected non-fatal failure.";
01097 }
01098 
01099 class ScopedFakeTestPartResultReporterTest : public Test {
01100  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
01101   enum FailureMode {
01102     FATAL_FAILURE,
01103     NONFATAL_FAILURE
01104   };
01105   static void AddFailure(FailureMode failure) {
01106     if (failure == FATAL_FAILURE) {
01107       AddFatalFailure();
01108     } else {
01109       AddNonfatalFailure();
01110     }
01111   }
01112 };
01113 
01114 // Tests that ScopedFakeTestPartResultReporter intercepts test
01115 // failures.
01116 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
01117   TestPartResultArray results;
01118   {
01119     ScopedFakeTestPartResultReporter reporter(
01120         ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
01121         &results);
01122     AddFailure(NONFATAL_FAILURE);
01123     AddFailure(FATAL_FAILURE);
01124   }
01125 
01126   EXPECT_EQ(2, results.size());
01127   EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
01128   EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
01129 }
01130 
01131 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
01132   TestPartResultArray results;
01133   {
01134     // Tests, that the deprecated constructor still works.
01135     ScopedFakeTestPartResultReporter reporter(&results);
01136     AddFailure(NONFATAL_FAILURE);
01137   }
01138   EXPECT_EQ(1, results.size());
01139 }
01140 
01141 #if GTEST_IS_THREADSAFE
01142 
01143 class ScopedFakeTestPartResultReporterWithThreadsTest
01144   : public ScopedFakeTestPartResultReporterTest {
01145  protected:
01146   static void AddFailureInOtherThread(FailureMode failure) {
01147     ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
01148     thread.Join();
01149   }
01150 };
01151 
01152 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
01153        InterceptsTestFailuresInAllThreads) {
01154   TestPartResultArray results;
01155   {
01156     ScopedFakeTestPartResultReporter reporter(
01157         ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
01158     AddFailure(NONFATAL_FAILURE);
01159     AddFailure(FATAL_FAILURE);
01160     AddFailureInOtherThread(NONFATAL_FAILURE);
01161     AddFailureInOtherThread(FATAL_FAILURE);
01162   }
01163 
01164   EXPECT_EQ(4, results.size());
01165   EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
01166   EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
01167   EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
01168   EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
01169 }
01170 
01171 #endif  // GTEST_IS_THREADSAFE
01172 
01173 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}.  Makes sure that they
01174 // work even if the failure is generated in a called function rather than
01175 // the current context.
01176 
01177 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
01178 
01179 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
01180   EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
01181 }
01182 
01183 #if GTEST_HAS_GLOBAL_STRING
01184 TEST_F(ExpectFatalFailureTest, AcceptsStringObject) {
01185   EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure."));
01186 }
01187 #endif
01188 
01189 TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
01190   EXPECT_FATAL_FAILURE(AddFatalFailure(),
01191                        ::std::string("Expected fatal failure."));
01192 }
01193 
01194 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
01195   // We have another test below to verify that the macro catches fatal
01196   // failures generated on another thread.
01197   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
01198                                       "Expected fatal failure.");
01199 }
01200 
01201 #ifdef __BORLANDC__
01202 // Silences warnings: "Condition is always true"
01203 # pragma option push -w-ccc
01204 #endif
01205 
01206 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
01207 // function even when the statement in it contains ASSERT_*.
01208 
01209 int NonVoidFunction() {
01210   EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
01211   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
01212   return 0;
01213 }
01214 
01215 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
01216   NonVoidFunction();
01217 }
01218 
01219 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
01220 // current function even though 'statement' generates a fatal failure.
01221 
01222 void DoesNotAbortHelper(bool* aborted) {
01223   EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
01224   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
01225 
01226   *aborted = false;
01227 }
01228 
01229 #ifdef __BORLANDC__
01230 // Restores warnings after previous "#pragma option push" suppressed them.
01231 # pragma option pop
01232 #endif
01233 
01234 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
01235   bool aborted = true;
01236   DoesNotAbortHelper(&aborted);
01237   EXPECT_FALSE(aborted);
01238 }
01239 
01240 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
01241 // statement that contains a macro which expands to code containing an
01242 // unprotected comma.
01243 
01244 static int global_var = 0;
01245 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
01246 
01247 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
01248 #ifndef __BORLANDC__
01249   // ICE's in C++Builder.
01250   EXPECT_FATAL_FAILURE({
01251     GTEST_USE_UNPROTECTED_COMMA_;
01252     AddFatalFailure();
01253   }, "");
01254 #endif
01255 
01256   EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
01257     GTEST_USE_UNPROTECTED_COMMA_;
01258     AddFatalFailure();
01259   }, "");
01260 }
01261 
01262 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
01263 
01264 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
01265 
01266 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
01267   EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
01268                           "Expected non-fatal failure.");
01269 }
01270 
01271 #if GTEST_HAS_GLOBAL_STRING
01272 TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) {
01273   EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
01274                           ::string("Expected non-fatal failure."));
01275 }
01276 #endif
01277 
01278 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
01279   EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
01280                           ::std::string("Expected non-fatal failure."));
01281 }
01282 
01283 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
01284   // We have another test below to verify that the macro catches
01285   // non-fatal failures generated on another thread.
01286   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
01287                                          "Expected non-fatal failure.");
01288 }
01289 
01290 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
01291 // statement that contains a macro which expands to code containing an
01292 // unprotected comma.
01293 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
01294   EXPECT_NONFATAL_FAILURE({
01295     GTEST_USE_UNPROTECTED_COMMA_;
01296     AddNonfatalFailure();
01297   }, "");
01298 
01299   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
01300     GTEST_USE_UNPROTECTED_COMMA_;
01301     AddNonfatalFailure();
01302   }, "");
01303 }
01304 
01305 #if GTEST_IS_THREADSAFE
01306 
01307 typedef ScopedFakeTestPartResultReporterWithThreadsTest
01308     ExpectFailureWithThreadsTest;
01309 
01310 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
01311   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
01312                                       "Expected fatal failure.");
01313 }
01314 
01315 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
01316   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
01317       AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
01318 }
01319 
01320 #endif  // GTEST_IS_THREADSAFE
01321 
01322 // Tests the TestProperty class.
01323 
01324 TEST(TestPropertyTest, ConstructorWorks) {
01325   const TestProperty property("key", "value");
01326   EXPECT_STREQ("key", property.key());
01327   EXPECT_STREQ("value", property.value());
01328 }
01329 
01330 TEST(TestPropertyTest, SetValue) {
01331   TestProperty property("key", "value_1");
01332   EXPECT_STREQ("key", property.key());
01333   property.SetValue("value_2");
01334   EXPECT_STREQ("key", property.key());
01335   EXPECT_STREQ("value_2", property.value());
01336 }
01337 
01338 // Tests the TestResult class
01339 
01340 // The test fixture for testing TestResult.
01341 class TestResultTest : public Test {
01342  protected:
01343   typedef std::vector<TestPartResult> TPRVector;
01344 
01345   // We make use of 2 TestPartResult objects,
01346   TestPartResult * pr1, * pr2;
01347 
01348   // ... and 3 TestResult objects.
01349   TestResult * r0, * r1, * r2;
01350 
01351   virtual void SetUp() {
01352     // pr1 is for success.
01353     pr1 = new TestPartResult(TestPartResult::kSuccess,
01354                              "foo/bar.cc",
01355                              10,
01356                              "Success!");
01357 
01358     // pr2 is for fatal failure.
01359     pr2 = new TestPartResult(TestPartResult::kFatalFailure,
01360                              "foo/bar.cc",
01361                              -1,  // This line number means "unknown"
01362                              "Failure!");
01363 
01364     // Creates the TestResult objects.
01365     r0 = new TestResult();
01366     r1 = new TestResult();
01367     r2 = new TestResult();
01368 
01369     // In order to test TestResult, we need to modify its internal
01370     // state, in particular the TestPartResult vector it holds.
01371     // test_part_results() returns a const reference to this vector.
01372     // We cast it to a non-const object s.t. it can be modified (yes,
01373     // this is a hack).
01374     TPRVector* results1 = const_cast<TPRVector*>(
01375         &TestResultAccessor::test_part_results(*r1));
01376     TPRVector* results2 = const_cast<TPRVector*>(
01377         &TestResultAccessor::test_part_results(*r2));
01378 
01379     // r0 is an empty TestResult.
01380 
01381     // r1 contains a single SUCCESS TestPartResult.
01382     results1->push_back(*pr1);
01383 
01384     // r2 contains a SUCCESS, and a FAILURE.
01385     results2->push_back(*pr1);
01386     results2->push_back(*pr2);
01387   }
01388 
01389   virtual void TearDown() {
01390     delete pr1;
01391     delete pr2;
01392 
01393     delete r0;
01394     delete r1;
01395     delete r2;
01396   }
01397 
01398   // Helper that compares two two TestPartResults.
01399   static void CompareTestPartResult(const TestPartResult& expected,
01400                                     const TestPartResult& actual) {
01401     EXPECT_EQ(expected.type(), actual.type());
01402     EXPECT_STREQ(expected.file_name(), actual.file_name());
01403     EXPECT_EQ(expected.line_number(), actual.line_number());
01404     EXPECT_STREQ(expected.summary(), actual.summary());
01405     EXPECT_STREQ(expected.message(), actual.message());
01406     EXPECT_EQ(expected.passed(), actual.passed());
01407     EXPECT_EQ(expected.failed(), actual.failed());
01408     EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
01409     EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
01410   }
01411 };
01412 
01413 // Tests TestResult::total_part_count().
01414 TEST_F(TestResultTest, total_part_count) {
01415   ASSERT_EQ(0, r0->total_part_count());
01416   ASSERT_EQ(1, r1->total_part_count());
01417   ASSERT_EQ(2, r2->total_part_count());
01418 }
01419 
01420 // Tests TestResult::Passed().
01421 TEST_F(TestResultTest, Passed) {
01422   ASSERT_TRUE(r0->Passed());
01423   ASSERT_TRUE(r1->Passed());
01424   ASSERT_FALSE(r2->Passed());
01425 }
01426 
01427 // Tests TestResult::Failed().
01428 TEST_F(TestResultTest, Failed) {
01429   ASSERT_FALSE(r0->Failed());
01430   ASSERT_FALSE(r1->Failed());
01431   ASSERT_TRUE(r2->Failed());
01432 }
01433 
01434 // Tests TestResult::GetTestPartResult().
01435 
01436 typedef TestResultTest TestResultDeathTest;
01437 
01438 TEST_F(TestResultDeathTest, GetTestPartResult) {
01439   CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
01440   CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
01441   EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
01442   EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
01443 }
01444 
01445 // Tests TestResult has no properties when none are added.
01446 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
01447   TestResult test_result;
01448   ASSERT_EQ(0, test_result.test_property_count());
01449 }
01450 
01451 // Tests TestResult has the expected property when added.
01452 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
01453   TestResult test_result;
01454   TestProperty property("key_1", "1");
01455   TestResultAccessor::RecordProperty(&test_result, "testcase", property);
01456   ASSERT_EQ(1, test_result.test_property_count());
01457   const TestProperty& actual_property = test_result.GetTestProperty(0);
01458   EXPECT_STREQ("key_1", actual_property.key());
01459   EXPECT_STREQ("1", actual_property.value());
01460 }
01461 
01462 // Tests TestResult has multiple properties when added.
01463 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
01464   TestResult test_result;
01465   TestProperty property_1("key_1", "1");
01466   TestProperty property_2("key_2", "2");
01467   TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
01468   TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
01469   ASSERT_EQ(2, test_result.test_property_count());
01470   const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
01471   EXPECT_STREQ("key_1", actual_property_1.key());
01472   EXPECT_STREQ("1", actual_property_1.value());
01473 
01474   const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
01475   EXPECT_STREQ("key_2", actual_property_2.key());
01476   EXPECT_STREQ("2", actual_property_2.value());
01477 }
01478 
01479 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
01480 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
01481   TestResult test_result;
01482   TestProperty property_1_1("key_1", "1");
01483   TestProperty property_2_1("key_2", "2");
01484   TestProperty property_1_2("key_1", "12");
01485   TestProperty property_2_2("key_2", "22");
01486   TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
01487   TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
01488   TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
01489   TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
01490 
01491   ASSERT_EQ(2, test_result.test_property_count());
01492   const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
01493   EXPECT_STREQ("key_1", actual_property_1.key());
01494   EXPECT_STREQ("12", actual_property_1.value());
01495 
01496   const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
01497   EXPECT_STREQ("key_2", actual_property_2.key());
01498   EXPECT_STREQ("22", actual_property_2.value());
01499 }
01500 
01501 // Tests TestResult::GetTestProperty().
01502 TEST(TestResultPropertyTest, GetTestProperty) {
01503   TestResult test_result;
01504   TestProperty property_1("key_1", "1");
01505   TestProperty property_2("key_2", "2");
01506   TestProperty property_3("key_3", "3");
01507   TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
01508   TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
01509   TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
01510 
01511   const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
01512   const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
01513   const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
01514 
01515   EXPECT_STREQ("key_1", fetched_property_1.key());
01516   EXPECT_STREQ("1", fetched_property_1.value());
01517 
01518   EXPECT_STREQ("key_2", fetched_property_2.key());
01519   EXPECT_STREQ("2", fetched_property_2.value());
01520 
01521   EXPECT_STREQ("key_3", fetched_property_3.key());
01522   EXPECT_STREQ("3", fetched_property_3.value());
01523 
01524   EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
01525   EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
01526 }
01527 
01528 // Tests that GTestFlagSaver works on Windows and Mac.
01529 
01530 class GTestFlagSaverTest : public Test {
01531  protected:
01532   // Saves the Google Test flags such that we can restore them later, and
01533   // then sets them to their default values.  This will be called
01534   // before the first test in this test case is run.
01535   static void SetUpTestCase() {
01536     saver_ = new GTestFlagSaver;
01537 
01538     GTEST_FLAG(also_run_disabled_tests) = false;
01539     GTEST_FLAG(break_on_failure) = false;
01540     GTEST_FLAG(catch_exceptions) = false;
01541     GTEST_FLAG(death_test_use_fork) = false;
01542     GTEST_FLAG(color) = "auto";
01543     GTEST_FLAG(filter) = "";
01544     GTEST_FLAG(list_tests) = false;
01545     GTEST_FLAG(output) = "";
01546     GTEST_FLAG(print_time) = true;
01547     GTEST_FLAG(random_seed) = 0;
01548     GTEST_FLAG(repeat) = 1;
01549     GTEST_FLAG(shuffle) = false;
01550     GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
01551     GTEST_FLAG(stream_result_to) = "";
01552     GTEST_FLAG(throw_on_failure) = false;
01553   }
01554 
01555   // Restores the Google Test flags that the tests have modified.  This will
01556   // be called after the last test in this test case is run.
01557   static void TearDownTestCase() {
01558     delete saver_;
01559     saver_ = NULL;
01560   }
01561 
01562   // Verifies that the Google Test flags have their default values, and then
01563   // modifies each of them.
01564   void VerifyAndModifyFlags() {
01565     EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
01566     EXPECT_FALSE(GTEST_FLAG(break_on_failure));
01567     EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
01568     EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
01569     EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
01570     EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
01571     EXPECT_FALSE(GTEST_FLAG(list_tests));
01572     EXPECT_STREQ("", GTEST_FLAG(output).c_str());
01573     EXPECT_TRUE(GTEST_FLAG(print_time));
01574     EXPECT_EQ(0, GTEST_FLAG(random_seed));
01575     EXPECT_EQ(1, GTEST_FLAG(repeat));
01576     EXPECT_FALSE(GTEST_FLAG(shuffle));
01577     EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
01578     EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
01579     EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
01580 
01581     GTEST_FLAG(also_run_disabled_tests) = true;
01582     GTEST_FLAG(break_on_failure) = true;
01583     GTEST_FLAG(catch_exceptions) = true;
01584     GTEST_FLAG(color) = "no";
01585     GTEST_FLAG(death_test_use_fork) = true;
01586     GTEST_FLAG(filter) = "abc";
01587     GTEST_FLAG(list_tests) = true;
01588     GTEST_FLAG(output) = "xml:foo.xml";
01589     GTEST_FLAG(print_time) = false;
01590     GTEST_FLAG(random_seed) = 1;
01591     GTEST_FLAG(repeat) = 100;
01592     GTEST_FLAG(shuffle) = true;
01593     GTEST_FLAG(stack_trace_depth) = 1;
01594     GTEST_FLAG(stream_result_to) = "localhost:1234";
01595     GTEST_FLAG(throw_on_failure) = true;
01596   }
01597 
01598  private:
01599   // For saving Google Test flags during this test case.
01600   static GTestFlagSaver* saver_;
01601 };
01602 
01603 GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
01604 
01605 // Google Test doesn't guarantee the order of tests.  The following two
01606 // tests are designed to work regardless of their order.
01607 
01608 // Modifies the Google Test flags in the test body.
01609 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
01610   VerifyAndModifyFlags();
01611 }
01612 
01613 // Verifies that the Google Test flags in the body of the previous test were
01614 // restored to their original values.
01615 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
01616   VerifyAndModifyFlags();
01617 }
01618 
01619 // Sets an environment variable with the given name to the given
01620 // value.  If the value argument is "", unsets the environment
01621 // variable.  The caller must ensure that both arguments are not NULL.
01622 static void SetEnv(const char* name, const char* value) {
01623 #if GTEST_OS_WINDOWS_MOBILE
01624   // Environment variables are not supported on Windows CE.
01625   return;
01626 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
01627   // C++Builder's putenv only stores a pointer to its parameter; we have to
01628   // ensure that the string remains valid as long as it might be needed.
01629   // We use an std::map to do so.
01630   static std::map<std::string, std::string*> added_env;
01631 
01632   // Because putenv stores a pointer to the string buffer, we can't delete the
01633   // previous string (if present) until after it's replaced.
01634   std::string *prev_env = NULL;
01635   if (added_env.find(name) != added_env.end()) {
01636     prev_env = added_env[name];
01637   }
01638   added_env[name] = new std::string(
01639       (Message() << name << "=" << value).GetString());
01640 
01641   // The standard signature of putenv accepts a 'char*' argument. Other
01642   // implementations, like C++Builder's, accept a 'const char*'.
01643   // We cast away the 'const' since that would work for both variants.
01644   putenv(const_cast<char*>(added_env[name]->c_str()));
01645   delete prev_env;
01646 #elif GTEST_OS_WINDOWS  // If we are on Windows proper.
01647   _putenv((Message() << name << "=" << value).GetString().c_str());
01648 #else
01649   if (*value == '\0') {
01650     unsetenv(name);
01651   } else {
01652     setenv(name, value, 1);
01653   }
01654 #endif  // GTEST_OS_WINDOWS_MOBILE
01655 }
01656 
01657 #if !GTEST_OS_WINDOWS_MOBILE
01658 // Environment variables are not supported on Windows CE.
01659 
01660 using testing::internal::Int32FromGTestEnv;
01661 
01662 // Tests Int32FromGTestEnv().
01663 
01664 // Tests that Int32FromGTestEnv() returns the default value when the
01665 // environment variable is not set.
01666 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
01667   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
01668   EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
01669 }
01670 
01671 // Tests that Int32FromGTestEnv() returns the default value when the
01672 // environment variable overflows as an Int32.
01673 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
01674   printf("(expecting 2 warnings)\n");
01675 
01676   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
01677   EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
01678 
01679   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
01680   EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
01681 }
01682 
01683 // Tests that Int32FromGTestEnv() returns the default value when the
01684 // environment variable does not represent a valid decimal integer.
01685 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
01686   printf("(expecting 2 warnings)\n");
01687 
01688   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
01689   EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
01690 
01691   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
01692   EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
01693 }
01694 
01695 // Tests that Int32FromGTestEnv() parses and returns the value of the
01696 // environment variable when it represents a valid decimal integer in
01697 // the range of an Int32.
01698 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
01699   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
01700   EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
01701 
01702   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
01703   EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
01704 }
01705 #endif  // !GTEST_OS_WINDOWS_MOBILE
01706 
01707 // Tests ParseInt32Flag().
01708 
01709 // Tests that ParseInt32Flag() returns false and doesn't change the
01710 // output value when the flag has wrong format
01711 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
01712   Int32 value = 123;
01713   EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
01714   EXPECT_EQ(123, value);
01715 
01716   EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
01717   EXPECT_EQ(123, value);
01718 }
01719 
01720 // Tests that ParseInt32Flag() returns false and doesn't change the
01721 // output value when the flag overflows as an Int32.
01722 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
01723   printf("(expecting 2 warnings)\n");
01724 
01725   Int32 value = 123;
01726   EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
01727   EXPECT_EQ(123, value);
01728 
01729   EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
01730   EXPECT_EQ(123, value);
01731 }
01732 
01733 // Tests that ParseInt32Flag() returns false and doesn't change the
01734 // output value when the flag does not represent a valid decimal
01735 // integer.
01736 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
01737   printf("(expecting 2 warnings)\n");
01738 
01739   Int32 value = 123;
01740   EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
01741   EXPECT_EQ(123, value);
01742 
01743   EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
01744   EXPECT_EQ(123, value);
01745 }
01746 
01747 // Tests that ParseInt32Flag() parses the value of the flag and
01748 // returns true when the flag represents a valid decimal integer in
01749 // the range of an Int32.
01750 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
01751   Int32 value = 123;
01752   EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
01753   EXPECT_EQ(456, value);
01754 
01755   EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
01756                              "abc", &value));
01757   EXPECT_EQ(-789, value);
01758 }
01759 
01760 // Tests that Int32FromEnvOrDie() parses the value of the var or
01761 // returns the correct default.
01762 // Environment variables are not supported on Windows CE.
01763 #if !GTEST_OS_WINDOWS_MOBILE
01764 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
01765   EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
01766   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
01767   EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
01768   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
01769   EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
01770 }
01771 #endif  // !GTEST_OS_WINDOWS_MOBILE
01772 
01773 // Tests that Int32FromEnvOrDie() aborts with an error message
01774 // if the variable is not an Int32.
01775 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
01776   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
01777   EXPECT_DEATH_IF_SUPPORTED(
01778       Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
01779       ".*");
01780 }
01781 
01782 // Tests that Int32FromEnvOrDie() aborts with an error message
01783 // if the variable cannot be represnted by an Int32.
01784 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
01785   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
01786   EXPECT_DEATH_IF_SUPPORTED(
01787       Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
01788       ".*");
01789 }
01790 
01791 // Tests that ShouldRunTestOnShard() selects all tests
01792 // where there is 1 shard.
01793 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
01794   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
01795   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
01796   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
01797   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
01798   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
01799 }
01800 
01801 class ShouldShardTest : public testing::Test {
01802  protected:
01803   virtual void SetUp() {
01804     index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
01805     total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
01806   }
01807 
01808   virtual void TearDown() {
01809     SetEnv(index_var_, "");
01810     SetEnv(total_var_, "");
01811   }
01812 
01813   const char* index_var_;
01814   const char* total_var_;
01815 };
01816 
01817 // Tests that sharding is disabled if neither of the environment variables
01818 // are set.
01819 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
01820   SetEnv(index_var_, "");
01821   SetEnv(total_var_, "");
01822 
01823   EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
01824   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
01825 }
01826 
01827 // Tests that sharding is not enabled if total_shards  == 1.
01828 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
01829   SetEnv(index_var_, "0");
01830   SetEnv(total_var_, "1");
01831   EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
01832   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
01833 }
01834 
01835 // Tests that sharding is enabled if total_shards > 1 and
01836 // we are not in a death test subprocess.
01837 // Environment variables are not supported on Windows CE.
01838 #if !GTEST_OS_WINDOWS_MOBILE
01839 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
01840   SetEnv(index_var_, "4");
01841   SetEnv(total_var_, "22");
01842   EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
01843   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
01844 
01845   SetEnv(index_var_, "8");
01846   SetEnv(total_var_, "9");
01847   EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
01848   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
01849 
01850   SetEnv(index_var_, "0");
01851   SetEnv(total_var_, "9");
01852   EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
01853   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
01854 }
01855 #endif  // !GTEST_OS_WINDOWS_MOBILE
01856 
01857 // Tests that we exit in error if the sharding values are not valid.
01858 
01859 typedef ShouldShardTest ShouldShardDeathTest;
01860 
01861 TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
01862   SetEnv(index_var_, "4");
01863   SetEnv(total_var_, "4");
01864   EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
01865 
01866   SetEnv(index_var_, "4");
01867   SetEnv(total_var_, "-2");
01868   EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
01869 
01870   SetEnv(index_var_, "5");
01871   SetEnv(total_var_, "");
01872   EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
01873 
01874   SetEnv(index_var_, "");
01875   SetEnv(total_var_, "5");
01876   EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
01877 }
01878 
01879 // Tests that ShouldRunTestOnShard is a partition when 5
01880 // shards are used.
01881 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
01882   // Choose an arbitrary number of tests and shards.
01883   const int num_tests = 17;
01884   const int num_shards = 5;
01885 
01886   // Check partitioning: each test should be on exactly 1 shard.
01887   for (int test_id = 0; test_id < num_tests; test_id++) {
01888     int prev_selected_shard_index = -1;
01889     for (int shard_index = 0; shard_index < num_shards; shard_index++) {
01890       if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
01891         if (prev_selected_shard_index < 0) {
01892           prev_selected_shard_index = shard_index;
01893         } else {
01894           ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
01895             << shard_index << " are both selected to run test " << test_id;
01896         }
01897       }
01898     }
01899   }
01900 
01901   // Check balance: This is not required by the sharding protocol, but is a
01902   // desirable property for performance.
01903   for (int shard_index = 0; shard_index < num_shards; shard_index++) {
01904     int num_tests_on_shard = 0;
01905     for (int test_id = 0; test_id < num_tests; test_id++) {
01906       num_tests_on_shard +=
01907         ShouldRunTestOnShard(num_shards, shard_index, test_id);
01908     }
01909     EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
01910   }
01911 }
01912 
01913 // For the same reason we are not explicitly testing everything in the
01914 // Test class, there are no separate tests for the following classes
01915 // (except for some trivial cases):
01916 //
01917 //   TestCase, UnitTest, UnitTestResultPrinter.
01918 //
01919 // Similarly, there are no separate tests for the following macros:
01920 //
01921 //   TEST, TEST_F, RUN_ALL_TESTS
01922 
01923 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
01924   ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
01925   EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
01926 }
01927 
01928 TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
01929   EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
01930   EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
01931 }
01932 
01933 // When a property using a reserved key is supplied to this function, it
01934 // tests that a non-fatal failure is added, a fatal failure is not added,
01935 // and that the property is not recorded.
01936 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
01937     const TestResult& test_result, const char* key) {
01938   EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
01939   ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
01940                                                   << "' recorded unexpectedly.";
01941 }
01942 
01943 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
01944     const char* key) {
01945   const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
01946   ASSERT_TRUE(test_info != NULL);
01947   ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
01948                                                         key);
01949 }
01950 
01951 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
01952     const char* key) {
01953   const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
01954   ASSERT_TRUE(test_case != NULL);
01955   ExpectNonFatalFailureRecordingPropertyWithReservedKey(
01956       test_case->ad_hoc_test_result(), key);
01957 }
01958 
01959 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
01960     const char* key) {
01961   ExpectNonFatalFailureRecordingPropertyWithReservedKey(
01962       UnitTest::GetInstance()->ad_hoc_test_result(), key);
01963 }
01964 
01965 // Tests that property recording functions in UnitTest outside of tests
01966 // functions correcly.  Creating a separate instance of UnitTest ensures it
01967 // is in a state similar to the UnitTest's singleton's between tests.
01968 class UnitTestRecordPropertyTest :
01969     public testing::internal::UnitTestRecordPropertyTestHelper {
01970  public:
01971   static void SetUpTestCase() {
01972     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
01973         "disabled");
01974     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
01975         "errors");
01976     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
01977         "failures");
01978     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
01979         "name");
01980     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
01981         "tests");
01982     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
01983         "time");
01984 
01985     Test::RecordProperty("test_case_key_1", "1");
01986     const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
01987     ASSERT_TRUE(test_case != NULL);
01988 
01989     ASSERT_EQ(1, test_case->ad_hoc_test_result().test_property_count());
01990     EXPECT_STREQ("test_case_key_1",
01991                  test_case->ad_hoc_test_result().GetTestProperty(0).key());
01992     EXPECT_STREQ("1",
01993                  test_case->ad_hoc_test_result().GetTestProperty(0).value());
01994   }
01995 };
01996 
01997 // Tests TestResult has the expected property when added.
01998 TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
01999   UnitTestRecordProperty("key_1", "1");
02000 
02001   ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
02002 
02003   EXPECT_STREQ("key_1",
02004                unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
02005   EXPECT_STREQ("1",
02006                unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
02007 }
02008 
02009 // Tests TestResult has multiple properties when added.
02010 TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
02011   UnitTestRecordProperty("key_1", "1");
02012   UnitTestRecordProperty("key_2", "2");
02013 
02014   ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
02015 
02016   EXPECT_STREQ("key_1",
02017                unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
02018   EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
02019 
02020   EXPECT_STREQ("key_2",
02021                unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
02022   EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
02023 }
02024 
02025 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
02026 TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
02027   UnitTestRecordProperty("key_1", "1");
02028   UnitTestRecordProperty("key_2", "2");
02029   UnitTestRecordProperty("key_1", "12");
02030   UnitTestRecordProperty("key_2", "22");
02031 
02032   ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
02033 
02034   EXPECT_STREQ("key_1",
02035                unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
02036   EXPECT_STREQ("12",
02037                unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
02038 
02039   EXPECT_STREQ("key_2",
02040                unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
02041   EXPECT_STREQ("22",
02042                unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
02043 }
02044 
02045 TEST_F(UnitTestRecordPropertyTest,
02046        AddFailureInsideTestsWhenUsingTestCaseReservedKeys) {
02047   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
02048       "name");
02049   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
02050       "value_param");
02051   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
02052       "type_param");
02053   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
02054       "status");
02055   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
02056       "time");
02057   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
02058       "classname");
02059 }
02060 
02061 TEST_F(UnitTestRecordPropertyTest,
02062        AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
02063   EXPECT_NONFATAL_FAILURE(
02064       Test::RecordProperty("name", "1"),
02065       "'classname', 'name', 'status', 'time', 'type_param', and 'value_param'"
02066       " are reserved");
02067 }
02068 
02069 class UnitTestRecordPropertyTestEnvironment : public Environment {
02070  public:
02071   virtual void TearDown() {
02072     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
02073         "tests");
02074     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
02075         "failures");
02076     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
02077         "disabled");
02078     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
02079         "errors");
02080     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
02081         "name");
02082     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
02083         "timestamp");
02084     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
02085         "time");
02086     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
02087         "random_seed");
02088   }
02089 };
02090 
02091 // This will test property recording outside of any test or test case.
02092 static Environment* record_property_env =
02093     AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
02094 
02095 // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
02096 // of various arities.  They do not attempt to be exhaustive.  Rather,
02097 // view them as smoke tests that can be easily reviewed and verified.
02098 // A more complete set of tests for predicate assertions can be found
02099 // in gtest_pred_impl_unittest.cc.
02100 
02101 // First, some predicates and predicate-formatters needed by the tests.
02102 
02103 // Returns true iff the argument is an even number.
02104 bool IsEven(int n) {
02105   return (n % 2) == 0;
02106 }
02107 
02108 // A functor that returns true iff the argument is an even number.
02109 struct IsEvenFunctor {
02110   bool operator()(int n) { return IsEven(n); }
02111 };
02112 
02113 // A predicate-formatter function that asserts the argument is an even
02114 // number.
02115 AssertionResult AssertIsEven(const char* expr, int n) {
02116   if (IsEven(n)) {
02117     return AssertionSuccess();
02118   }
02119 
02120   Message msg;
02121   msg << expr << " evaluates to " << n << ", which is not even.";
02122   return AssertionFailure(msg);
02123 }
02124 
02125 // A predicate function that returns AssertionResult for use in
02126 // EXPECT/ASSERT_TRUE/FALSE.
02127 AssertionResult ResultIsEven(int n) {
02128   if (IsEven(n))
02129     return AssertionSuccess() << n << " is even";
02130   else
02131     return AssertionFailure() << n << " is odd";
02132 }
02133 
02134 // A predicate function that returns AssertionResult but gives no
02135 // explanation why it succeeds. Needed for testing that
02136 // EXPECT/ASSERT_FALSE handles such functions correctly.
02137 AssertionResult ResultIsEvenNoExplanation(int n) {
02138   if (IsEven(n))
02139     return AssertionSuccess();
02140   else
02141     return AssertionFailure() << n << " is odd";
02142 }
02143 
02144 // A predicate-formatter functor that asserts the argument is an even
02145 // number.
02146 struct AssertIsEvenFunctor {
02147   AssertionResult operator()(const char* expr, int n) {
02148     return AssertIsEven(expr, n);
02149   }
02150 };
02151 
02152 // Returns true iff the sum of the arguments is an even number.
02153 bool SumIsEven2(int n1, int n2) {
02154   return IsEven(n1 + n2);
02155 }
02156 
02157 // A functor that returns true iff the sum of the arguments is an even
02158 // number.
02159 struct SumIsEven3Functor {
02160   bool operator()(int n1, int n2, int n3) {
02161     return IsEven(n1 + n2 + n3);
02162   }
02163 };
02164 
02165 // A predicate-formatter function that asserts the sum of the
02166 // arguments is an even number.
02167 AssertionResult AssertSumIsEven4(
02168     const char* e1, const char* e2, const char* e3, const char* e4,
02169     int n1, int n2, int n3, int n4) {
02170   const int sum = n1 + n2 + n3 + n4;
02171   if (IsEven(sum)) {
02172     return AssertionSuccess();
02173   }
02174 
02175   Message msg;
02176   msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
02177       << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
02178       << ") evaluates to " << sum << ", which is not even.";
02179   return AssertionFailure(msg);
02180 }
02181 
02182 // A predicate-formatter functor that asserts the sum of the arguments
02183 // is an even number.
02184 struct AssertSumIsEven5Functor {
02185   AssertionResult operator()(
02186       const char* e1, const char* e2, const char* e3, const char* e4,
02187       const char* e5, int n1, int n2, int n3, int n4, int n5) {
02188     const int sum = n1 + n2 + n3 + n4 + n5;
02189     if (IsEven(sum)) {
02190       return AssertionSuccess();
02191     }
02192 
02193     Message msg;
02194     msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
02195         << " ("
02196         << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
02197         << ") evaluates to " << sum << ", which is not even.";
02198     return AssertionFailure(msg);
02199   }
02200 };
02201 
02202 
02203 // Tests unary predicate assertions.
02204 
02205 // Tests unary predicate assertions that don't use a custom formatter.
02206 TEST(Pred1Test, WithoutFormat) {
02207   // Success cases.
02208   EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
02209   ASSERT_PRED1(IsEven, 4);
02210 
02211   // Failure cases.
02212   EXPECT_NONFATAL_FAILURE({  // NOLINT
02213     EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
02214   }, "This failure is expected.");
02215   EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
02216                        "evaluates to false");
02217 }
02218 
02219 // Tests unary predicate assertions that use a custom formatter.
02220 TEST(Pred1Test, WithFormat) {
02221   // Success cases.
02222   EXPECT_PRED_FORMAT1(AssertIsEven, 2);
02223   ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
02224     << "This failure is UNEXPECTED!";
02225 
02226   // Failure cases.
02227   const int n = 5;
02228   EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
02229                           "n evaluates to 5, which is not even.");
02230   EXPECT_FATAL_FAILURE({  // NOLINT
02231     ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
02232   }, "This failure is expected.");
02233 }
02234 
02235 // Tests that unary predicate assertions evaluates their arguments
02236 // exactly once.
02237 TEST(Pred1Test, SingleEvaluationOnFailure) {
02238   // A success case.
02239   static int n = 0;
02240   EXPECT_PRED1(IsEven, n++);
02241   EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
02242 
02243   // A failure case.
02244   EXPECT_FATAL_FAILURE({  // NOLINT
02245     ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
02246         << "This failure is expected.";
02247   }, "This failure is expected.");
02248   EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
02249 }
02250 
02251 
02252 // Tests predicate assertions whose arity is >= 2.
02253 
02254 // Tests predicate assertions that don't use a custom formatter.
02255 TEST(PredTest, WithoutFormat) {
02256   // Success cases.
02257   ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
02258   EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
02259 
02260   // Failure cases.
02261   const int n1 = 1;
02262   const int n2 = 2;
02263   EXPECT_NONFATAL_FAILURE({  // NOLINT
02264     EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
02265   }, "This failure is expected.");
02266   EXPECT_FATAL_FAILURE({  // NOLINT
02267     ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
02268   }, "evaluates to false");
02269 }
02270 
02271 // Tests predicate assertions that use a custom formatter.
02272 TEST(PredTest, WithFormat) {
02273   // Success cases.
02274   ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
02275     "This failure is UNEXPECTED!";
02276   EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
02277 
02278   // Failure cases.
02279   const int n1 = 1;
02280   const int n2 = 2;
02281   const int n3 = 4;
02282   const int n4 = 6;
02283   EXPECT_NONFATAL_FAILURE({  // NOLINT
02284     EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
02285   }, "evaluates to 13, which is not even.");
02286   EXPECT_FATAL_FAILURE({  // NOLINT
02287     ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
02288         << "This failure is expected.";
02289   }, "This failure is expected.");
02290 }
02291 
02292 // Tests that predicate assertions evaluates their arguments
02293 // exactly once.
02294 TEST(PredTest, SingleEvaluationOnFailure) {
02295   // A success case.
02296   int n1 = 0;
02297   int n2 = 0;
02298   EXPECT_PRED2(SumIsEven2, n1++, n2++);
02299   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
02300   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
02301 
02302   // Another success case.
02303   n1 = n2 = 0;
02304   int n3 = 0;
02305   int n4 = 0;
02306   int n5 = 0;
02307   ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
02308                       n1++, n2++, n3++, n4++, n5++)
02309                         << "This failure is UNEXPECTED!";
02310   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
02311   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
02312   EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
02313   EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
02314   EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
02315 
02316   // A failure case.
02317   n1 = n2 = n3 = 0;
02318   EXPECT_NONFATAL_FAILURE({  // NOLINT
02319     EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
02320         << "This failure is expected.";
02321   }, "This failure is expected.");
02322   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
02323   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
02324   EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
02325 
02326   // Another failure case.
02327   n1 = n2 = n3 = n4 = 0;
02328   EXPECT_NONFATAL_FAILURE({  // NOLINT
02329     EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
02330   }, "evaluates to 1, which is not even.");
02331   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
02332   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
02333   EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
02334   EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
02335 }
02336 
02337 
02338 // Some helper functions for testing using overloaded/template
02339 // functions with ASSERT_PREDn and EXPECT_PREDn.
02340 
02341 bool IsPositive(double x) {
02342   return x > 0;
02343 }
02344 
02345 template <typename T>
02346 bool IsNegative(T x) {
02347   return x < 0;
02348 }
02349 
02350 template <typename T1, typename T2>
02351 bool GreaterThan(T1 x1, T2 x2) {
02352   return x1 > x2;
02353 }
02354 
02355 // Tests that overloaded functions can be used in *_PRED* as long as
02356 // their types are explicitly specified.
02357 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
02358   // C++Builder requires C-style casts rather than static_cast.
02359   EXPECT_PRED1((bool (*)(int))(IsPositive), 5);  // NOLINT
02360   ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0);  // NOLINT
02361 }
02362 
02363 // Tests that template functions can be used in *_PRED* as long as
02364 // their types are explicitly specified.
02365 TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
02366   EXPECT_PRED1(IsNegative<int>, -5);
02367   // Makes sure that we can handle templates with more than one
02368   // parameter.
02369   ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
02370 }
02371 
02372 
02373 // Some helper functions for testing using overloaded/template
02374 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
02375 
02376 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
02377   return n > 0 ? AssertionSuccess() :
02378       AssertionFailure(Message() << "Failure");
02379 }
02380 
02381 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
02382   return x > 0 ? AssertionSuccess() :
02383       AssertionFailure(Message() << "Failure");
02384 }
02385 
02386 template <typename T>
02387 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
02388   return x < 0 ? AssertionSuccess() :
02389       AssertionFailure(Message() << "Failure");
02390 }
02391 
02392 template <typename T1, typename T2>
02393 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
02394                              const T1& x1, const T2& x2) {
02395   return x1 == x2 ? AssertionSuccess() :
02396       AssertionFailure(Message() << "Failure");
02397 }
02398 
02399 // Tests that overloaded functions can be used in *_PRED_FORMAT*
02400 // without explicitly specifying their types.
02401 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
02402   EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
02403   ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
02404 }
02405 
02406 // Tests that template functions can be used in *_PRED_FORMAT* without
02407 // explicitly specifying their types.
02408 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
02409   EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
02410   ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
02411 }
02412 
02413 
02414 // Tests string assertions.
02415 
02416 // Tests ASSERT_STREQ with non-NULL arguments.
02417 TEST(StringAssertionTest, ASSERT_STREQ) {
02418   const char * const p1 = "good";
02419   ASSERT_STREQ(p1, p1);
02420 
02421   // Let p2 have the same content as p1, but be at a different address.
02422   const char p2[] = "good";
02423   ASSERT_STREQ(p1, p2);
02424 
02425   EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
02426                        "Expected: \"bad\"");
02427 }
02428 
02429 // Tests ASSERT_STREQ with NULL arguments.
02430 TEST(StringAssertionTest, ASSERT_STREQ_Null) {
02431   ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
02432   EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
02433                        "non-null");
02434 }
02435 
02436 // Tests ASSERT_STREQ with NULL arguments.
02437 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
02438   EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
02439                        "non-null");
02440 }
02441 
02442 // Tests ASSERT_STRNE.
02443 TEST(StringAssertionTest, ASSERT_STRNE) {
02444   ASSERT_STRNE("hi", "Hi");
02445   ASSERT_STRNE("Hi", NULL);
02446   ASSERT_STRNE(NULL, "Hi");
02447   ASSERT_STRNE("", NULL);
02448   ASSERT_STRNE(NULL, "");
02449   ASSERT_STRNE("", "Hi");
02450   ASSERT_STRNE("Hi", "");
02451   EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
02452                        "\"Hi\" vs \"Hi\"");
02453 }
02454 
02455 // Tests ASSERT_STRCASEEQ.
02456 TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
02457   ASSERT_STRCASEEQ("hi", "Hi");
02458   ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
02459 
02460   ASSERT_STRCASEEQ("", "");
02461   EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
02462                        "(ignoring case)");
02463 }
02464 
02465 // Tests ASSERT_STRCASENE.
02466 TEST(StringAssertionTest, ASSERT_STRCASENE) {
02467   ASSERT_STRCASENE("hi1", "Hi2");
02468   ASSERT_STRCASENE("Hi", NULL);
02469   ASSERT_STRCASENE(NULL, "Hi");
02470   ASSERT_STRCASENE("", NULL);
02471   ASSERT_STRCASENE(NULL, "");
02472   ASSERT_STRCASENE("", "Hi");
02473   ASSERT_STRCASENE("Hi", "");
02474   EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
02475                        "(ignoring case)");
02476 }
02477 
02478 // Tests *_STREQ on wide strings.
02479 TEST(StringAssertionTest, STREQ_Wide) {
02480   // NULL strings.
02481   ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
02482 
02483   // Empty strings.
02484   ASSERT_STREQ(L"", L"");
02485 
02486   // Non-null vs NULL.
02487   EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
02488                           "non-null");
02489 
02490   // Equal strings.
02491   EXPECT_STREQ(L"Hi", L"Hi");
02492 
02493   // Unequal strings.
02494   EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
02495                           "Abc");
02496 
02497   // Strings containing wide characters.
02498   EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
02499                           "abc");
02500 
02501   // The streaming variation.
02502   EXPECT_NONFATAL_FAILURE({  // NOLINT
02503     EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
02504   }, "Expected failure");
02505 }
02506 
02507 // Tests *_STRNE on wide strings.
02508 TEST(StringAssertionTest, STRNE_Wide) {
02509   // NULL strings.
02510   EXPECT_NONFATAL_FAILURE({  // NOLINT
02511     EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
02512   }, "");
02513 
02514   // Empty strings.
02515   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
02516                           "L\"\"");
02517 
02518   // Non-null vs NULL.
02519   ASSERT_STRNE(L"non-null", NULL);
02520 
02521   // Equal strings.
02522   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
02523                           "L\"Hi\"");
02524 
02525   // Unequal strings.
02526   EXPECT_STRNE(L"abc", L"Abc");
02527 
02528   // Strings containing wide characters.
02529   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
02530                           "abc");
02531 
02532   // The streaming variation.
02533   ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
02534 }
02535 
02536 // Tests for ::testing::IsSubstring().
02537 
02538 // Tests that IsSubstring() returns the correct result when the input
02539 // argument type is const char*.
02540 TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
02541   EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
02542   EXPECT_FALSE(IsSubstring("", "", "b", NULL));
02543   EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
02544 
02545   EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
02546   EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
02547 }
02548 
02549 // Tests that IsSubstring() returns the correct result when the input
02550 // argument type is const wchar_t*.
02551 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
02552   EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
02553   EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
02554   EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
02555 
02556   EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
02557   EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
02558 }
02559 
02560 // Tests that IsSubstring() generates the correct message when the input
02561 // argument type is const char*.
02562 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
02563   EXPECT_STREQ("Value of: needle_expr\n"
02564                "  Actual: \"needle\"\n"
02565                "Expected: a substring of haystack_expr\n"
02566                "Which is: \"haystack\"",
02567                IsSubstring("needle_expr", "haystack_expr",
02568                            "needle", "haystack").failure_message());
02569 }
02570 
02571 // Tests that IsSubstring returns the correct result when the input
02572 // argument type is ::std::string.
02573 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
02574   EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
02575   EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
02576 }
02577 
02578 #if GTEST_HAS_STD_WSTRING
02579 // Tests that IsSubstring returns the correct result when the input
02580 // argument type is ::std::wstring.
02581 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
02582   EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
02583   EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
02584 }
02585 
02586 // Tests that IsSubstring() generates the correct message when the input
02587 // argument type is ::std::wstring.
02588 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
02589   EXPECT_STREQ("Value of: needle_expr\n"
02590                "  Actual: L\"needle\"\n"
02591                "Expected: a substring of haystack_expr\n"
02592                "Which is: L\"haystack\"",
02593                IsSubstring(
02594                    "needle_expr", "haystack_expr",
02595                    ::std::wstring(L"needle"), L"haystack").failure_message());
02596 }
02597 
02598 #endif  // GTEST_HAS_STD_WSTRING
02599 
02600 // Tests for ::testing::IsNotSubstring().
02601 
02602 // Tests that IsNotSubstring() returns the correct result when the input
02603 // argument type is const char*.
02604 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
02605   EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
02606   EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
02607 }
02608 
02609 // Tests that IsNotSubstring() returns the correct result when the input
02610 // argument type is const wchar_t*.
02611 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
02612   EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
02613   EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
02614 }
02615 
02616 // Tests that IsNotSubstring() generates the correct message when the input
02617 // argument type is const wchar_t*.
02618 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
02619   EXPECT_STREQ("Value of: needle_expr\n"
02620                "  Actual: L\"needle\"\n"
02621                "Expected: not a substring of haystack_expr\n"
02622                "Which is: L\"two needles\"",
02623                IsNotSubstring(
02624                    "needle_expr", "haystack_expr",
02625                    L"needle", L"two needles").failure_message());
02626 }
02627 
02628 // Tests that IsNotSubstring returns the correct result when the input
02629 // argument type is ::std::string.
02630 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
02631   EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
02632   EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
02633 }
02634 
02635 // Tests that IsNotSubstring() generates the correct message when the input
02636 // argument type is ::std::string.
02637 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
02638   EXPECT_STREQ("Value of: needle_expr\n"
02639                "  Actual: \"needle\"\n"
02640                "Expected: not a substring of haystack_expr\n"
02641                "Which is: \"two needles\"",
02642                IsNotSubstring(
02643                    "needle_expr", "haystack_expr",
02644                    ::std::string("needle"), "two needles").failure_message());
02645 }
02646 
02647 #if GTEST_HAS_STD_WSTRING
02648 
02649 // Tests that IsNotSubstring returns the correct result when the input
02650 // argument type is ::std::wstring.
02651 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
02652   EXPECT_FALSE(
02653       IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
02654   EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
02655 }
02656 
02657 #endif  // GTEST_HAS_STD_WSTRING
02658 
02659 // Tests floating-point assertions.
02660 
02661 template <typename RawType>
02662 class FloatingPointTest : public Test {
02663  protected:
02664   // Pre-calculated numbers to be used by the tests.
02665   struct TestValues {
02666     RawType close_to_positive_zero;
02667     RawType close_to_negative_zero;
02668     RawType further_from_negative_zero;
02669 
02670     RawType close_to_one;
02671     RawType further_from_one;
02672 
02673     RawType infinity;
02674     RawType close_to_infinity;
02675     RawType further_from_infinity;
02676 
02677     RawType nan1;
02678     RawType nan2;
02679   };
02680 
02681   typedef typename testing::internal::FloatingPoint<RawType> Floating;
02682   typedef typename Floating::Bits Bits;
02683 
02684   virtual void SetUp() {
02685     const size_t max_ulps = Floating::kMaxUlps;
02686 
02687     // The bits that represent 0.0.
02688     const Bits zero_bits = Floating(0).bits();
02689 
02690     // Makes some numbers close to 0.0.
02691     values_.close_to_positive_zero = Floating::ReinterpretBits(
02692         zero_bits + max_ulps/2);
02693     values_.close_to_negative_zero = -Floating::ReinterpretBits(
02694         zero_bits + max_ulps - max_ulps/2);
02695     values_.further_from_negative_zero = -Floating::ReinterpretBits(
02696         zero_bits + max_ulps + 1 - max_ulps/2);
02697 
02698     // The bits that represent 1.0.
02699     const Bits one_bits = Floating(1).bits();
02700 
02701     // Makes some numbers close to 1.0.
02702     values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
02703     values_.further_from_one = Floating::ReinterpretBits(
02704         one_bits + max_ulps + 1);
02705 
02706     // +infinity.
02707     values_.infinity = Floating::Infinity();
02708 
02709     // The bits that represent +infinity.
02710     const Bits infinity_bits = Floating(values_.infinity).bits();
02711 
02712     // Makes some numbers close to infinity.
02713     values_.close_to_infinity = Floating::ReinterpretBits(
02714         infinity_bits - max_ulps);
02715     values_.further_from_infinity = Floating::ReinterpretBits(
02716         infinity_bits - max_ulps - 1);
02717 
02718     // Makes some NAN's.  Sets the most significant bit of the fraction so that
02719     // our NaN's are quiet; trying to process a signaling NaN would raise an
02720     // exception if our environment enables floating point exceptions.
02721     values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
02722         | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
02723     values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
02724         | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
02725   }
02726 
02727   void TestSize() {
02728     EXPECT_EQ(sizeof(RawType), sizeof(Bits));
02729   }
02730 
02731   static TestValues values_;
02732 };
02733 
02734 template <typename RawType>
02735 typename FloatingPointTest<RawType>::TestValues
02736     FloatingPointTest<RawType>::values_;
02737 
02738 // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
02739 typedef FloatingPointTest<float> FloatTest;
02740 
02741 // Tests that the size of Float::Bits matches the size of float.
02742 TEST_F(FloatTest, Size) {
02743   TestSize();
02744 }
02745 
02746 // Tests comparing with +0 and -0.
02747 TEST_F(FloatTest, Zeros) {
02748   EXPECT_FLOAT_EQ(0.0, -0.0);
02749   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
02750                           "1.0");
02751   EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
02752                        "1.5");
02753 }
02754 
02755 // Tests comparing numbers close to 0.
02756 //
02757 // This ensures that *_FLOAT_EQ handles the sign correctly and no
02758 // overflow occurs when comparing numbers whose absolute value is very
02759 // small.
02760 TEST_F(FloatTest, AlmostZeros) {
02761   // In C++Builder, names within local classes (such as used by
02762   // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
02763   // scoping class.  Use a static local alias as a workaround.
02764   // We use the assignment syntax since some compilers, like Sun Studio,
02765   // don't allow initializing references using construction syntax
02766   // (parentheses).
02767   static const FloatTest::TestValues& v = this->values_;
02768 
02769   EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
02770   EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
02771   EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
02772 
02773   EXPECT_FATAL_FAILURE({  // NOLINT
02774     ASSERT_FLOAT_EQ(v.close_to_positive_zero,
02775                     v.further_from_negative_zero);
02776   }, "v.further_from_negative_zero");
02777 }
02778 
02779 // Tests comparing numbers close to each other.
02780 TEST_F(FloatTest, SmallDiff) {
02781   EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
02782   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
02783                           "values_.further_from_one");
02784 }
02785 
02786 // Tests comparing numbers far apart.
02787 TEST_F(FloatTest, LargeDiff) {
02788   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
02789                           "3.0");
02790 }
02791 
02792 // Tests comparing with infinity.
02793 //
02794 // This ensures that no overflow occurs when comparing numbers whose
02795 // absolute value is very large.
02796 TEST_F(FloatTest, Infinity) {
02797   EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
02798   EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
02799 #if !GTEST_OS_SYMBIAN
02800   // Nokia's STLport crashes if we try to output infinity or NaN.
02801   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
02802                           "-values_.infinity");
02803 
02804   // This is interesting as the representations of infinity and nan1
02805   // are only 1 DLP apart.
02806   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
02807                           "values_.nan1");
02808 #endif  // !GTEST_OS_SYMBIAN
02809 }
02810 
02811 // Tests that comparing with NAN always returns false.
02812 TEST_F(FloatTest, NaN) {
02813 #if !GTEST_OS_SYMBIAN
02814 // Nokia's STLport crashes if we try to output infinity or NaN.
02815 
02816   // In C++Builder, names within local classes (such as used by
02817   // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
02818   // scoping class.  Use a static local alias as a workaround.
02819   // We use the assignment syntax since some compilers, like Sun Studio,
02820   // don't allow initializing references using construction syntax
02821   // (parentheses).
02822   static const FloatTest::TestValues& v = this->values_;
02823 
02824   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
02825                           "v.nan1");
02826   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
02827                           "v.nan2");
02828   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
02829                           "v.nan1");
02830 
02831   EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
02832                        "v.infinity");
02833 #endif  // !GTEST_OS_SYMBIAN
02834 }
02835 
02836 // Tests that *_FLOAT_EQ are reflexive.
02837 TEST_F(FloatTest, Reflexive) {
02838   EXPECT_FLOAT_EQ(0.0, 0.0);
02839   EXPECT_FLOAT_EQ(1.0, 1.0);
02840   ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
02841 }
02842 
02843 // Tests that *_FLOAT_EQ are commutative.
02844 TEST_F(FloatTest, Commutative) {
02845   // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
02846   EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
02847 
02848   // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
02849   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
02850                           "1.0");
02851 }
02852 
02853 // Tests EXPECT_NEAR.
02854 TEST_F(FloatTest, EXPECT_NEAR) {
02855   EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
02856   EXPECT_NEAR(2.0f, 3.0f, 1.0f);
02857   EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f),  // NOLINT
02858                           "The difference between 1.0f and 1.5f is 0.5, "
02859                           "which exceeds 0.25f");
02860   // To work around a bug in gcc 2.95.0, there is intentionally no
02861   // space after the first comma in the previous line.
02862 }
02863 
02864 // Tests ASSERT_NEAR.
02865 TEST_F(FloatTest, ASSERT_NEAR) {
02866   ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
02867   ASSERT_NEAR(2.0f, 3.0f, 1.0f);
02868   EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f),  // NOLINT
02869                        "The difference between 1.0f and 1.5f is 0.5, "
02870                        "which exceeds 0.25f");
02871   // To work around a bug in gcc 2.95.0, there is intentionally no
02872   // space after the first comma in the previous line.
02873 }
02874 
02875 // Tests the cases where FloatLE() should succeed.
02876 TEST_F(FloatTest, FloatLESucceeds) {
02877   EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f);  // When val1 < val2,
02878   ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f);  // val1 == val2,
02879 
02880   // or when val1 is greater than, but almost equals to, val2.
02881   EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
02882 }
02883 
02884 // Tests the cases where FloatLE() should fail.
02885 TEST_F(FloatTest, FloatLEFails) {
02886   // When val1 is greater than val2 by a large margin,
02887   EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
02888                           "(2.0f) <= (1.0f)");
02889 
02890   // or by a small yet non-negligible margin,
02891   EXPECT_NONFATAL_FAILURE({  // NOLINT
02892     EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
02893   }, "(values_.further_from_one) <= (1.0f)");
02894 
02895 #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
02896   // Nokia's STLport crashes if we try to output infinity or NaN.
02897   // C++Builder gives bad results for ordered comparisons involving NaNs
02898   // due to compiler bugs.
02899   EXPECT_NONFATAL_FAILURE({  // NOLINT
02900     EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
02901   }, "(values_.nan1) <= (values_.infinity)");
02902   EXPECT_NONFATAL_FAILURE({  // NOLINT
02903     EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
02904   }, "(-values_.infinity) <= (values_.nan1)");
02905   EXPECT_FATAL_FAILURE({  // NOLINT
02906     ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
02907   }, "(values_.nan1) <= (values_.nan1)");
02908 #endif  // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
02909 }
02910 
02911 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
02912 typedef FloatingPointTest<double> DoubleTest;
02913 
02914 // Tests that the size of Double::Bits matches the size of double.
02915 TEST_F(DoubleTest, Size) {
02916   TestSize();
02917 }
02918 
02919 // Tests comparing with +0 and -0.
02920 TEST_F(DoubleTest, Zeros) {
02921   EXPECT_DOUBLE_EQ(0.0, -0.0);
02922   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
02923                           "1.0");
02924   EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
02925                        "1.0");
02926 }
02927 
02928 // Tests comparing numbers close to 0.
02929 //
02930 // This ensures that *_DOUBLE_EQ handles the sign correctly and no
02931 // overflow occurs when comparing numbers whose absolute value is very
02932 // small.
02933 TEST_F(DoubleTest, AlmostZeros) {
02934   // In C++Builder, names within local classes (such as used by
02935   // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
02936   // scoping class.  Use a static local alias as a workaround.
02937   // We use the assignment syntax since some compilers, like Sun Studio,
02938   // don't allow initializing references using construction syntax
02939   // (parentheses).
02940   static const DoubleTest::TestValues& v = this->values_;
02941 
02942   EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
02943   EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
02944   EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
02945 
02946   EXPECT_FATAL_FAILURE({  // NOLINT
02947     ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
02948                      v.further_from_negative_zero);
02949   }, "v.further_from_negative_zero");
02950 }
02951 
02952 // Tests comparing numbers close to each other.
02953 TEST_F(DoubleTest, SmallDiff) {
02954   EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
02955   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
02956                           "values_.further_from_one");
02957 }
02958 
02959 // Tests comparing numbers far apart.
02960 TEST_F(DoubleTest, LargeDiff) {
02961   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
02962                           "3.0");
02963 }
02964 
02965 // Tests comparing with infinity.
02966 //
02967 // This ensures that no overflow occurs when comparing numbers whose
02968 // absolute value is very large.
02969 TEST_F(DoubleTest, Infinity) {
02970   EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
02971   EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
02972 #if !GTEST_OS_SYMBIAN
02973   // Nokia's STLport crashes if we try to output infinity or NaN.
02974   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
02975                           "-values_.infinity");
02976 
02977   // This is interesting as the representations of infinity_ and nan1_
02978   // are only 1 DLP apart.
02979   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
02980                           "values_.nan1");
02981 #endif  // !GTEST_OS_SYMBIAN
02982 }
02983 
02984 // Tests that comparing with NAN always returns false.
02985 TEST_F(DoubleTest, NaN) {
02986 #if !GTEST_OS_SYMBIAN
02987   // In C++Builder, names within local classes (such as used by
02988   // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
02989   // scoping class.  Use a static local alias as a workaround.
02990   // We use the assignment syntax since some compilers, like Sun Studio,
02991   // don't allow initializing references using construction syntax
02992   // (parentheses).
02993   static const DoubleTest::TestValues& v = this->values_;
02994 
02995   // Nokia's STLport crashes if we try to output infinity or NaN.
02996   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
02997                           "v.nan1");
02998   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
02999   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
03000   EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
03001                        "v.infinity");
03002 #endif  // !GTEST_OS_SYMBIAN
03003 }
03004 
03005 // Tests that *_DOUBLE_EQ are reflexive.
03006 TEST_F(DoubleTest, Reflexive) {
03007   EXPECT_DOUBLE_EQ(0.0, 0.0);
03008   EXPECT_DOUBLE_EQ(1.0, 1.0);
03009 #if !GTEST_OS_SYMBIAN
03010   // Nokia's STLport crashes if we try to output infinity or NaN.
03011   ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
03012 #endif  // !GTEST_OS_SYMBIAN
03013 }
03014 
03015 // Tests that *_DOUBLE_EQ are commutative.
03016 TEST_F(DoubleTest, Commutative) {
03017   // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
03018   EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
03019 
03020   // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
03021   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
03022                           "1.0");
03023 }
03024 
03025 // Tests EXPECT_NEAR.
03026 TEST_F(DoubleTest, EXPECT_NEAR) {
03027   EXPECT_NEAR(-1.0, -1.1, 0.2);
03028   EXPECT_NEAR(2.0, 3.0, 1.0);
03029   EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25),  // NOLINT
03030                           "The difference between 1.0 and 1.5 is 0.5, "
03031                           "which exceeds 0.25");
03032   // To work around a bug in gcc 2.95.0, there is intentionally no
03033   // space after the first comma in the previous statement.
03034 }
03035 
03036 // Tests ASSERT_NEAR.
03037 TEST_F(DoubleTest, ASSERT_NEAR) {
03038   ASSERT_NEAR(-1.0, -1.1, 0.2);
03039   ASSERT_NEAR(2.0, 3.0, 1.0);
03040   EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25),  // NOLINT
03041                        "The difference between 1.0 and 1.5 is 0.5, "
03042                        "which exceeds 0.25");
03043   // To work around a bug in gcc 2.95.0, there is intentionally no
03044   // space after the first comma in the previous statement.
03045 }
03046 
03047 // Tests the cases where DoubleLE() should succeed.
03048 TEST_F(DoubleTest, DoubleLESucceeds) {
03049   EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0);  // When val1 < val2,
03050   ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0);  // val1 == val2,
03051 
03052   // or when val1 is greater than, but almost equals to, val2.
03053   EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
03054 }
03055 
03056 // Tests the cases where DoubleLE() should fail.
03057 TEST_F(DoubleTest, DoubleLEFails) {
03058   // When val1 is greater than val2 by a large margin,
03059   EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
03060                           "(2.0) <= (1.0)");
03061 
03062   // or by a small yet non-negligible margin,
03063   EXPECT_NONFATAL_FAILURE({  // NOLINT
03064     EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
03065   }, "(values_.further_from_one) <= (1.0)");
03066 
03067 #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
03068   // Nokia's STLport crashes if we try to output infinity or NaN.
03069   // C++Builder gives bad results for ordered comparisons involving NaNs
03070   // due to compiler bugs.
03071   EXPECT_NONFATAL_FAILURE({  // NOLINT
03072     EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
03073   }, "(values_.nan1) <= (values_.infinity)");
03074   EXPECT_NONFATAL_FAILURE({  // NOLINT
03075     EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
03076   }, " (-values_.infinity) <= (values_.nan1)");
03077   EXPECT_FATAL_FAILURE({  // NOLINT
03078     ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
03079   }, "(values_.nan1) <= (values_.nan1)");
03080 #endif  // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
03081 }
03082 
03083 
03084 // Verifies that a test or test case whose name starts with DISABLED_ is
03085 // not run.
03086 
03087 // A test whose name starts with DISABLED_.
03088 // Should not run.
03089 TEST(DisabledTest, DISABLED_TestShouldNotRun) {
03090   FAIL() << "Unexpected failure: Disabled test should not be run.";
03091 }
03092 
03093 // A test whose name does not start with DISABLED_.
03094 // Should run.
03095 TEST(DisabledTest, NotDISABLED_TestShouldRun) {
03096   EXPECT_EQ(1, 1);
03097 }
03098 
03099 // A test case whose name starts with DISABLED_.
03100 // Should not run.
03101 TEST(DISABLED_TestCase, TestShouldNotRun) {
03102   FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
03103 }
03104 
03105 // A test case and test whose names start with DISABLED_.
03106 // Should not run.
03107 TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
03108   FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
03109 }
03110 
03111 // Check that when all tests in a test case are disabled, SetupTestCase() and
03112 // TearDownTestCase() are not called.
03113 class DisabledTestsTest : public Test {
03114  protected:
03115   static void SetUpTestCase() {
03116     FAIL() << "Unexpected failure: All tests disabled in test case. "
03117               "SetupTestCase() should not be called.";
03118   }
03119 
03120   static void TearDownTestCase() {
03121     FAIL() << "Unexpected failure: All tests disabled in test case. "
03122               "TearDownTestCase() should not be called.";
03123   }
03124 };
03125 
03126 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
03127   FAIL() << "Unexpected failure: Disabled test should not be run.";
03128 }
03129 
03130 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
03131   FAIL() << "Unexpected failure: Disabled test should not be run.";
03132 }
03133 
03134 // Tests that disabled typed tests aren't run.
03135 
03136 #if GTEST_HAS_TYPED_TEST
03137 
03138 template <typename T>
03139 class TypedTest : public Test {
03140 };
03141 
03142 typedef testing::Types<int, double> NumericTypes;
03143 TYPED_TEST_CASE(TypedTest, NumericTypes);
03144 
03145 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
03146   FAIL() << "Unexpected failure: Disabled typed test should not run.";
03147 }
03148 
03149 template <typename T>
03150 class DISABLED_TypedTest : public Test {
03151 };
03152 
03153 TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
03154 
03155 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
03156   FAIL() << "Unexpected failure: Disabled typed test should not run.";
03157 }
03158 
03159 #endif  // GTEST_HAS_TYPED_TEST
03160 
03161 // Tests that disabled type-parameterized tests aren't run.
03162 
03163 #if GTEST_HAS_TYPED_TEST_P
03164 
03165 template <typename T>
03166 class TypedTestP : public Test {
03167 };
03168 
03169 TYPED_TEST_CASE_P(TypedTestP);
03170 
03171 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
03172   FAIL() << "Unexpected failure: "
03173          << "Disabled type-parameterized test should not run.";
03174 }
03175 
03176 REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
03177 
03178 INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
03179 
03180 template <typename T>
03181 class DISABLED_TypedTestP : public Test {
03182 };
03183 
03184 TYPED_TEST_CASE_P(DISABLED_TypedTestP);
03185 
03186 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
03187   FAIL() << "Unexpected failure: "
03188          << "Disabled type-parameterized test should not run.";
03189 }
03190 
03191 REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
03192 
03193 INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
03194 
03195 #endif  // GTEST_HAS_TYPED_TEST_P
03196 
03197 // Tests that assertion macros evaluate their arguments exactly once.
03198 
03199 class SingleEvaluationTest : public Test {
03200  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
03201   // This helper function is needed by the FailedASSERT_STREQ test
03202   // below.  It's public to work around C++Builder's bug with scoping local
03203   // classes.
03204   static void CompareAndIncrementCharPtrs() {
03205     ASSERT_STREQ(p1_++, p2_++);
03206   }
03207 
03208   // This helper function is needed by the FailedASSERT_NE test below.  It's
03209   // public to work around C++Builder's bug with scoping local classes.
03210   static void CompareAndIncrementInts() {
03211     ASSERT_NE(a_++, b_++);
03212   }
03213 
03214  protected:
03215   SingleEvaluationTest() {
03216     p1_ = s1_;
03217     p2_ = s2_;
03218     a_ = 0;
03219     b_ = 0;
03220   }
03221 
03222   static const char* const s1_;
03223   static const char* const s2_;
03224   static const char* p1_;
03225   static const char* p2_;
03226 
03227   static int a_;
03228   static int b_;
03229 };
03230 
03231 const char* const SingleEvaluationTest::s1_ = "01234";
03232 const char* const SingleEvaluationTest::s2_ = "abcde";
03233 const char* SingleEvaluationTest::p1_;
03234 const char* SingleEvaluationTest::p2_;
03235 int SingleEvaluationTest::a_;
03236 int SingleEvaluationTest::b_;
03237 
03238 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
03239 // exactly once.
03240 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
03241   EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
03242                        "p2_++");
03243   EXPECT_EQ(s1_ + 1, p1_);
03244   EXPECT_EQ(s2_ + 1, p2_);
03245 }
03246 
03247 // Tests that string assertion arguments are evaluated exactly once.
03248 TEST_F(SingleEvaluationTest, ASSERT_STR) {
03249   // successful EXPECT_STRNE
03250   EXPECT_STRNE(p1_++, p2_++);
03251   EXPECT_EQ(s1_ + 1, p1_);
03252   EXPECT_EQ(s2_ + 1, p2_);
03253 
03254   // failed EXPECT_STRCASEEQ
03255   EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
03256                           "ignoring case");
03257   EXPECT_EQ(s1_ + 2, p1_);
03258   EXPECT_EQ(s2_ + 2, p2_);
03259 }
03260 
03261 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
03262 // once.
03263 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
03264   EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
03265                        "(a_++) != (b_++)");
03266   EXPECT_EQ(1, a_);
03267   EXPECT_EQ(1, b_);
03268 }
03269 
03270 // Tests that assertion arguments are evaluated exactly once.
03271 TEST_F(SingleEvaluationTest, OtherCases) {
03272   // successful EXPECT_TRUE
03273   EXPECT_TRUE(0 == a_++);  // NOLINT
03274   EXPECT_EQ(1, a_);
03275 
03276   // failed EXPECT_TRUE
03277   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
03278   EXPECT_EQ(2, a_);
03279 
03280   // successful EXPECT_GT
03281   EXPECT_GT(a_++, b_++);
03282   EXPECT_EQ(3, a_);
03283   EXPECT_EQ(1, b_);
03284 
03285   // failed EXPECT_LT
03286   EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
03287   EXPECT_EQ(4, a_);
03288   EXPECT_EQ(2, b_);
03289 
03290   // successful ASSERT_TRUE
03291   ASSERT_TRUE(0 < a_++);  // NOLINT
03292   EXPECT_EQ(5, a_);
03293 
03294   // successful ASSERT_GT
03295   ASSERT_GT(a_++, b_++);
03296   EXPECT_EQ(6, a_);
03297   EXPECT_EQ(3, b_);
03298 }
03299 
03300 #if GTEST_HAS_EXCEPTIONS
03301 
03302 void ThrowAnInteger() {
03303   throw 1;
03304 }
03305 
03306 // Tests that assertion arguments are evaluated exactly once.
03307 TEST_F(SingleEvaluationTest, ExceptionTests) {
03308   // successful EXPECT_THROW
03309   EXPECT_THROW({  // NOLINT
03310     a_++;
03311     ThrowAnInteger();
03312   }, int);
03313   EXPECT_EQ(1, a_);
03314 
03315   // failed EXPECT_THROW, throws different
03316   EXPECT_NONFATAL_FAILURE(EXPECT_THROW({  // NOLINT
03317     a_++;
03318     ThrowAnInteger();
03319   }, bool), "throws a different type");
03320   EXPECT_EQ(2, a_);
03321 
03322   // failed EXPECT_THROW, throws nothing
03323   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
03324   EXPECT_EQ(3, a_);
03325 
03326   // successful EXPECT_NO_THROW
03327   EXPECT_NO_THROW(a_++);
03328   EXPECT_EQ(4, a_);
03329 
03330   // failed EXPECT_NO_THROW
03331   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({  // NOLINT
03332     a_++;
03333     ThrowAnInteger();
03334   }), "it throws");
03335   EXPECT_EQ(5, a_);
03336 
03337   // successful EXPECT_ANY_THROW
03338   EXPECT_ANY_THROW({  // NOLINT
03339     a_++;
03340     ThrowAnInteger();
03341   });
03342   EXPECT_EQ(6, a_);
03343 
03344   // failed EXPECT_ANY_THROW
03345   EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
03346   EXPECT_EQ(7, a_);
03347 }
03348 
03349 #endif  // GTEST_HAS_EXCEPTIONS
03350 
03351 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
03352 class NoFatalFailureTest : public Test {
03353  protected:
03354   void Succeeds() {}
03355   void FailsNonFatal() {
03356     ADD_FAILURE() << "some non-fatal failure";
03357   }
03358   void Fails() {
03359     FAIL() << "some fatal failure";
03360   }
03361 
03362   void DoAssertNoFatalFailureOnFails() {
03363     ASSERT_NO_FATAL_FAILURE(Fails());
03364     ADD_FAILURE() << "shold not reach here.";
03365   }
03366 
03367   void DoExpectNoFatalFailureOnFails() {
03368     EXPECT_NO_FATAL_FAILURE(Fails());
03369     ADD_FAILURE() << "other failure";
03370   }
03371 };
03372 
03373 TEST_F(NoFatalFailureTest, NoFailure) {
03374   EXPECT_NO_FATAL_FAILURE(Succeeds());
03375   ASSERT_NO_FATAL_FAILURE(Succeeds());
03376 }
03377 
03378 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
03379   EXPECT_NONFATAL_FAILURE(
03380       EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
03381       "some non-fatal failure");
03382   EXPECT_NONFATAL_FAILURE(
03383       ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
03384       "some non-fatal failure");
03385 }
03386 
03387 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
03388   TestPartResultArray gtest_failures;
03389   {
03390     ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
03391     DoAssertNoFatalFailureOnFails();
03392   }
03393   ASSERT_EQ(2, gtest_failures.size());
03394   EXPECT_EQ(TestPartResult::kFatalFailure,
03395             gtest_failures.GetTestPartResult(0).type());
03396   EXPECT_EQ(TestPartResult::kFatalFailure,
03397             gtest_failures.GetTestPartResult(1).type());
03398   EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
03399                       gtest_failures.GetTestPartResult(0).message());
03400   EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
03401                       gtest_failures.GetTestPartResult(1).message());
03402 }
03403 
03404 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
03405   TestPartResultArray gtest_failures;
03406   {
03407     ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
03408     DoExpectNoFatalFailureOnFails();
03409   }
03410   ASSERT_EQ(3, gtest_failures.size());
03411   EXPECT_EQ(TestPartResult::kFatalFailure,
03412             gtest_failures.GetTestPartResult(0).type());
03413   EXPECT_EQ(TestPartResult::kNonFatalFailure,
03414             gtest_failures.GetTestPartResult(1).type());
03415   EXPECT_EQ(TestPartResult::kNonFatalFailure,
03416             gtest_failures.GetTestPartResult(2).type());
03417   EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
03418                       gtest_failures.GetTestPartResult(0).message());
03419   EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
03420                       gtest_failures.GetTestPartResult(1).message());
03421   EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
03422                       gtest_failures.GetTestPartResult(2).message());
03423 }
03424 
03425 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
03426   TestPartResultArray gtest_failures;
03427   {
03428     ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
03429     EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
03430   }
03431   ASSERT_EQ(2, gtest_failures.size());
03432   EXPECT_EQ(TestPartResult::kNonFatalFailure,
03433             gtest_failures.GetTestPartResult(0).type());
03434   EXPECT_EQ(TestPartResult::kNonFatalFailure,
03435             gtest_failures.GetTestPartResult(1).type());
03436   EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
03437                       gtest_failures.GetTestPartResult(0).message());
03438   EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
03439                       gtest_failures.GetTestPartResult(1).message());
03440 }
03441 
03442 // Tests non-string assertions.
03443 
03444 // Tests EqFailure(), used for implementing *EQ* assertions.
03445 TEST(AssertionTest, EqFailure) {
03446   const std::string foo_val("5"), bar_val("6");
03447   const std::string msg1(
03448       EqFailure("foo", "bar", foo_val, bar_val, false)
03449       .failure_message());
03450   EXPECT_STREQ(
03451       "Value of: bar\n"
03452       "  Actual: 6\n"
03453       "Expected: foo\n"
03454       "Which is: 5",
03455       msg1.c_str());
03456 
03457   const std::string msg2(
03458       EqFailure("foo", "6", foo_val, bar_val, false)
03459       .failure_message());
03460   EXPECT_STREQ(
03461       "Value of: 6\n"
03462       "Expected: foo\n"
03463       "Which is: 5",
03464       msg2.c_str());
03465 
03466   const std::string msg3(
03467       EqFailure("5", "bar", foo_val, bar_val, false)
03468       .failure_message());
03469   EXPECT_STREQ(
03470       "Value of: bar\n"
03471       "  Actual: 6\n"
03472       "Expected: 5",
03473       msg3.c_str());
03474 
03475   const std::string msg4(
03476       EqFailure("5", "6", foo_val, bar_val, false).failure_message());
03477   EXPECT_STREQ(
03478       "Value of: 6\n"
03479       "Expected: 5",
03480       msg4.c_str());
03481 
03482   const std::string msg5(
03483       EqFailure("foo", "bar",
03484                 std::string("\"x\""), std::string("\"y\""),
03485                 true).failure_message());
03486   EXPECT_STREQ(
03487       "Value of: bar\n"
03488       "  Actual: \"y\"\n"
03489       "Expected: foo (ignoring case)\n"
03490       "Which is: \"x\"",
03491       msg5.c_str());
03492 }
03493 
03494 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
03495 TEST(AssertionTest, AppendUserMessage) {
03496   const std::string foo("foo");
03497 
03498   Message msg;
03499   EXPECT_STREQ("foo",
03500                AppendUserMessage(foo, msg).c_str());
03501 
03502   msg << "bar";
03503   EXPECT_STREQ("foo\nbar",
03504                AppendUserMessage(foo, msg).c_str());
03505 }
03506 
03507 #ifdef __BORLANDC__
03508 // Silences warnings: "Condition is always true", "Unreachable code"
03509 # pragma option push -w-ccc -w-rch
03510 #endif
03511 
03512 // Tests ASSERT_TRUE.
03513 TEST(AssertionTest, ASSERT_TRUE) {
03514   ASSERT_TRUE(2 > 1);  // NOLINT
03515   EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
03516                        "2 < 1");
03517 }
03518 
03519 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
03520 TEST(AssertionTest, AssertTrueWithAssertionResult) {
03521   ASSERT_TRUE(ResultIsEven(2));
03522 #ifndef __BORLANDC__
03523   // ICE's in C++Builder.
03524   EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
03525                        "Value of: ResultIsEven(3)\n"
03526                        "  Actual: false (3 is odd)\n"
03527                        "Expected: true");
03528 #endif
03529   ASSERT_TRUE(ResultIsEvenNoExplanation(2));
03530   EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
03531                        "Value of: ResultIsEvenNoExplanation(3)\n"
03532                        "  Actual: false (3 is odd)\n"
03533                        "Expected: true");
03534 }
03535 
03536 // Tests ASSERT_FALSE.
03537 TEST(AssertionTest, ASSERT_FALSE) {
03538   ASSERT_FALSE(2 < 1);  // NOLINT
03539   EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
03540                        "Value of: 2 > 1\n"
03541                        "  Actual: true\n"
03542                        "Expected: false");
03543 }
03544 
03545 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
03546 TEST(AssertionTest, AssertFalseWithAssertionResult) {
03547   ASSERT_FALSE(ResultIsEven(3));
03548 #ifndef __BORLANDC__
03549   // ICE's in C++Builder.
03550   EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
03551                        "Value of: ResultIsEven(2)\n"
03552                        "  Actual: true (2 is even)\n"
03553                        "Expected: false");
03554 #endif
03555   ASSERT_FALSE(ResultIsEvenNoExplanation(3));
03556   EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
03557                        "Value of: ResultIsEvenNoExplanation(2)\n"
03558                        "  Actual: true\n"
03559                        "Expected: false");
03560 }
03561 
03562 #ifdef __BORLANDC__
03563 // Restores warnings after previous "#pragma option push" supressed them
03564 # pragma option pop
03565 #endif
03566 
03567 // Tests using ASSERT_EQ on double values.  The purpose is to make
03568 // sure that the specialization we did for integer and anonymous enums
03569 // isn't used for double arguments.
03570 TEST(ExpectTest, ASSERT_EQ_Double) {
03571   // A success.
03572   ASSERT_EQ(5.6, 5.6);
03573 
03574   // A failure.
03575   EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
03576                        "5.1");
03577 }
03578 
03579 // Tests ASSERT_EQ.
03580 TEST(AssertionTest, ASSERT_EQ) {
03581   ASSERT_EQ(5, 2 + 3);
03582   EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
03583                        "Value of: 2*3\n"
03584                        "  Actual: 6\n"
03585                        "Expected: 5");
03586 }
03587 
03588 // Tests ASSERT_EQ(NULL, pointer).
03589 #if GTEST_CAN_COMPARE_NULL
03590 TEST(AssertionTest, ASSERT_EQ_NULL) {
03591   // A success.
03592   const char* p = NULL;
03593   // Some older GCC versions may issue a spurious waring in this or the next
03594   // assertion statement. This warning should not be suppressed with
03595   // static_cast since the test verifies the ability to use bare NULL as the
03596   // expected parameter to the macro.
03597   ASSERT_EQ(NULL, p);
03598 
03599   // A failure.
03600   static int n = 0;
03601   EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
03602                        "Value of: &n\n");
03603 }
03604 #endif  // GTEST_CAN_COMPARE_NULL
03605 
03606 // Tests ASSERT_EQ(0, non_pointer).  Since the literal 0 can be
03607 // treated as a null pointer by the compiler, we need to make sure
03608 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
03609 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
03610 TEST(ExpectTest, ASSERT_EQ_0) {
03611   int n = 0;
03612 
03613   // A success.
03614   ASSERT_EQ(0, n);
03615 
03616   // A failure.
03617   EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
03618                        "Expected: 0");
03619 }
03620 
03621 // Tests ASSERT_NE.
03622 TEST(AssertionTest, ASSERT_NE) {
03623   ASSERT_NE(6, 7);
03624   EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
03625                        "Expected: ('a') != ('a'), "
03626                        "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
03627 }
03628 
03629 // Tests ASSERT_LE.
03630 TEST(AssertionTest, ASSERT_LE) {
03631   ASSERT_LE(2, 3);
03632   ASSERT_LE(2, 2);
03633   EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
03634                        "Expected: (2) <= (0), actual: 2 vs 0");
03635 }
03636 
03637 // Tests ASSERT_LT.
03638 TEST(AssertionTest, ASSERT_LT) {
03639   ASSERT_LT(2, 3);
03640   EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
03641                        "Expected: (2) < (2), actual: 2 vs 2");
03642 }
03643 
03644 // Tests ASSERT_GE.
03645 TEST(AssertionTest, ASSERT_GE) {
03646   ASSERT_GE(2, 1);
03647   ASSERT_GE(2, 2);
03648   EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
03649                        "Expected: (2) >= (3), actual: 2 vs 3");
03650 }
03651 
03652 // Tests ASSERT_GT.
03653 TEST(AssertionTest, ASSERT_GT) {
03654   ASSERT_GT(2, 1);
03655   EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
03656                        "Expected: (2) > (2), actual: 2 vs 2");
03657 }
03658 
03659 #if GTEST_HAS_EXCEPTIONS
03660 
03661 void ThrowNothing() {}
03662 
03663 // Tests ASSERT_THROW.
03664 TEST(AssertionTest, ASSERT_THROW) {
03665   ASSERT_THROW(ThrowAnInteger(), int);
03666 
03667 # ifndef __BORLANDC__
03668 
03669   // ICE's in C++Builder 2007 and 2009.
03670   EXPECT_FATAL_FAILURE(
03671       ASSERT_THROW(ThrowAnInteger(), bool),
03672       "Expected: ThrowAnInteger() throws an exception of type bool.\n"
03673       "  Actual: it throws a different type.");
03674 # endif
03675 
03676   EXPECT_FATAL_FAILURE(
03677       ASSERT_THROW(ThrowNothing(), bool),
03678       "Expected: ThrowNothing() throws an exception of type bool.\n"
03679       "  Actual: it throws nothing.");
03680 }
03681 
03682 // Tests ASSERT_NO_THROW.
03683 TEST(AssertionTest, ASSERT_NO_THROW) {
03684   ASSERT_NO_THROW(ThrowNothing());
03685   EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
03686                        "Expected: ThrowAnInteger() doesn't throw an exception."
03687                        "\n  Actual: it throws.");
03688 }
03689 
03690 // Tests ASSERT_ANY_THROW.
03691 TEST(AssertionTest, ASSERT_ANY_THROW) {
03692   ASSERT_ANY_THROW(ThrowAnInteger());
03693   EXPECT_FATAL_FAILURE(
03694       ASSERT_ANY_THROW(ThrowNothing()),
03695       "Expected: ThrowNothing() throws an exception.\n"
03696       "  Actual: it doesn't.");
03697 }
03698 
03699 #endif  // GTEST_HAS_EXCEPTIONS
03700 
03701 // Makes sure we deal with the precedence of <<.  This test should
03702 // compile.
03703 TEST(AssertionTest, AssertPrecedence) {
03704   ASSERT_EQ(1 < 2, true);
03705   bool false_value = false;
03706   ASSERT_EQ(true && false_value, false);
03707 }
03708 
03709 // A subroutine used by the following test.
03710 void TestEq1(int x) {
03711   ASSERT_EQ(1, x);
03712 }
03713 
03714 // Tests calling a test subroutine that's not part of a fixture.
03715 TEST(AssertionTest, NonFixtureSubroutine) {
03716   EXPECT_FATAL_FAILURE(TestEq1(2),
03717                        "Value of: x");
03718 }
03719 
03720 // An uncopyable class.
03721 class Uncopyable {
03722  public:
03723   explicit Uncopyable(int a_value) : value_(a_value) {}
03724 
03725   int value() const { return value_; }
03726   bool operator==(const Uncopyable& rhs) const {
03727     return value() == rhs.value();
03728   }
03729  private:
03730   // This constructor deliberately has no implementation, as we don't
03731   // want this class to be copyable.
03732   Uncopyable(const Uncopyable&);  // NOLINT
03733 
03734   int value_;
03735 };
03736 
03737 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
03738   return os << value.value();
03739 }
03740 
03741 
03742 bool IsPositiveUncopyable(const Uncopyable& x) {
03743   return x.value() > 0;
03744 }
03745 
03746 // A subroutine used by the following test.
03747 void TestAssertNonPositive() {
03748   Uncopyable y(-1);
03749   ASSERT_PRED1(IsPositiveUncopyable, y);
03750 }
03751 // A subroutine used by the following test.
03752 void TestAssertEqualsUncopyable() {
03753   Uncopyable x(5);
03754   Uncopyable y(-1);
03755   ASSERT_EQ(x, y);
03756 }
03757 
03758 // Tests that uncopyable objects can be used in assertions.
03759 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
03760   Uncopyable x(5);
03761   ASSERT_PRED1(IsPositiveUncopyable, x);
03762   ASSERT_EQ(x, x);
03763   EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
03764     "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
03765   EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
03766     "Value of: y\n  Actual: -1\nExpected: x\nWhich is: 5");
03767 }
03768 
03769 // Tests that uncopyable objects can be used in expects.
03770 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
03771   Uncopyable x(5);
03772   EXPECT_PRED1(IsPositiveUncopyable, x);
03773   Uncopyable y(-1);
03774   EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
03775     "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
03776   EXPECT_EQ(x, x);
03777   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
03778     "Value of: y\n  Actual: -1\nExpected: x\nWhich is: 5");
03779 }
03780 
03781 enum NamedEnum {
03782   kE1 = 0,
03783   kE2 = 1
03784 };
03785 
03786 TEST(AssertionTest, NamedEnum) {
03787   EXPECT_EQ(kE1, kE1);
03788   EXPECT_LT(kE1, kE2);
03789   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
03790   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1");
03791 }
03792 
03793 // The version of gcc used in XCode 2.2 has a bug and doesn't allow
03794 // anonymous enums in assertions.  Therefore the following test is not
03795 // done on Mac.
03796 // Sun Studio and HP aCC also reject this code.
03797 #if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC)
03798 
03799 // Tests using assertions with anonymous enums.
03800 enum {
03801   kCaseA = -1,
03802 
03803 # if GTEST_OS_LINUX
03804 
03805   // We want to test the case where the size of the anonymous enum is
03806   // larger than sizeof(int), to make sure our implementation of the
03807   // assertions doesn't truncate the enums.  However, MSVC
03808   // (incorrectly) doesn't allow an enum value to exceed the range of
03809   // an int, so this has to be conditionally compiled.
03810   //
03811   // On Linux, kCaseB and kCaseA have the same value when truncated to
03812   // int size.  We want to test whether this will confuse the
03813   // assertions.
03814   kCaseB = testing::internal::kMaxBiggestInt,
03815 
03816 # else
03817 
03818   kCaseB = INT_MAX,
03819 
03820 # endif  // GTEST_OS_LINUX
03821 
03822   kCaseC = 42
03823 };
03824 
03825 TEST(AssertionTest, AnonymousEnum) {
03826 # if GTEST_OS_LINUX
03827 
03828   EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
03829 
03830 # endif  // GTEST_OS_LINUX
03831 
03832   EXPECT_EQ(kCaseA, kCaseA);
03833   EXPECT_NE(kCaseA, kCaseB);
03834   EXPECT_LT(kCaseA, kCaseB);
03835   EXPECT_LE(kCaseA, kCaseB);
03836   EXPECT_GT(kCaseB, kCaseA);
03837   EXPECT_GE(kCaseA, kCaseA);
03838   EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
03839                           "(kCaseA) >= (kCaseB)");
03840   EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
03841                           "-1 vs 42");
03842 
03843   ASSERT_EQ(kCaseA, kCaseA);
03844   ASSERT_NE(kCaseA, kCaseB);
03845   ASSERT_LT(kCaseA, kCaseB);
03846   ASSERT_LE(kCaseA, kCaseB);
03847   ASSERT_GT(kCaseB, kCaseA);
03848   ASSERT_GE(kCaseA, kCaseA);
03849 
03850 # ifndef __BORLANDC__
03851 
03852   // ICE's in C++Builder.
03853   EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
03854                        "Value of: kCaseB");
03855   EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
03856                        "Actual: 42");
03857 # endif
03858 
03859   EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
03860                        "Which is: -1");
03861 }
03862 
03863 #endif  // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
03864 
03865 #if GTEST_OS_WINDOWS
03866 
03867 static HRESULT UnexpectedHRESULTFailure() {
03868   return E_UNEXPECTED;
03869 }
03870 
03871 static HRESULT OkHRESULTSuccess() {
03872   return S_OK;
03873 }
03874 
03875 static HRESULT FalseHRESULTSuccess() {
03876   return S_FALSE;
03877 }
03878 
03879 // HRESULT assertion tests test both zero and non-zero
03880 // success codes as well as failure message for each.
03881 //
03882 // Windows CE doesn't support message texts.
03883 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
03884   EXPECT_HRESULT_SUCCEEDED(S_OK);
03885   EXPECT_HRESULT_SUCCEEDED(S_FALSE);
03886 
03887   EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
03888     "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
03889     "  Actual: 0x8000FFFF");
03890 }
03891 
03892 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
03893   ASSERT_HRESULT_SUCCEEDED(S_OK);
03894   ASSERT_HRESULT_SUCCEEDED(S_FALSE);
03895 
03896   EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
03897     "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
03898     "  Actual: 0x8000FFFF");
03899 }
03900 
03901 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
03902   EXPECT_HRESULT_FAILED(E_UNEXPECTED);
03903 
03904   EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
03905     "Expected: (OkHRESULTSuccess()) fails.\n"
03906     "  Actual: 0x0");
03907   EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
03908     "Expected: (FalseHRESULTSuccess()) fails.\n"
03909     "  Actual: 0x1");
03910 }
03911 
03912 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
03913   ASSERT_HRESULT_FAILED(E_UNEXPECTED);
03914 
03915 # ifndef __BORLANDC__
03916 
03917   // ICE's in C++Builder 2007 and 2009.
03918   EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
03919     "Expected: (OkHRESULTSuccess()) fails.\n"
03920     "  Actual: 0x0");
03921 # endif
03922 
03923   EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
03924     "Expected: (FalseHRESULTSuccess()) fails.\n"
03925     "  Actual: 0x1");
03926 }
03927 
03928 // Tests that streaming to the HRESULT macros works.
03929 TEST(HRESULTAssertionTest, Streaming) {
03930   EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
03931   ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
03932   EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
03933   ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
03934 
03935   EXPECT_NONFATAL_FAILURE(
03936       EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
03937       "expected failure");
03938 
03939 # ifndef __BORLANDC__
03940 
03941   // ICE's in C++Builder 2007 and 2009.
03942   EXPECT_FATAL_FAILURE(
03943       ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
03944       "expected failure");
03945 # endif
03946 
03947   EXPECT_NONFATAL_FAILURE(
03948       EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
03949       "expected failure");
03950 
03951   EXPECT_FATAL_FAILURE(
03952       ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
03953       "expected failure");
03954 }
03955 
03956 #endif  // GTEST_OS_WINDOWS
03957 
03958 #ifdef __BORLANDC__
03959 // Silences warnings: "Condition is always true", "Unreachable code"
03960 # pragma option push -w-ccc -w-rch
03961 #endif
03962 
03963 // Tests that the assertion macros behave like single statements.
03964 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
03965   if (AlwaysFalse())
03966     ASSERT_TRUE(false) << "This should never be executed; "
03967                           "It's a compilation test only.";
03968 
03969   if (AlwaysTrue())
03970     EXPECT_FALSE(false);
03971   else
03972     ;  // NOLINT
03973 
03974   if (AlwaysFalse())
03975     ASSERT_LT(1, 3);
03976 
03977   if (AlwaysFalse())
03978     ;  // NOLINT
03979   else
03980     EXPECT_GT(3, 2) << "";
03981 }
03982 
03983 #if GTEST_HAS_EXCEPTIONS
03984 // Tests that the compiler will not complain about unreachable code in the
03985 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
03986 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
03987   int n = 0;
03988 
03989   EXPECT_THROW(throw 1, int);
03990   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
03991   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
03992   EXPECT_NO_THROW(n++);
03993   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
03994   EXPECT_ANY_THROW(throw 1);
03995   EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
03996 }
03997 
03998 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
03999   if (AlwaysFalse())
04000     EXPECT_THROW(ThrowNothing(), bool);
04001 
04002   if (AlwaysTrue())
04003     EXPECT_THROW(ThrowAnInteger(), int);
04004   else
04005     ;  // NOLINT
04006 
04007   if (AlwaysFalse())
04008     EXPECT_NO_THROW(ThrowAnInteger());
04009 
04010   if (AlwaysTrue())
04011     EXPECT_NO_THROW(ThrowNothing());
04012   else
04013     ;  // NOLINT
04014 
04015   if (AlwaysFalse())
04016     EXPECT_ANY_THROW(ThrowNothing());
04017 
04018   if (AlwaysTrue())
04019     EXPECT_ANY_THROW(ThrowAnInteger());
04020   else
04021     ;  // NOLINT
04022 }
04023 #endif  // GTEST_HAS_EXCEPTIONS
04024 
04025 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
04026   if (AlwaysFalse())
04027     EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
04028                                     << "It's a compilation test only.";
04029   else
04030     ;  // NOLINT
04031 
04032   if (AlwaysFalse())
04033     ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
04034   else
04035     ;  // NOLINT
04036 
04037   if (AlwaysTrue())
04038     EXPECT_NO_FATAL_FAILURE(SUCCEED());
04039   else
04040     ;  // NOLINT
04041 
04042   if (AlwaysFalse())
04043     ;  // NOLINT
04044   else
04045     ASSERT_NO_FATAL_FAILURE(SUCCEED());
04046 }
04047 
04048 // Tests that the assertion macros work well with switch statements.
04049 TEST(AssertionSyntaxTest, WorksWithSwitch) {
04050   switch (0) {
04051     case 1:
04052       break;
04053     default:
04054       ASSERT_TRUE(true);
04055   }
04056 
04057   switch (0)
04058     case 0:
04059       EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
04060 
04061   // Binary assertions are implemented using a different code path
04062   // than the Boolean assertions.  Hence we test them separately.
04063   switch (0) {
04064     case 1:
04065     default:
04066       ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
04067   }
04068 
04069   switch (0)
04070     case 0:
04071       EXPECT_NE(1, 2);
04072 }
04073 
04074 #if GTEST_HAS_EXCEPTIONS
04075 
04076 void ThrowAString() {
04077     throw "std::string";
04078 }
04079 
04080 // Test that the exception assertion macros compile and work with const
04081 // type qualifier.
04082 TEST(AssertionSyntaxTest, WorksWithConst) {
04083     ASSERT_THROW(ThrowAString(), const char*);
04084 
04085     EXPECT_THROW(ThrowAString(), const char*);
04086 }
04087 
04088 #endif  // GTEST_HAS_EXCEPTIONS
04089 
04090 }  // namespace
04091 
04092 namespace testing {
04093 
04094 // Tests that Google Test tracks SUCCEED*.
04095 TEST(SuccessfulAssertionTest, SUCCEED) {
04096   SUCCEED();
04097   SUCCEED() << "OK";
04098   EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
04099 }
04100 
04101 // Tests that Google Test doesn't track successful EXPECT_*.
04102 TEST(SuccessfulAssertionTest, EXPECT) {
04103   EXPECT_TRUE(true);
04104   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
04105 }
04106 
04107 // Tests that Google Test doesn't track successful EXPECT_STR*.
04108 TEST(SuccessfulAssertionTest, EXPECT_STR) {
04109   EXPECT_STREQ("", "");
04110   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
04111 }
04112 
04113 // Tests that Google Test doesn't track successful ASSERT_*.
04114 TEST(SuccessfulAssertionTest, ASSERT) {
04115   ASSERT_TRUE(true);
04116   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
04117 }
04118 
04119 // Tests that Google Test doesn't track successful ASSERT_STR*.
04120 TEST(SuccessfulAssertionTest, ASSERT_STR) {
04121   ASSERT_STREQ("", "");
04122   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
04123 }
04124 
04125 }  // namespace testing
04126 
04127 namespace {
04128 
04129 // Tests the message streaming variation of assertions.
04130 
04131 TEST(AssertionWithMessageTest, EXPECT) {
04132   EXPECT_EQ(1, 1) << "This should succeed.";
04133   EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
04134                           "Expected failure #1");
04135   EXPECT_LE(1, 2) << "This should succeed.";
04136   EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
04137                           "Expected failure #2.");
04138   EXPECT_GE(1, 0) << "This should succeed.";
04139   EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
04140                           "Expected failure #3.");
04141 
04142   EXPECT_STREQ("1", "1") << "This should succeed.";
04143   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
04144                           "Expected failure #4.");
04145   EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
04146   EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
04147                           "Expected failure #5.");
04148 
04149   EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
04150   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
04151                           "Expected failure #6.");
04152   EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
04153 }
04154 
04155 TEST(AssertionWithMessageTest, ASSERT) {
04156   ASSERT_EQ(1, 1) << "This should succeed.";
04157   ASSERT_NE(1, 2) << "This should succeed.";
04158   ASSERT_LE(1, 2) << "This should succeed.";
04159   ASSERT_LT(1, 2) << "This should succeed.";
04160   ASSERT_GE(1, 0) << "This should succeed.";
04161   EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
04162                        "Expected failure.");
04163 }
04164 
04165 TEST(AssertionWithMessageTest, ASSERT_STR) {
04166   ASSERT_STREQ("1", "1") << "This should succeed.";
04167   ASSERT_STRNE("1", "2") << "This should succeed.";
04168   ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
04169   EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
04170                        "Expected failure.");
04171 }
04172 
04173 TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
04174   ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
04175   ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
04176   EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.",  // NOLINT
04177                        "Expect failure.");
04178   // To work around a bug in gcc 2.95.0, there is intentionally no
04179   // space after the first comma in the previous statement.
04180 }
04181 
04182 // Tests using ASSERT_FALSE with a streamed message.
04183 TEST(AssertionWithMessageTest, ASSERT_FALSE) {
04184   ASSERT_FALSE(false) << "This shouldn't fail.";
04185   EXPECT_FATAL_FAILURE({  // NOLINT
04186     ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
04187                        << " evaluates to " << true;
04188   }, "Expected failure");
04189 }
04190 
04191 // Tests using FAIL with a streamed message.
04192 TEST(AssertionWithMessageTest, FAIL) {
04193   EXPECT_FATAL_FAILURE(FAIL() << 0,
04194                        "0");
04195 }
04196 
04197 // Tests using SUCCEED with a streamed message.
04198 TEST(AssertionWithMessageTest, SUCCEED) {
04199   SUCCEED() << "Success == " << 1;
04200 }
04201 
04202 // Tests using ASSERT_TRUE with a streamed message.
04203 TEST(AssertionWithMessageTest, ASSERT_TRUE) {
04204   ASSERT_TRUE(true) << "This should succeed.";
04205   ASSERT_TRUE(true) << true;
04206   EXPECT_FATAL_FAILURE({  // NOLINT
04207     ASSERT_TRUE(false) << static_cast<const char *>(NULL)
04208                        << static_cast<char *>(NULL);
04209   }, "(null)(null)");
04210 }
04211 
04212 #if GTEST_OS_WINDOWS
04213 // Tests using wide strings in assertion messages.
04214 TEST(AssertionWithMessageTest, WideStringMessage) {
04215   EXPECT_NONFATAL_FAILURE({  // NOLINT
04216     EXPECT_TRUE(false) << L"This failure is expected.\x8119";
04217   }, "This failure is expected.");
04218   EXPECT_FATAL_FAILURE({  // NOLINT
04219     ASSERT_EQ(1, 2) << "This failure is "
04220                     << L"expected too.\x8120";
04221   }, "This failure is expected too.");
04222 }
04223 #endif  // GTEST_OS_WINDOWS
04224 
04225 // Tests EXPECT_TRUE.
04226 TEST(ExpectTest, EXPECT_TRUE) {
04227   EXPECT_TRUE(true) << "Intentional success";
04228   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
04229                           "Intentional failure #1.");
04230   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
04231                           "Intentional failure #2.");
04232   EXPECT_TRUE(2 > 1);  // NOLINT
04233   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
04234                           "Value of: 2 < 1\n"
04235                           "  Actual: false\n"
04236                           "Expected: true");
04237   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
04238                           "2 > 3");
04239 }
04240 
04241 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
04242 TEST(ExpectTest, ExpectTrueWithAssertionResult) {
04243   EXPECT_TRUE(ResultIsEven(2));
04244   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
04245                           "Value of: ResultIsEven(3)\n"
04246                           "  Actual: false (3 is odd)\n"
04247                           "Expected: true");
04248   EXPECT_TRUE(ResultIsEvenNoExplanation(2));
04249   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
04250                           "Value of: ResultIsEvenNoExplanation(3)\n"
04251                           "  Actual: false (3 is odd)\n"
04252                           "Expected: true");
04253 }
04254 
04255 // Tests EXPECT_FALSE with a streamed message.
04256 TEST(ExpectTest, EXPECT_FALSE) {
04257   EXPECT_FALSE(2 < 1);  // NOLINT
04258   EXPECT_FALSE(false) << "Intentional success";
04259   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
04260                           "Intentional failure #1.");
04261   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
04262                           "Intentional failure #2.");
04263   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
04264                           "Value of: 2 > 1\n"
04265                           "  Actual: true\n"
04266                           "Expected: false");
04267   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
04268                           "2 < 3");
04269 }
04270 
04271 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
04272 TEST(ExpectTest, ExpectFalseWithAssertionResult) {
04273   EXPECT_FALSE(ResultIsEven(3));
04274   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
04275                           "Value of: ResultIsEven(2)\n"
04276                           "  Actual: true (2 is even)\n"
04277                           "Expected: false");
04278   EXPECT_FALSE(ResultIsEvenNoExplanation(3));
04279   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
04280                           "Value of: ResultIsEvenNoExplanation(2)\n"
04281                           "  Actual: true\n"
04282                           "Expected: false");
04283 }
04284 
04285 #ifdef __BORLANDC__
04286 // Restores warnings after previous "#pragma option push" supressed them
04287 # pragma option pop
04288 #endif
04289 
04290 // Tests EXPECT_EQ.
04291 TEST(ExpectTest, EXPECT_EQ) {
04292   EXPECT_EQ(5, 2 + 3);
04293   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
04294                           "Value of: 2*3\n"
04295                           "  Actual: 6\n"
04296                           "Expected: 5");
04297   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
04298                           "2 - 3");
04299 }
04300 
04301 // Tests using EXPECT_EQ on double values.  The purpose is to make
04302 // sure that the specialization we did for integer and anonymous enums
04303 // isn't used for double arguments.
04304 TEST(ExpectTest, EXPECT_EQ_Double) {
04305   // A success.
04306   EXPECT_EQ(5.6, 5.6);
04307 
04308   // A failure.
04309   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
04310                           "5.1");
04311 }
04312 
04313 #if GTEST_CAN_COMPARE_NULL
04314 // Tests EXPECT_EQ(NULL, pointer).
04315 TEST(ExpectTest, EXPECT_EQ_NULL) {
04316   // A success.
04317   const char* p = NULL;
04318   // Some older GCC versions may issue a spurious warning in this or the next
04319   // assertion statement. This warning should not be suppressed with
04320   // static_cast since the test verifies the ability to use bare NULL as the
04321   // expected parameter to the macro.
04322   EXPECT_EQ(NULL, p);
04323 
04324   // A failure.
04325   int n = 0;
04326   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
04327                           "Value of: &n\n");
04328 }
04329 #endif  // GTEST_CAN_COMPARE_NULL
04330 
04331 // Tests EXPECT_EQ(0, non_pointer).  Since the literal 0 can be
04332 // treated as a null pointer by the compiler, we need to make sure
04333 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
04334 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
04335 TEST(ExpectTest, EXPECT_EQ_0) {
04336   int n = 0;
04337 
04338   // A success.
04339   EXPECT_EQ(0, n);
04340 
04341   // A failure.
04342   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
04343                           "Expected: 0");
04344 }
04345 
04346 // Tests EXPECT_NE.
04347 TEST(ExpectTest, EXPECT_NE) {
04348   EXPECT_NE(6, 7);
04349 
04350   EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
04351                           "Expected: ('a') != ('a'), "
04352                           "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
04353   EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
04354                           "2");
04355   char* const p0 = NULL;
04356   EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
04357                           "p0");
04358   // Only way to get the Nokia compiler to compile the cast
04359   // is to have a separate void* variable first. Putting
04360   // the two casts on the same line doesn't work, neither does
04361   // a direct C-style to char*.
04362   void* pv1 = (void*)0x1234;  // NOLINT
04363   char* const p1 = reinterpret_cast<char*>(pv1);
04364   EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
04365                           "p1");
04366 }
04367 
04368 // Tests EXPECT_LE.
04369 TEST(ExpectTest, EXPECT_LE) {
04370   EXPECT_LE(2, 3);
04371   EXPECT_LE(2, 2);
04372   EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
04373                           "Expected: (2) <= (0), actual: 2 vs 0");
04374   EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
04375                           "(1.1) <= (0.9)");
04376 }
04377 
04378 // Tests EXPECT_LT.
04379 TEST(ExpectTest, EXPECT_LT) {
04380   EXPECT_LT(2, 3);
04381   EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
04382                           "Expected: (2) < (2), actual: 2 vs 2");
04383   EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
04384                           "(2) < (1)");
04385 }
04386 
04387 // Tests EXPECT_GE.
04388 TEST(ExpectTest, EXPECT_GE) {
04389   EXPECT_GE(2, 1);
04390   EXPECT_GE(2, 2);
04391   EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
04392                           "Expected: (2) >= (3), actual: 2 vs 3");
04393   EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
04394                           "(0.9) >= (1.1)");
04395 }
04396 
04397 // Tests EXPECT_GT.
04398 TEST(ExpectTest, EXPECT_GT) {
04399   EXPECT_GT(2, 1);
04400   EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
04401                           "Expected: (2) > (2), actual: 2 vs 2");
04402   EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
04403                           "(2) > (3)");
04404 }
04405 
04406 #if GTEST_HAS_EXCEPTIONS
04407 
04408 // Tests EXPECT_THROW.
04409 TEST(ExpectTest, EXPECT_THROW) {
04410   EXPECT_THROW(ThrowAnInteger(), int);
04411   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
04412                           "Expected: ThrowAnInteger() throws an exception of "
04413                           "type bool.\n  Actual: it throws a different type.");
04414   EXPECT_NONFATAL_FAILURE(
04415       EXPECT_THROW(ThrowNothing(), bool),
04416       "Expected: ThrowNothing() throws an exception of type bool.\n"
04417       "  Actual: it throws nothing.");
04418 }
04419 
04420 // Tests EXPECT_NO_THROW.
04421 TEST(ExpectTest, EXPECT_NO_THROW) {
04422   EXPECT_NO_THROW(ThrowNothing());
04423   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
04424                           "Expected: ThrowAnInteger() doesn't throw an "
04425                           "exception.\n  Actual: it throws.");
04426 }
04427 
04428 // Tests EXPECT_ANY_THROW.
04429 TEST(ExpectTest, EXPECT_ANY_THROW) {
04430   EXPECT_ANY_THROW(ThrowAnInteger());
04431   EXPECT_NONFATAL_FAILURE(
04432       EXPECT_ANY_THROW(ThrowNothing()),
04433       "Expected: ThrowNothing() throws an exception.\n"
04434       "  Actual: it doesn't.");
04435 }
04436 
04437 #endif  // GTEST_HAS_EXCEPTIONS
04438 
04439 // Make sure we deal with the precedence of <<.
04440 TEST(ExpectTest, ExpectPrecedence) {
04441   EXPECT_EQ(1 < 2, true);
04442   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
04443                           "Value of: true && false");
04444 }
04445 
04446 
04447 // Tests the StreamableToString() function.
04448 
04449 // Tests using StreamableToString() on a scalar.
04450 TEST(StreamableToStringTest, Scalar) {
04451   EXPECT_STREQ("5", StreamableToString(5).c_str());
04452 }
04453 
04454 // Tests using StreamableToString() on a non-char pointer.
04455 TEST(StreamableToStringTest, Pointer) {
04456   int n = 0;
04457   int* p = &n;
04458   EXPECT_STRNE("(null)", StreamableToString(p).c_str());
04459 }
04460 
04461 // Tests using StreamableToString() on a NULL non-char pointer.
04462 TEST(StreamableToStringTest, NullPointer) {
04463   int* p = NULL;
04464   EXPECT_STREQ("(null)", StreamableToString(p).c_str());
04465 }
04466 
04467 // Tests using StreamableToString() on a C string.
04468 TEST(StreamableToStringTest, CString) {
04469   EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
04470 }
04471 
04472 // Tests using StreamableToString() on a NULL C string.
04473 TEST(StreamableToStringTest, NullCString) {
04474   char* p = NULL;
04475   EXPECT_STREQ("(null)", StreamableToString(p).c_str());
04476 }
04477 
04478 // Tests using streamable values as assertion messages.
04479 
04480 // Tests using std::string as an assertion message.
04481 TEST(StreamableTest, string) {
04482   static const std::string str(
04483       "This failure message is a std::string, and is expected.");
04484   EXPECT_FATAL_FAILURE(FAIL() << str,
04485                        str.c_str());
04486 }
04487 
04488 // Tests that we can output strings containing embedded NULs.
04489 // Limited to Linux because we can only do this with std::string's.
04490 TEST(StreamableTest, stringWithEmbeddedNUL) {
04491   static const char char_array_with_nul[] =
04492       "Here's a NUL\0 and some more string";
04493   static const std::string string_with_nul(char_array_with_nul,
04494                                            sizeof(char_array_with_nul)
04495                                            - 1);  // drops the trailing NUL
04496   EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
04497                        "Here's a NUL\\0 and some more string");
04498 }
04499 
04500 // Tests that we can output a NUL char.
04501 TEST(StreamableTest, NULChar) {
04502   EXPECT_FATAL_FAILURE({  // NOLINT
04503     FAIL() << "A NUL" << '\0' << " and some more string";
04504   }, "A NUL\\0 and some more string");
04505 }
04506 
04507 // Tests using int as an assertion message.
04508 TEST(StreamableTest, int) {
04509   EXPECT_FATAL_FAILURE(FAIL() << 900913,
04510                        "900913");
04511 }
04512 
04513 // Tests using NULL char pointer as an assertion message.
04514 //
04515 // In MSVC, streaming a NULL char * causes access violation.  Google Test
04516 // implemented a workaround (substituting "(null)" for NULL).  This
04517 // tests whether the workaround works.
04518 TEST(StreamableTest, NullCharPtr) {
04519   EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
04520                        "(null)");
04521 }
04522 
04523 // Tests that basic IO manipulators (endl, ends, and flush) can be
04524 // streamed to testing::Message.
04525 TEST(StreamableTest, BasicIoManip) {
04526   EXPECT_FATAL_FAILURE({  // NOLINT
04527     FAIL() << "Line 1." << std::endl
04528            << "A NUL char " << std::ends << std::flush << " in line 2.";
04529   }, "Line 1.\nA NUL char \\0 in line 2.");
04530 }
04531 
04532 // Tests the macros that haven't been covered so far.
04533 
04534 void AddFailureHelper(bool* aborted) {
04535   *aborted = true;
04536   ADD_FAILURE() << "Intentional failure.";
04537   *aborted = false;
04538 }
04539 
04540 // Tests ADD_FAILURE.
04541 TEST(MacroTest, ADD_FAILURE) {
04542   bool aborted = true;
04543   EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
04544                           "Intentional failure.");
04545   EXPECT_FALSE(aborted);
04546 }
04547 
04548 // Tests ADD_FAILURE_AT.
04549 TEST(MacroTest, ADD_FAILURE_AT) {
04550   // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
04551   // the failure message contains the user-streamed part.
04552   EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
04553 
04554   // Verifies that the user-streamed part is optional.
04555   EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
04556 
04557   // Unfortunately, we cannot verify that the failure message contains
04558   // the right file path and line number the same way, as
04559   // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
04560   // line number.  Instead, we do that in gtest_output_test_.cc.
04561 }
04562 
04563 // Tests FAIL.
04564 TEST(MacroTest, FAIL) {
04565   EXPECT_FATAL_FAILURE(FAIL(),
04566                        "Failed");
04567   EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
04568                        "Intentional failure.");
04569 }
04570 
04571 // Tests SUCCEED
04572 TEST(MacroTest, SUCCEED) {
04573   SUCCEED();
04574   SUCCEED() << "Explicit success.";
04575 }
04576 
04577 // Tests for EXPECT_EQ() and ASSERT_EQ().
04578 //
04579 // These tests fail *intentionally*, s.t. the failure messages can be
04580 // generated and tested.
04581 //
04582 // We have different tests for different argument types.
04583 
04584 // Tests using bool values in {EXPECT|ASSERT}_EQ.
04585 TEST(EqAssertionTest, Bool) {
04586   EXPECT_EQ(true,  true);
04587   EXPECT_FATAL_FAILURE({
04588       bool false_value = false;
04589       ASSERT_EQ(false_value, true);
04590     }, "Value of: true");
04591 }
04592 
04593 // Tests using int values in {EXPECT|ASSERT}_EQ.
04594 TEST(EqAssertionTest, Int) {
04595   ASSERT_EQ(32, 32);
04596   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
04597                           "33");
04598 }
04599 
04600 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
04601 TEST(EqAssertionTest, Time_T) {
04602   EXPECT_EQ(static_cast<time_t>(0),
04603             static_cast<time_t>(0));
04604   EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
04605                                  static_cast<time_t>(1234)),
04606                        "1234");
04607 }
04608 
04609 // Tests using char values in {EXPECT|ASSERT}_EQ.
04610 TEST(EqAssertionTest, Char) {
04611   ASSERT_EQ('z', 'z');
04612   const char ch = 'b';
04613   EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
04614                           "ch");
04615   EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
04616                           "ch");
04617 }
04618 
04619 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
04620 TEST(EqAssertionTest, WideChar) {
04621   EXPECT_EQ(L'b', L'b');
04622 
04623   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
04624                           "Value of: L'x'\n"
04625                           "  Actual: L'x' (120, 0x78)\n"
04626                           "Expected: L'\0'\n"
04627                           "Which is: L'\0' (0, 0x0)");
04628 
04629   static wchar_t wchar;
04630   wchar = L'b';
04631   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
04632                           "wchar");
04633   wchar = 0x8119;
04634   EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
04635                        "Value of: wchar");
04636 }
04637 
04638 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
04639 TEST(EqAssertionTest, StdString) {
04640   // Compares a const char* to an std::string that has identical
04641   // content.
04642   ASSERT_EQ("Test", ::std::string("Test"));
04643 
04644   // Compares two identical std::strings.
04645   static const ::std::string str1("A * in the middle");
04646   static const ::std::string str2(str1);
04647   EXPECT_EQ(str1, str2);
04648 
04649   // Compares a const char* to an std::string that has different
04650   // content
04651   EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
04652                           "\"test\"");
04653 
04654   // Compares an std::string to a char* that has different content.
04655   char* const p1 = const_cast<char*>("foo");
04656   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
04657                           "p1");
04658 
04659   // Compares two std::strings that have different contents, one of
04660   // which having a NUL character in the middle.  This should fail.
04661   static ::std::string str3(str1);
04662   str3.at(2) = '\0';
04663   EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
04664                        "Value of: str3\n"
04665                        "  Actual: \"A \\0 in the middle\"");
04666 }
04667 
04668 #if GTEST_HAS_STD_WSTRING
04669 
04670 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
04671 TEST(EqAssertionTest, StdWideString) {
04672   // Compares two identical std::wstrings.
04673   const ::std::wstring wstr1(L"A * in the middle");
04674   const ::std::wstring wstr2(wstr1);
04675   ASSERT_EQ(wstr1, wstr2);
04676 
04677   // Compares an std::wstring to a const wchar_t* that has identical
04678   // content.
04679   const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
04680   EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
04681 
04682   // Compares an std::wstring to a const wchar_t* that has different
04683   // content.
04684   const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
04685   EXPECT_NONFATAL_FAILURE({  // NOLINT
04686     EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
04687   }, "kTestX8120");
04688 
04689   // Compares two std::wstrings that have different contents, one of
04690   // which having a NUL character in the middle.
04691   ::std::wstring wstr3(wstr1);
04692   wstr3.at(2) = L'\0';
04693   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
04694                           "wstr3");
04695 
04696   // Compares a wchar_t* to an std::wstring that has different
04697   // content.
04698   EXPECT_FATAL_FAILURE({  // NOLINT
04699     ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
04700   }, "");
04701 }
04702 
04703 #endif  // GTEST_HAS_STD_WSTRING
04704 
04705 #if GTEST_HAS_GLOBAL_STRING
04706 // Tests using ::string values in {EXPECT|ASSERT}_EQ.
04707 TEST(EqAssertionTest, GlobalString) {
04708   // Compares a const char* to a ::string that has identical content.
04709   EXPECT_EQ("Test", ::string("Test"));
04710 
04711   // Compares two identical ::strings.
04712   const ::string str1("A * in the middle");
04713   const ::string str2(str1);
04714   ASSERT_EQ(str1, str2);
04715 
04716   // Compares a ::string to a const char* that has different content.
04717   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
04718                           "test");
04719 
04720   // Compares two ::strings that have different contents, one of which
04721   // having a NUL character in the middle.
04722   ::string str3(str1);
04723   str3.at(2) = '\0';
04724   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
04725                           "str3");
04726 
04727   // Compares a ::string to a char* that has different content.
04728   EXPECT_FATAL_FAILURE({  // NOLINT
04729     ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
04730   }, "");
04731 }
04732 
04733 #endif  // GTEST_HAS_GLOBAL_STRING
04734 
04735 #if GTEST_HAS_GLOBAL_WSTRING
04736 
04737 // Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
04738 TEST(EqAssertionTest, GlobalWideString) {
04739   // Compares two identical ::wstrings.
04740   static const ::wstring wstr1(L"A * in the middle");
04741   static const ::wstring wstr2(wstr1);
04742   EXPECT_EQ(wstr1, wstr2);
04743 
04744   // Compares a const wchar_t* to a ::wstring that has identical content.
04745   const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
04746   ASSERT_EQ(kTestX8119, ::wstring(kTestX8119));
04747 
04748   // Compares a const wchar_t* to a ::wstring that has different
04749   // content.
04750   const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
04751   EXPECT_NONFATAL_FAILURE({  // NOLINT
04752     EXPECT_EQ(kTestX8120, ::wstring(kTestX8119));
04753   }, "Test\\x8119");
04754 
04755   // Compares a wchar_t* to a ::wstring that has different content.
04756   wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
04757   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
04758                           "bar");
04759 
04760   // Compares two ::wstrings that have different contents, one of which
04761   // having a NUL character in the middle.
04762   static ::wstring wstr3;
04763   wstr3 = wstr1;
04764   wstr3.at(2) = L'\0';
04765   EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
04766                        "wstr3");
04767 }
04768 
04769 #endif  // GTEST_HAS_GLOBAL_WSTRING
04770 
04771 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
04772 TEST(EqAssertionTest, CharPointer) {
04773   char* const p0 = NULL;
04774   // Only way to get the Nokia compiler to compile the cast
04775   // is to have a separate void* variable first. Putting
04776   // the two casts on the same line doesn't work, neither does
04777   // a direct C-style to char*.
04778   void* pv1 = (void*)0x1234;  // NOLINT
04779   void* pv2 = (void*)0xABC0;  // NOLINT
04780   char* const p1 = reinterpret_cast<char*>(pv1);
04781   char* const p2 = reinterpret_cast<char*>(pv2);
04782   ASSERT_EQ(p1, p1);
04783 
04784   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
04785                           "Value of: p2");
04786   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
04787                           "p2");
04788   EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
04789                                  reinterpret_cast<char*>(0xABC0)),
04790                        "ABC0");
04791 }
04792 
04793 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
04794 TEST(EqAssertionTest, WideCharPointer) {
04795   wchar_t* const p0 = NULL;
04796   // Only way to get the Nokia compiler to compile the cast
04797   // is to have a separate void* variable first. Putting
04798   // the two casts on the same line doesn't work, neither does
04799   // a direct C-style to char*.
04800   void* pv1 = (void*)0x1234;  // NOLINT
04801   void* pv2 = (void*)0xABC0;  // NOLINT
04802   wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
04803   wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
04804   EXPECT_EQ(p0, p0);
04805 
04806   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
04807                           "Value of: p2");
04808   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
04809                           "p2");
04810   void* pv3 = (void*)0x1234;  // NOLINT
04811   void* pv4 = (void*)0xABC0;  // NOLINT
04812   const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
04813   const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
04814   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
04815                           "p4");
04816 }
04817 
04818 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
04819 TEST(EqAssertionTest, OtherPointer) {
04820   ASSERT_EQ(static_cast<const int*>(NULL),
04821             static_cast<const int*>(NULL));
04822   EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
04823                                  reinterpret_cast<const int*>(0x1234)),
04824                        "0x1234");
04825 }
04826 
04827 // A class that supports binary comparison operators but not streaming.
04828 class UnprintableChar {
04829  public:
04830   explicit UnprintableChar(char ch) : char_(ch) {}
04831 
04832   bool operator==(const UnprintableChar& rhs) const {
04833     return char_ == rhs.char_;
04834   }
04835   bool operator!=(const UnprintableChar& rhs) const {
04836     return char_ != rhs.char_;
04837   }
04838   bool operator<(const UnprintableChar& rhs) const {
04839     return char_ < rhs.char_;
04840   }
04841   bool operator<=(const UnprintableChar& rhs) const {
04842     return char_ <= rhs.char_;
04843   }
04844   bool operator>(const UnprintableChar& rhs) const {
04845     return char_ > rhs.char_;
04846   }
04847   bool operator>=(const UnprintableChar& rhs) const {
04848     return char_ >= rhs.char_;
04849   }
04850 
04851  private:
04852   char char_;
04853 };
04854 
04855 // Tests that ASSERT_EQ() and friends don't require the arguments to
04856 // be printable.
04857 TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
04858   const UnprintableChar x('x'), y('y');
04859   ASSERT_EQ(x, x);
04860   EXPECT_NE(x, y);
04861   ASSERT_LT(x, y);
04862   EXPECT_LE(x, y);
04863   ASSERT_GT(y, x);
04864   EXPECT_GE(x, x);
04865 
04866   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
04867   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
04868   EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
04869   EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
04870   EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
04871 
04872   // Code tested by EXPECT_FATAL_FAILURE cannot reference local
04873   // variables, so we have to write UnprintableChar('x') instead of x.
04874 #ifndef __BORLANDC__
04875   // ICE's in C++Builder.
04876   EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
04877                        "1-byte object <78>");
04878   EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
04879                        "1-byte object <78>");
04880 #endif
04881   EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
04882                        "1-byte object <79>");
04883   EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
04884                        "1-byte object <78>");
04885   EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
04886                        "1-byte object <79>");
04887 }
04888 
04889 // Tests the FRIEND_TEST macro.
04890 
04891 // This class has a private member we want to test.  We will test it
04892 // both in a TEST and in a TEST_F.
04893 class Foo {
04894  public:
04895   Foo() {}
04896 
04897  private:
04898   int Bar() const { return 1; }
04899 
04900   // Declares the friend tests that can access the private member
04901   // Bar().
04902   FRIEND_TEST(FRIEND_TEST_Test, TEST);
04903   FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
04904 };
04905 
04906 // Tests that the FRIEND_TEST declaration allows a TEST to access a
04907 // class's private members.  This should compile.
04908 TEST(FRIEND_TEST_Test, TEST) {
04909   ASSERT_EQ(1, Foo().Bar());
04910 }
04911 
04912 // The fixture needed to test using FRIEND_TEST with TEST_F.
04913 class FRIEND_TEST_Test2 : public Test {
04914  protected:
04915   Foo foo;
04916 };
04917 
04918 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
04919 // class's private members.  This should compile.
04920 TEST_F(FRIEND_TEST_Test2, TEST_F) {
04921   ASSERT_EQ(1, foo.Bar());
04922 }
04923 
04924 // Tests the life cycle of Test objects.
04925 
04926 // The test fixture for testing the life cycle of Test objects.
04927 //
04928 // This class counts the number of live test objects that uses this
04929 // fixture.
04930 class TestLifeCycleTest : public Test {
04931  protected:
04932   // Constructor.  Increments the number of test objects that uses
04933   // this fixture.
04934   TestLifeCycleTest() { count_++; }
04935 
04936   // Destructor.  Decrements the number of test objects that uses this
04937   // fixture.
04938   ~TestLifeCycleTest() { count_--; }
04939 
04940   // Returns the number of live test objects that uses this fixture.
04941   int count() const { return count_; }
04942 
04943  private:
04944   static int count_;
04945 };
04946 
04947 int TestLifeCycleTest::count_ = 0;
04948 
04949 // Tests the life cycle of test objects.
04950 TEST_F(TestLifeCycleTest, Test1) {
04951   // There should be only one test object in this test case that's
04952   // currently alive.
04953   ASSERT_EQ(1, count());
04954 }
04955 
04956 // Tests the life cycle of test objects.
04957 TEST_F(TestLifeCycleTest, Test2) {
04958   // After Test1 is done and Test2 is started, there should still be
04959   // only one live test object, as the object for Test1 should've been
04960   // deleted.
04961   ASSERT_EQ(1, count());
04962 }
04963 
04964 }  // namespace
04965 
04966 // Tests that the copy constructor works when it is NOT optimized away by
04967 // the compiler.
04968 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
04969   // Checks that the copy constructor doesn't try to dereference NULL pointers
04970   // in the source object.
04971   AssertionResult r1 = AssertionSuccess();
04972   AssertionResult r2 = r1;
04973   // The following line is added to prevent the compiler from optimizing
04974   // away the constructor call.
04975   r1 << "abc";
04976 
04977   AssertionResult r3 = r1;
04978   EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
04979   EXPECT_STREQ("abc", r1.message());
04980 }
04981 
04982 // Tests that AssertionSuccess and AssertionFailure construct
04983 // AssertionResult objects as expected.
04984 TEST(AssertionResultTest, ConstructionWorks) {
04985   AssertionResult r1 = AssertionSuccess();
04986   EXPECT_TRUE(r1);
04987   EXPECT_STREQ("", r1.message());
04988 
04989   AssertionResult r2 = AssertionSuccess() << "abc";
04990   EXPECT_TRUE(r2);
04991   EXPECT_STREQ("abc", r2.message());
04992 
04993   AssertionResult r3 = AssertionFailure();
04994   EXPECT_FALSE(r3);
04995   EXPECT_STREQ("", r3.message());
04996 
04997   AssertionResult r4 = AssertionFailure() << "def";
04998   EXPECT_FALSE(r4);
04999   EXPECT_STREQ("def", r4.message());
05000 
05001   AssertionResult r5 = AssertionFailure(Message() << "ghi");
05002   EXPECT_FALSE(r5);
05003   EXPECT_STREQ("ghi", r5.message());
05004 }
05005 
05006 // Tests that the negation flips the predicate result but keeps the message.
05007 TEST(AssertionResultTest, NegationWorks) {
05008   AssertionResult r1 = AssertionSuccess() << "abc";
05009   EXPECT_FALSE(!r1);
05010   EXPECT_STREQ("abc", (!r1).message());
05011 
05012   AssertionResult r2 = AssertionFailure() << "def";
05013   EXPECT_TRUE(!r2);
05014   EXPECT_STREQ("def", (!r2).message());
05015 }
05016 
05017 TEST(AssertionResultTest, StreamingWorks) {
05018   AssertionResult r = AssertionSuccess();
05019   r << "abc" << 'd' << 0 << true;
05020   EXPECT_STREQ("abcd0true", r.message());
05021 }
05022 
05023 TEST(AssertionResultTest, CanStreamOstreamManipulators) {
05024   AssertionResult r = AssertionSuccess();
05025   r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
05026   EXPECT_STREQ("Data\n\\0Will be visible", r.message());
05027 }
05028 
05029 // Tests streaming a user type whose definition and operator << are
05030 // both in the global namespace.
05031 class Base {
05032  public:
05033   explicit Base(int an_x) : x_(an_x) {}
05034   int x() const { return x_; }
05035  private:
05036   int x_;
05037 };
05038 std::ostream& operator<<(std::ostream& os,
05039                          const Base& val) {
05040   return os << val.x();
05041 }
05042 std::ostream& operator<<(std::ostream& os,
05043                          const Base* pointer) {
05044   return os << "(" << pointer->x() << ")";
05045 }
05046 
05047 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
05048   Message msg;
05049   Base a(1);
05050 
05051   msg << a << &a;  // Uses ::operator<<.
05052   EXPECT_STREQ("1(1)", msg.GetString().c_str());
05053 }
05054 
05055 // Tests streaming a user type whose definition and operator<< are
05056 // both in an unnamed namespace.
05057 namespace {
05058 class MyTypeInUnnamedNameSpace : public Base {
05059  public:
05060   explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
05061 };
05062 std::ostream& operator<<(std::ostream& os,
05063                          const MyTypeInUnnamedNameSpace& val) {
05064   return os << val.x();
05065 }
05066 std::ostream& operator<<(std::ostream& os,
05067                          const MyTypeInUnnamedNameSpace* pointer) {
05068   return os << "(" << pointer->x() << ")";
05069 }
05070 }  // namespace
05071 
05072 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
05073   Message msg;
05074   MyTypeInUnnamedNameSpace a(1);
05075 
05076   msg << a << &a;  // Uses <unnamed_namespace>::operator<<.
05077   EXPECT_STREQ("1(1)", msg.GetString().c_str());
05078 }
05079 
05080 // Tests streaming a user type whose definition and operator<< are
05081 // both in a user namespace.
05082 namespace namespace1 {
05083 class MyTypeInNameSpace1 : public Base {
05084  public:
05085   explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
05086 };
05087 std::ostream& operator<<(std::ostream& os,
05088                          const MyTypeInNameSpace1& val) {
05089   return os << val.x();
05090 }
05091 std::ostream& operator<<(std::ostream& os,
05092                          const MyTypeInNameSpace1* pointer) {
05093   return os << "(" << pointer->x() << ")";
05094 }
05095 }  // namespace namespace1
05096 
05097 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
05098   Message msg;
05099   namespace1::MyTypeInNameSpace1 a(1);
05100 
05101   msg << a << &a;  // Uses namespace1::operator<<.
05102   EXPECT_STREQ("1(1)", msg.GetString().c_str());
05103 }
05104 
05105 // Tests streaming a user type whose definition is in a user namespace
05106 // but whose operator<< is in the global namespace.
05107 namespace namespace2 {
05108 class MyTypeInNameSpace2 : public ::Base {
05109  public:
05110   explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
05111 };
05112 }  // namespace namespace2
05113 std::ostream& operator<<(std::ostream& os,
05114                          const namespace2::MyTypeInNameSpace2& val) {
05115   return os << val.x();
05116 }
05117 std::ostream& operator<<(std::ostream& os,
05118                          const namespace2::MyTypeInNameSpace2* pointer) {
05119   return os << "(" << pointer->x() << ")";
05120 }
05121 
05122 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
05123   Message msg;
05124   namespace2::MyTypeInNameSpace2 a(1);
05125 
05126   msg << a << &a;  // Uses ::operator<<.
05127   EXPECT_STREQ("1(1)", msg.GetString().c_str());
05128 }
05129 
05130 // Tests streaming NULL pointers to testing::Message.
05131 TEST(MessageTest, NullPointers) {
05132   Message msg;
05133   char* const p1 = NULL;
05134   unsigned char* const p2 = NULL;
05135   int* p3 = NULL;
05136   double* p4 = NULL;
05137   bool* p5 = NULL;
05138   Message* p6 = NULL;
05139 
05140   msg << p1 << p2 << p3 << p4 << p5 << p6;
05141   ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
05142                msg.GetString().c_str());
05143 }
05144 
05145 // Tests streaming wide strings to testing::Message.
05146 TEST(MessageTest, WideStrings) {
05147   // Streams a NULL of type const wchar_t*.
05148   const wchar_t* const_wstr = NULL;
05149   EXPECT_STREQ("(null)",
05150                (Message() << const_wstr).GetString().c_str());
05151 
05152   // Streams a NULL of type wchar_t*.
05153   wchar_t* wstr = NULL;
05154   EXPECT_STREQ("(null)",
05155                (Message() << wstr).GetString().c_str());
05156 
05157   // Streams a non-NULL of type const wchar_t*.
05158   const_wstr = L"abc\x8119";
05159   EXPECT_STREQ("abc\xe8\x84\x99",
05160                (Message() << const_wstr).GetString().c_str());
05161 
05162   // Streams a non-NULL of type wchar_t*.
05163   wstr = const_cast<wchar_t*>(const_wstr);
05164   EXPECT_STREQ("abc\xe8\x84\x99",
05165                (Message() << wstr).GetString().c_str());
05166 }
05167 
05168 
05169 // This line tests that we can define tests in the testing namespace.
05170 namespace testing {
05171 
05172 // Tests the TestInfo class.
05173 
05174 class TestInfoTest : public Test {
05175  protected:
05176   static const TestInfo* GetTestInfo(const char* test_name) {
05177     const TestCase* const test_case = GetUnitTestImpl()->
05178         GetTestCase("TestInfoTest", "", NULL, NULL);
05179 
05180     for (int i = 0; i < test_case->total_test_count(); ++i) {
05181       const TestInfo* const test_info = test_case->GetTestInfo(i);
05182       if (strcmp(test_name, test_info->name()) == 0)
05183         return test_info;
05184     }
05185     return NULL;
05186   }
05187 
05188   static const TestResult* GetTestResult(
05189       const TestInfo* test_info) {
05190     return test_info->result();
05191   }
05192 };
05193 
05194 // Tests TestInfo::test_case_name() and TestInfo::name().
05195 TEST_F(TestInfoTest, Names) {
05196   const TestInfo* const test_info = GetTestInfo("Names");
05197 
05198   ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
05199   ASSERT_STREQ("Names", test_info->name());
05200 }
05201 
05202 // Tests TestInfo::result().
05203 TEST_F(TestInfoTest, result) {
05204   const TestInfo* const test_info = GetTestInfo("result");
05205 
05206   // Initially, there is no TestPartResult for this test.
05207   ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
05208 
05209   // After the previous assertion, there is still none.
05210   ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
05211 }
05212 
05213 // Tests setting up and tearing down a test case.
05214 
05215 class SetUpTestCaseTest : public Test {
05216  protected:
05217   // This will be called once before the first test in this test case
05218   // is run.
05219   static void SetUpTestCase() {
05220     printf("Setting up the test case . . .\n");
05221 
05222     // Initializes some shared resource.  In this simple example, we
05223     // just create a C string.  More complex stuff can be done if
05224     // desired.
05225     shared_resource_ = "123";
05226 
05227     // Increments the number of test cases that have been set up.
05228     counter_++;
05229 
05230     // SetUpTestCase() should be called only once.
05231     EXPECT_EQ(1, counter_);
05232   }
05233 
05234   // This will be called once after the last test in this test case is
05235   // run.
05236   static void TearDownTestCase() {
05237     printf("Tearing down the test case . . .\n");
05238 
05239     // Decrements the number of test cases that have been set up.
05240     counter_--;
05241 
05242     // TearDownTestCase() should be called only once.
05243     EXPECT_EQ(0, counter_);
05244 
05245     // Cleans up the shared resource.
05246     shared_resource_ = NULL;
05247   }
05248 
05249   // This will be called before each test in this test case.
05250   virtual void SetUp() {
05251     // SetUpTestCase() should be called only once, so counter_ should
05252     // always be 1.
05253     EXPECT_EQ(1, counter_);
05254   }
05255 
05256   // Number of test cases that have been set up.
05257   static int counter_;
05258 
05259   // Some resource to be shared by all tests in this test case.
05260   static const char* shared_resource_;
05261 };
05262 
05263 int SetUpTestCaseTest::counter_ = 0;
05264 const char* SetUpTestCaseTest::shared_resource_ = NULL;
05265 
05266 // A test that uses the shared resource.
05267 TEST_F(SetUpTestCaseTest, Test1) {
05268   EXPECT_STRNE(NULL, shared_resource_);
05269 }
05270 
05271 // Another test that uses the shared resource.
05272 TEST_F(SetUpTestCaseTest, Test2) {
05273   EXPECT_STREQ("123", shared_resource_);
05274 }
05275 
05276 // The InitGoogleTestTest test case tests testing::InitGoogleTest().
05277 
05278 // The Flags struct stores a copy of all Google Test flags.
05279 struct Flags {
05280   // Constructs a Flags struct where each flag has its default value.
05281   Flags() : also_run_disabled_tests(false),
05282             break_on_failure(false),
05283             catch_exceptions(false),
05284             death_test_use_fork(false),
05285             filter(""),
05286             list_tests(false),
05287             output(""),
05288             print_time(true),
05289             random_seed(0),
05290             repeat(1),
05291             shuffle(false),
05292             stack_trace_depth(kMaxStackTraceDepth),
05293             stream_result_to(""),
05294             throw_on_failure(false) {}
05295 
05296   // Factory methods.
05297 
05298   // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
05299   // the given value.
05300   static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
05301     Flags flags;
05302     flags.also_run_disabled_tests = also_run_disabled_tests;
05303     return flags;
05304   }
05305 
05306   // Creates a Flags struct where the gtest_break_on_failure flag has
05307   // the given value.
05308   static Flags BreakOnFailure(bool break_on_failure) {
05309     Flags flags;
05310     flags.break_on_failure = break_on_failure;
05311     return flags;
05312   }
05313 
05314   // Creates a Flags struct where the gtest_catch_exceptions flag has
05315   // the given value.
05316   static Flags CatchExceptions(bool catch_exceptions) {
05317     Flags flags;
05318     flags.catch_exceptions = catch_exceptions;
05319     return flags;
05320   }
05321 
05322   // Creates a Flags struct where the gtest_death_test_use_fork flag has
05323   // the given value.
05324   static Flags DeathTestUseFork(bool death_test_use_fork) {
05325     Flags flags;
05326     flags.death_test_use_fork = death_test_use_fork;
05327     return flags;
05328   }
05329 
05330   // Creates a Flags struct where the gtest_filter flag has the given
05331   // value.
05332   static Flags Filter(const char* filter) {
05333     Flags flags;
05334     flags.filter = filter;
05335     return flags;
05336   }
05337 
05338   // Creates a Flags struct where the gtest_list_tests flag has the
05339   // given value.
05340   static Flags ListTests(bool list_tests) {
05341     Flags flags;
05342     flags.list_tests = list_tests;
05343     return flags;
05344   }
05345 
05346   // Creates a Flags struct where the gtest_output flag has the given
05347   // value.
05348   static Flags Output(const char* output) {
05349     Flags flags;
05350     flags.output = output;
05351     return flags;
05352   }
05353 
05354   // Creates a Flags struct where the gtest_print_time flag has the given
05355   // value.
05356   static Flags PrintTime(bool print_time) {
05357     Flags flags;
05358     flags.print_time = print_time;
05359     return flags;
05360   }
05361 
05362   // Creates a Flags struct where the gtest_random_seed flag has
05363   // the given value.
05364   static Flags RandomSeed(Int32 random_seed) {
05365     Flags flags;
05366     flags.random_seed = random_seed;
05367     return flags;
05368   }
05369 
05370   // Creates a Flags struct where the gtest_repeat flag has the given
05371   // value.
05372   static Flags Repeat(Int32 repeat) {
05373     Flags flags;
05374     flags.repeat = repeat;
05375     return flags;
05376   }
05377 
05378   // Creates a Flags struct where the gtest_shuffle flag has
05379   // the given value.
05380   static Flags Shuffle(bool shuffle) {
05381     Flags flags;
05382     flags.shuffle = shuffle;
05383     return flags;
05384   }
05385 
05386   // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
05387   // the given value.
05388   static Flags StackTraceDepth(Int32 stack_trace_depth) {
05389     Flags flags;
05390     flags.stack_trace_depth = stack_trace_depth;
05391     return flags;
05392   }
05393 
05394   // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
05395   // the given value.
05396   static Flags StreamResultTo(const char* stream_result_to) {
05397     Flags flags;
05398     flags.stream_result_to = stream_result_to;
05399     return flags;
05400   }
05401 
05402   // Creates a Flags struct where the gtest_throw_on_failure flag has
05403   // the given value.
05404   static Flags ThrowOnFailure(bool throw_on_failure) {
05405     Flags flags;
05406     flags.throw_on_failure = throw_on_failure;
05407     return flags;
05408   }
05409 
05410   // These fields store the flag values.
05411   bool also_run_disabled_tests;
05412   bool break_on_failure;
05413   bool catch_exceptions;
05414   bool death_test_use_fork;
05415   const char* filter;
05416   bool list_tests;
05417   const char* output;
05418   bool print_time;
05419   Int32 random_seed;
05420   Int32 repeat;
05421   bool shuffle;
05422   Int32 stack_trace_depth;
05423   const char* stream_result_to;
05424   bool throw_on_failure;
05425 };
05426 
05427 // Fixture for testing InitGoogleTest().
05428 class InitGoogleTestTest : public Test {
05429  protected:
05430   // Clears the flags before each test.
05431   virtual void SetUp() {
05432     GTEST_FLAG(also_run_disabled_tests) = false;
05433     GTEST_FLAG(break_on_failure) = false;
05434     GTEST_FLAG(catch_exceptions) = false;
05435     GTEST_FLAG(death_test_use_fork) = false;
05436     GTEST_FLAG(filter) = "";
05437     GTEST_FLAG(list_tests) = false;
05438     GTEST_FLAG(output) = "";
05439     GTEST_FLAG(print_time) = true;
05440     GTEST_FLAG(random_seed) = 0;
05441     GTEST_FLAG(repeat) = 1;
05442     GTEST_FLAG(shuffle) = false;
05443     GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
05444     GTEST_FLAG(stream_result_to) = "";
05445     GTEST_FLAG(throw_on_failure) = false;
05446   }
05447 
05448   // Asserts that two narrow or wide string arrays are equal.
05449   template <typename CharType>
05450   static void AssertStringArrayEq(size_t size1, CharType** array1,
05451                                   size_t size2, CharType** array2) {
05452     ASSERT_EQ(size1, size2) << " Array sizes different.";
05453 
05454     for (size_t i = 0; i != size1; i++) {
05455       ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
05456     }
05457   }
05458 
05459   // Verifies that the flag values match the expected values.
05460   static void CheckFlags(const Flags& expected) {
05461     EXPECT_EQ(expected.also_run_disabled_tests,
05462               GTEST_FLAG(also_run_disabled_tests));
05463     EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
05464     EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
05465     EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
05466     EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
05467     EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
05468     EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
05469     EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
05470     EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
05471     EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
05472     EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
05473     EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
05474     EXPECT_STREQ(expected.stream_result_to,
05475                  GTEST_FLAG(stream_result_to).c_str());
05476     EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
05477   }
05478 
05479   // Parses a command line (specified by argc1 and argv1), then
05480   // verifies that the flag values are expected and that the
05481   // recognized flags are removed from the command line.
05482   template <typename CharType>
05483   static void TestParsingFlags(int argc1, const CharType** argv1,
05484                                int argc2, const CharType** argv2,
05485                                const Flags& expected, bool should_print_help) {
05486     const bool saved_help_flag = ::testing::internal::g_help_flag;
05487     ::testing::internal::g_help_flag = false;
05488 
05489 #if GTEST_HAS_STREAM_REDIRECTION
05490     CaptureStdout();
05491 #endif
05492 
05493     // Parses the command line.
05494     internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
05495 
05496 #if GTEST_HAS_STREAM_REDIRECTION
05497     const std::string captured_stdout = GetCapturedStdout();
05498 #endif
05499 
05500     // Verifies the flag values.
05501     CheckFlags(expected);
05502 
05503     // Verifies that the recognized flags are removed from the command
05504     // line.
05505     AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
05506 
05507     // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
05508     // help message for the flags it recognizes.
05509     EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
05510 
05511 #if GTEST_HAS_STREAM_REDIRECTION
05512     const char* const expected_help_fragment =
05513         "This program contains tests written using";
05514     if (should_print_help) {
05515       EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
05516     } else {
05517       EXPECT_PRED_FORMAT2(IsNotSubstring,
05518                           expected_help_fragment, captured_stdout);
05519     }
05520 #endif  // GTEST_HAS_STREAM_REDIRECTION
05521 
05522     ::testing::internal::g_help_flag = saved_help_flag;
05523   }
05524 
05525   // This macro wraps TestParsingFlags s.t. the user doesn't need
05526   // to specify the array sizes.
05527 
05528 #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
05529   TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
05530                    sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
05531                    expected, should_print_help)
05532 };
05533 
05534 // Tests parsing an empty command line.
05535 TEST_F(InitGoogleTestTest, Empty) {
05536   const char* argv[] = {
05537     NULL
05538   };
05539 
05540   const char* argv2[] = {
05541     NULL
05542   };
05543 
05544   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
05545 }
05546 
05547 // Tests parsing a command line that has no flag.
05548 TEST_F(InitGoogleTestTest, NoFlag) {
05549   const char* argv[] = {
05550     "foo.exe",
05551     NULL
05552   };
05553 
05554   const char* argv2[] = {
05555     "foo.exe",
05556     NULL
05557   };
05558 
05559   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
05560 }
05561 
05562 // Tests parsing a bad --gtest_filter flag.
05563 TEST_F(InitGoogleTestTest, FilterBad) {
05564   const char* argv[] = {
05565     "foo.exe",
05566     "--gtest_filter",
05567     NULL
05568   };
05569 
05570   const char* argv2[] = {
05571     "foo.exe",
05572     "--gtest_filter",
05573     NULL
05574   };
05575 
05576   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
05577 }
05578 
05579 // Tests parsing an empty --gtest_filter flag.
05580 TEST_F(InitGoogleTestTest, FilterEmpty) {
05581   const char* argv[] = {
05582     "foo.exe",
05583     "--gtest_filter=",
05584     NULL
05585   };
05586 
05587   const char* argv2[] = {
05588     "foo.exe",
05589     NULL
05590   };
05591 
05592   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
05593 }
05594 
05595 // Tests parsing a non-empty --gtest_filter flag.
05596 TEST_F(InitGoogleTestTest, FilterNonEmpty) {
05597   const char* argv[] = {
05598     "foo.exe",
05599     "--gtest_filter=abc",
05600     NULL
05601   };
05602 
05603   const char* argv2[] = {
05604     "foo.exe",
05605     NULL
05606   };
05607 
05608   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
05609 }
05610 
05611 // Tests parsing --gtest_break_on_failure.
05612 TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
05613   const char* argv[] = {
05614     "foo.exe",
05615     "--gtest_break_on_failure",
05616     NULL
05617 };
05618 
05619   const char* argv2[] = {
05620     "foo.exe",
05621     NULL
05622   };
05623 
05624   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
05625 }
05626 
05627 // Tests parsing --gtest_break_on_failure=0.
05628 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
05629   const char* argv[] = {
05630     "foo.exe",
05631     "--gtest_break_on_failure=0",
05632     NULL
05633   };
05634 
05635   const char* argv2[] = {
05636     "foo.exe",
05637     NULL
05638   };
05639 
05640   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
05641 }
05642 
05643 // Tests parsing --gtest_break_on_failure=f.
05644 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
05645   const char* argv[] = {
05646     "foo.exe",
05647     "--gtest_break_on_failure=f",
05648     NULL
05649   };
05650 
05651   const char* argv2[] = {
05652     "foo.exe",
05653     NULL
05654   };
05655 
05656   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
05657 }
05658 
05659 // Tests parsing --gtest_break_on_failure=F.
05660 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
05661   const char* argv[] = {
05662     "foo.exe",
05663     "--gtest_break_on_failure=F",
05664     NULL
05665   };
05666 
05667   const char* argv2[] = {
05668     "foo.exe",
05669     NULL
05670   };
05671 
05672   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
05673 }
05674 
05675 // Tests parsing a --gtest_break_on_failure flag that has a "true"
05676 // definition.
05677 TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
05678   const char* argv[] = {
05679     "foo.exe",
05680     "--gtest_break_on_failure=1",
05681     NULL
05682   };
05683 
05684   const char* argv2[] = {
05685     "foo.exe",
05686     NULL
05687   };
05688 
05689   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
05690 }
05691 
05692 // Tests parsing --gtest_catch_exceptions.
05693 TEST_F(InitGoogleTestTest, CatchExceptions) {
05694   const char* argv[] = {
05695     "foo.exe",
05696     "--gtest_catch_exceptions",
05697     NULL
05698   };
05699 
05700   const char* argv2[] = {
05701     "foo.exe",
05702     NULL
05703   };
05704 
05705   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
05706 }
05707 
05708 // Tests parsing --gtest_death_test_use_fork.
05709 TEST_F(InitGoogleTestTest, DeathTestUseFork) {
05710   const char* argv[] = {
05711     "foo.exe",
05712     "--gtest_death_test_use_fork",
05713     NULL
05714   };
05715 
05716   const char* argv2[] = {
05717     "foo.exe",
05718     NULL
05719   };
05720 
05721   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
05722 }
05723 
05724 // Tests having the same flag twice with different values.  The
05725 // expected behavior is that the one coming last takes precedence.
05726 TEST_F(InitGoogleTestTest, DuplicatedFlags) {
05727   const char* argv[] = {
05728     "foo.exe",
05729     "--gtest_filter=a",
05730     "--gtest_filter=b",
05731     NULL
05732   };
05733 
05734   const char* argv2[] = {
05735     "foo.exe",
05736     NULL
05737   };
05738 
05739   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
05740 }
05741 
05742 // Tests having an unrecognized flag on the command line.
05743 TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
05744   const char* argv[] = {
05745     "foo.exe",
05746     "--gtest_break_on_failure",
05747     "bar",  // Unrecognized by Google Test.
05748     "--gtest_filter=b",
05749     NULL
05750   };
05751 
05752   const char* argv2[] = {
05753     "foo.exe",
05754     "bar",
05755     NULL
05756   };
05757 
05758   Flags flags;
05759   flags.break_on_failure = true;
05760   flags.filter = "b";
05761   GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
05762 }
05763 
05764 // Tests having a --gtest_list_tests flag
05765 TEST_F(InitGoogleTestTest, ListTestsFlag) {
05766     const char* argv[] = {
05767       "foo.exe",
05768       "--gtest_list_tests",
05769       NULL
05770     };
05771 
05772     const char* argv2[] = {
05773       "foo.exe",
05774       NULL
05775     };
05776 
05777     GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
05778 }
05779 
05780 // Tests having a --gtest_list_tests flag with a "true" value
05781 TEST_F(InitGoogleTestTest, ListTestsTrue) {
05782     const char* argv[] = {
05783       "foo.exe",
05784       "--gtest_list_tests=1",
05785       NULL
05786     };
05787 
05788     const char* argv2[] = {
05789       "foo.exe",
05790       NULL
05791     };
05792 
05793     GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
05794 }
05795 
05796 // Tests having a --gtest_list_tests flag with a "false" value
05797 TEST_F(InitGoogleTestTest, ListTestsFalse) {
05798     const char* argv[] = {
05799       "foo.exe",
05800       "--gtest_list_tests=0",
05801       NULL
05802     };
05803 
05804     const char* argv2[] = {
05805       "foo.exe",
05806       NULL
05807     };
05808 
05809     GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
05810 }
05811 
05812 // Tests parsing --gtest_list_tests=f.
05813 TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
05814   const char* argv[] = {
05815     "foo.exe",
05816     "--gtest_list_tests=f",
05817     NULL
05818   };
05819 
05820   const char* argv2[] = {
05821     "foo.exe",
05822     NULL
05823   };
05824 
05825   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
05826 }
05827 
05828 // Tests parsing --gtest_list_tests=F.
05829 TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
05830   const char* argv[] = {
05831     "foo.exe",
05832     "--gtest_list_tests=F",
05833     NULL
05834   };
05835 
05836   const char* argv2[] = {
05837     "foo.exe",
05838     NULL
05839   };
05840 
05841   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
05842 }
05843 
05844 // Tests parsing --gtest_output (invalid).
05845 TEST_F(InitGoogleTestTest, OutputEmpty) {
05846   const char* argv[] = {
05847     "foo.exe",
05848     "--gtest_output",
05849     NULL
05850   };
05851 
05852   const char* argv2[] = {
05853     "foo.exe",
05854     "--gtest_output",
05855     NULL
05856   };
05857 
05858   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
05859 }
05860 
05861 // Tests parsing --gtest_output=xml
05862 TEST_F(InitGoogleTestTest, OutputXml) {
05863   const char* argv[] = {
05864     "foo.exe",
05865     "--gtest_output=xml",
05866     NULL
05867   };
05868 
05869   const char* argv2[] = {
05870     "foo.exe",
05871     NULL
05872   };
05873 
05874   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
05875 }
05876 
05877 // Tests parsing --gtest_output=xml:file
05878 TEST_F(InitGoogleTestTest, OutputXmlFile) {
05879   const char* argv[] = {
05880     "foo.exe",
05881     "--gtest_output=xml:file",
05882     NULL
05883   };
05884 
05885   const char* argv2[] = {
05886     "foo.exe",
05887     NULL
05888   };
05889 
05890   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
05891 }
05892 
05893 // Tests parsing --gtest_output=xml:directory/path/
05894 TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
05895   const char* argv[] = {
05896     "foo.exe",
05897     "--gtest_output=xml:directory/path/",
05898     NULL
05899   };
05900 
05901   const char* argv2[] = {
05902     "foo.exe",
05903     NULL
05904   };
05905 
05906   GTEST_TEST_PARSING_FLAGS_(argv, argv2,
05907                             Flags::Output("xml:directory/path/"), false);
05908 }
05909 
05910 // Tests having a --gtest_print_time flag
05911 TEST_F(InitGoogleTestTest, PrintTimeFlag) {
05912     const char* argv[] = {
05913       "foo.exe",
05914       "--gtest_print_time",
05915       NULL
05916     };
05917 
05918     const char* argv2[] = {
05919       "foo.exe",
05920       NULL
05921     };
05922 
05923     GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
05924 }
05925 
05926 // Tests having a --gtest_print_time flag with a "true" value
05927 TEST_F(InitGoogleTestTest, PrintTimeTrue) {
05928     const char* argv[] = {
05929       "foo.exe",
05930       "--gtest_print_time=1",
05931       NULL
05932     };
05933 
05934     const char* argv2[] = {
05935       "foo.exe",
05936       NULL
05937     };
05938 
05939     GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
05940 }
05941 
05942 // Tests having a --gtest_print_time flag with a "false" value
05943 TEST_F(InitGoogleTestTest, PrintTimeFalse) {
05944     const char* argv[] = {
05945       "foo.exe",
05946       "--gtest_print_time=0",
05947       NULL
05948     };
05949 
05950     const char* argv2[] = {
05951       "foo.exe",
05952       NULL
05953     };
05954 
05955     GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
05956 }
05957 
05958 // Tests parsing --gtest_print_time=f.
05959 TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
05960   const char* argv[] = {
05961     "foo.exe",
05962     "--gtest_print_time=f",
05963     NULL
05964   };
05965 
05966   const char* argv2[] = {
05967     "foo.exe",
05968     NULL
05969   };
05970 
05971   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
05972 }
05973 
05974 // Tests parsing --gtest_print_time=F.
05975 TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
05976   const char* argv[] = {
05977     "foo.exe",
05978     "--gtest_print_time=F",
05979     NULL
05980   };
05981 
05982   const char* argv2[] = {
05983     "foo.exe",
05984     NULL
05985   };
05986 
05987   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
05988 }
05989 
05990 // Tests parsing --gtest_random_seed=number
05991 TEST_F(InitGoogleTestTest, RandomSeed) {
05992   const char* argv[] = {
05993     "foo.exe",
05994     "--gtest_random_seed=1000",
05995     NULL
05996   };
05997 
05998   const char* argv2[] = {
05999     "foo.exe",
06000     NULL
06001   };
06002 
06003   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
06004 }
06005 
06006 // Tests parsing --gtest_repeat=number
06007 TEST_F(InitGoogleTestTest, Repeat) {
06008   const char* argv[] = {
06009     "foo.exe",
06010     "--gtest_repeat=1000",
06011     NULL
06012   };
06013 
06014   const char* argv2[] = {
06015     "foo.exe",
06016     NULL
06017   };
06018 
06019   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
06020 }
06021 
06022 // Tests having a --gtest_also_run_disabled_tests flag
06023 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
06024     const char* argv[] = {
06025       "foo.exe",
06026       "--gtest_also_run_disabled_tests",
06027       NULL
06028     };
06029 
06030     const char* argv2[] = {
06031       "foo.exe",
06032       NULL
06033     };
06034 
06035     GTEST_TEST_PARSING_FLAGS_(argv, argv2,
06036                               Flags::AlsoRunDisabledTests(true), false);
06037 }
06038 
06039 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
06040 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
06041     const char* argv[] = {
06042       "foo.exe",
06043       "--gtest_also_run_disabled_tests=1",
06044       NULL
06045     };
06046 
06047     const char* argv2[] = {
06048       "foo.exe",
06049       NULL
06050     };
06051 
06052     GTEST_TEST_PARSING_FLAGS_(argv, argv2,
06053                               Flags::AlsoRunDisabledTests(true), false);
06054 }
06055 
06056 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
06057 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
06058     const char* argv[] = {
06059       "foo.exe",
06060       "--gtest_also_run_disabled_tests=0",
06061       NULL
06062     };
06063 
06064     const char* argv2[] = {
06065       "foo.exe",
06066       NULL
06067     };
06068 
06069     GTEST_TEST_PARSING_FLAGS_(argv, argv2,
06070                               Flags::AlsoRunDisabledTests(false), false);
06071 }
06072 
06073 // Tests parsing --gtest_shuffle.
06074 TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
06075   const char* argv[] = {
06076     "foo.exe",
06077     "--gtest_shuffle",
06078     NULL
06079 };
06080 
06081   const char* argv2[] = {
06082     "foo.exe",
06083     NULL
06084   };
06085 
06086   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
06087 }
06088 
06089 // Tests parsing --gtest_shuffle=0.
06090 TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
06091   const char* argv[] = {
06092     "foo.exe",
06093     "--gtest_shuffle=0",
06094     NULL
06095   };
06096 
06097   const char* argv2[] = {
06098     "foo.exe",
06099     NULL
06100   };
06101 
06102   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
06103 }
06104 
06105 // Tests parsing a --gtest_shuffle flag that has a "true"
06106 // definition.
06107 TEST_F(InitGoogleTestTest, ShuffleTrue) {
06108   const char* argv[] = {
06109     "foo.exe",
06110     "--gtest_shuffle=1",
06111     NULL
06112   };
06113 
06114   const char* argv2[] = {
06115     "foo.exe",
06116     NULL
06117   };
06118 
06119   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
06120 }
06121 
06122 // Tests parsing --gtest_stack_trace_depth=number.
06123 TEST_F(InitGoogleTestTest, StackTraceDepth) {
06124   const char* argv[] = {
06125     "foo.exe",
06126     "--gtest_stack_trace_depth=5",
06127     NULL
06128   };
06129 
06130   const char* argv2[] = {
06131     "foo.exe",
06132     NULL
06133   };
06134 
06135   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
06136 }
06137 
06138 TEST_F(InitGoogleTestTest, StreamResultTo) {
06139   const char* argv[] = {
06140     "foo.exe",
06141     "--gtest_stream_result_to=localhost:1234",
06142     NULL
06143   };
06144 
06145   const char* argv2[] = {
06146     "foo.exe",
06147     NULL
06148   };
06149 
06150   GTEST_TEST_PARSING_FLAGS_(
06151       argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
06152 }
06153 
06154 // Tests parsing --gtest_throw_on_failure.
06155 TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
06156   const char* argv[] = {
06157     "foo.exe",
06158     "--gtest_throw_on_failure",
06159     NULL
06160 };
06161 
06162   const char* argv2[] = {
06163     "foo.exe",
06164     NULL
06165   };
06166 
06167   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
06168 }
06169 
06170 // Tests parsing --gtest_throw_on_failure=0.
06171 TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
06172   const char* argv[] = {
06173     "foo.exe",
06174     "--gtest_throw_on_failure=0",
06175     NULL
06176   };
06177 
06178   const char* argv2[] = {
06179     "foo.exe",
06180     NULL
06181   };
06182 
06183   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
06184 }
06185 
06186 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
06187 // definition.
06188 TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
06189   const char* argv[] = {
06190     "foo.exe",
06191     "--gtest_throw_on_failure=1",
06192     NULL
06193   };
06194 
06195   const char* argv2[] = {
06196     "foo.exe",
06197     NULL
06198   };
06199 
06200   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
06201 }
06202 
06203 #if GTEST_OS_WINDOWS
06204 // Tests parsing wide strings.
06205 TEST_F(InitGoogleTestTest, WideStrings) {
06206   const wchar_t* argv[] = {
06207     L"foo.exe",
06208     L"--gtest_filter=Foo*",
06209     L"--gtest_list_tests=1",
06210     L"--gtest_break_on_failure",
06211     L"--non_gtest_flag",
06212     NULL
06213   };
06214 
06215   const wchar_t* argv2[] = {
06216     L"foo.exe",
06217     L"--non_gtest_flag",
06218     NULL
06219   };
06220 
06221   Flags expected_flags;
06222   expected_flags.break_on_failure = true;
06223   expected_flags.filter = "Foo*";
06224   expected_flags.list_tests = true;
06225 
06226   GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
06227 }
06228 #endif  // GTEST_OS_WINDOWS
06229 
06230 // Tests current_test_info() in UnitTest.
06231 class CurrentTestInfoTest : public Test {
06232  protected:
06233   // Tests that current_test_info() returns NULL before the first test in
06234   // the test case is run.
06235   static void SetUpTestCase() {
06236     // There should be no tests running at this point.
06237     const TestInfo* test_info =
06238       UnitTest::GetInstance()->current_test_info();
06239     EXPECT_TRUE(test_info == NULL)
06240         << "There should be no tests running at this point.";
06241   }
06242 
06243   // Tests that current_test_info() returns NULL after the last test in
06244   // the test case has run.
06245   static void TearDownTestCase() {
06246     const TestInfo* test_info =
06247       UnitTest::GetInstance()->current_test_info();
06248     EXPECT_TRUE(test_info == NULL)
06249         << "There should be no tests running at this point.";
06250   }
06251 };
06252 
06253 // Tests that current_test_info() returns TestInfo for currently running
06254 // test by checking the expected test name against the actual one.
06255 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
06256   const TestInfo* test_info =
06257     UnitTest::GetInstance()->current_test_info();
06258   ASSERT_TRUE(NULL != test_info)
06259       << "There is a test running so we should have a valid TestInfo.";
06260   EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
06261       << "Expected the name of the currently running test case.";
06262   EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
06263       << "Expected the name of the currently running test.";
06264 }
06265 
06266 // Tests that current_test_info() returns TestInfo for currently running
06267 // test by checking the expected test name against the actual one.  We
06268 // use this test to see that the TestInfo object actually changed from
06269 // the previous invocation.
06270 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
06271   const TestInfo* test_info =
06272     UnitTest::GetInstance()->current_test_info();
06273   ASSERT_TRUE(NULL != test_info)
06274       << "There is a test running so we should have a valid TestInfo.";
06275   EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
06276       << "Expected the name of the currently running test case.";
06277   EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
06278       << "Expected the name of the currently running test.";
06279 }
06280 
06281 }  // namespace testing
06282 
06283 // These two lines test that we can define tests in a namespace that
06284 // has the name "testing" and is nested in another namespace.
06285 namespace my_namespace {
06286 namespace testing {
06287 
06288 // Makes sure that TEST knows to use ::testing::Test instead of
06289 // ::my_namespace::testing::Test.
06290 class Test {};
06291 
06292 // Makes sure that an assertion knows to use ::testing::Message instead of
06293 // ::my_namespace::testing::Message.
06294 class Message {};
06295 
06296 // Makes sure that an assertion knows to use
06297 // ::testing::AssertionResult instead of
06298 // ::my_namespace::testing::AssertionResult.
06299 class AssertionResult {};
06300 
06301 // Tests that an assertion that should succeed works as expected.
06302 TEST(NestedTestingNamespaceTest, Success) {
06303   EXPECT_EQ(1, 1) << "This shouldn't fail.";
06304 }
06305 
06306 // Tests that an assertion that should fail works as expected.
06307 TEST(NestedTestingNamespaceTest, Failure) {
06308   EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
06309                        "This failure is expected.");
06310 }
06311 
06312 }  // namespace testing
06313 }  // namespace my_namespace
06314 
06315 // Tests that one can call superclass SetUp and TearDown methods--
06316 // that is, that they are not private.
06317 // No tests are based on this fixture; the test "passes" if it compiles
06318 // successfully.
06319 class ProtectedFixtureMethodsTest : public Test {
06320  protected:
06321   virtual void SetUp() {
06322     Test::SetUp();
06323   }
06324   virtual void TearDown() {
06325     Test::TearDown();
06326   }
06327 };
06328 
06329 // StreamingAssertionsTest tests the streaming versions of a representative
06330 // sample of assertions.
06331 TEST(StreamingAssertionsTest, Unconditional) {
06332   SUCCEED() << "expected success";
06333   EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
06334                           "expected failure");
06335   EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
06336                        "expected failure");
06337 }
06338 
06339 #ifdef __BORLANDC__
06340 // Silences warnings: "Condition is always true", "Unreachable code"
06341 # pragma option push -w-ccc -w-rch
06342 #endif
06343 
06344 TEST(StreamingAssertionsTest, Truth) {
06345   EXPECT_TRUE(true) << "unexpected failure";
06346   ASSERT_TRUE(true) << "unexpected failure";
06347   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
06348                           "expected failure");
06349   EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
06350                        "expected failure");
06351 }
06352 
06353 TEST(StreamingAssertionsTest, Truth2) {
06354   EXPECT_FALSE(false) << "unexpected failure";
06355   ASSERT_FALSE(false) << "unexpected failure";
06356   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
06357                           "expected failure");
06358   EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
06359                        "expected failure");
06360 }
06361 
06362 #ifdef __BORLANDC__
06363 // Restores warnings after previous "#pragma option push" supressed them
06364 # pragma option pop
06365 #endif
06366 
06367 TEST(StreamingAssertionsTest, IntegerEquals) {
06368   EXPECT_EQ(1, 1) << "unexpected failure";
06369   ASSERT_EQ(1, 1) << "unexpected failure";
06370   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
06371                           "expected failure");
06372   EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
06373                        "expected failure");
06374 }
06375 
06376 TEST(StreamingAssertionsTest, IntegerLessThan) {
06377   EXPECT_LT(1, 2) << "unexpected failure";
06378   ASSERT_LT(1, 2) << "unexpected failure";
06379   EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
06380                           "expected failure");
06381   EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
06382                        "expected failure");
06383 }
06384 
06385 TEST(StreamingAssertionsTest, StringsEqual) {
06386   EXPECT_STREQ("foo", "foo") << "unexpected failure";
06387   ASSERT_STREQ("foo", "foo") << "unexpected failure";
06388   EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
06389                           "expected failure");
06390   EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
06391                        "expected failure");
06392 }
06393 
06394 TEST(StreamingAssertionsTest, StringsNotEqual) {
06395   EXPECT_STRNE("foo", "bar") << "unexpected failure";
06396   ASSERT_STRNE("foo", "bar") << "unexpected failure";
06397   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
06398                           "expected failure");
06399   EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
06400                        "expected failure");
06401 }
06402 
06403 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
06404   EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
06405   ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
06406   EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
06407                           "expected failure");
06408   EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
06409                        "expected failure");
06410 }
06411 
06412 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
06413   EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
06414   ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
06415   EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
06416                           "expected failure");
06417   EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
06418                        "expected failure");
06419 }
06420 
06421 TEST(StreamingAssertionsTest, FloatingPointEquals) {
06422   EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
06423   ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
06424   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
06425                           "expected failure");
06426   EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
06427                        "expected failure");
06428 }
06429 
06430 #if GTEST_HAS_EXCEPTIONS
06431 
06432 TEST(StreamingAssertionsTest, Throw) {
06433   EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
06434   ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
06435   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
06436                           "expected failure", "expected failure");
06437   EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
06438                        "expected failure", "expected failure");
06439 }
06440 
06441 TEST(StreamingAssertionsTest, NoThrow) {
06442   EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
06443   ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
06444   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
06445                           "expected failure", "expected failure");
06446   EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
06447                        "expected failure", "expected failure");
06448 }
06449 
06450 TEST(StreamingAssertionsTest, AnyThrow) {
06451   EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
06452   ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
06453   EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
06454                           "expected failure", "expected failure");
06455   EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
06456                        "expected failure", "expected failure");
06457 }
06458 
06459 #endif  // GTEST_HAS_EXCEPTIONS
06460 
06461 // Tests that Google Test correctly decides whether to use colors in the output.
06462 
06463 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
06464   GTEST_FLAG(color) = "yes";
06465 
06466   SetEnv("TERM", "xterm");  // TERM supports colors.
06467   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06468   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
06469 
06470   SetEnv("TERM", "dumb");  // TERM doesn't support colors.
06471   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06472   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
06473 }
06474 
06475 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
06476   SetEnv("TERM", "dumb");  // TERM doesn't support colors.
06477 
06478   GTEST_FLAG(color) = "True";
06479   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
06480 
06481   GTEST_FLAG(color) = "t";
06482   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
06483 
06484   GTEST_FLAG(color) = "1";
06485   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
06486 }
06487 
06488 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
06489   GTEST_FLAG(color) = "no";
06490 
06491   SetEnv("TERM", "xterm");  // TERM supports colors.
06492   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
06493   EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
06494 
06495   SetEnv("TERM", "dumb");  // TERM doesn't support colors.
06496   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
06497   EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
06498 }
06499 
06500 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
06501   SetEnv("TERM", "xterm");  // TERM supports colors.
06502 
06503   GTEST_FLAG(color) = "F";
06504   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
06505 
06506   GTEST_FLAG(color) = "0";
06507   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
06508 
06509   GTEST_FLAG(color) = "unknown";
06510   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
06511 }
06512 
06513 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
06514   GTEST_FLAG(color) = "auto";
06515 
06516   SetEnv("TERM", "xterm");  // TERM supports colors.
06517   EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
06518   EXPECT_TRUE(ShouldUseColor(true));    // Stdout is a TTY.
06519 }
06520 
06521 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
06522   GTEST_FLAG(color) = "auto";
06523 
06524 #if GTEST_OS_WINDOWS
06525   // On Windows, we ignore the TERM variable as it's usually not set.
06526 
06527   SetEnv("TERM", "dumb");
06528   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06529 
06530   SetEnv("TERM", "");
06531   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06532 
06533   SetEnv("TERM", "xterm");
06534   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06535 #else
06536   // On non-Windows platforms, we rely on TERM to determine if the
06537   // terminal supports colors.
06538 
06539   SetEnv("TERM", "dumb");  // TERM doesn't support colors.
06540   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
06541 
06542   SetEnv("TERM", "emacs");  // TERM doesn't support colors.
06543   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
06544 
06545   SetEnv("TERM", "vt100");  // TERM doesn't support colors.
06546   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
06547 
06548   SetEnv("TERM", "xterm-mono");  // TERM doesn't support colors.
06549   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
06550 
06551   SetEnv("TERM", "xterm");  // TERM supports colors.
06552   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06553 
06554   SetEnv("TERM", "xterm-color");  // TERM supports colors.
06555   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06556 
06557   SetEnv("TERM", "xterm-256color");  // TERM supports colors.
06558   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06559 
06560   SetEnv("TERM", "screen");  // TERM supports colors.
06561   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06562 
06563   SetEnv("TERM", "screen-256color");  // TERM supports colors.
06564   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06565 
06566   SetEnv("TERM", "linux");  // TERM supports colors.
06567   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06568 
06569   SetEnv("TERM", "cygwin");  // TERM supports colors.
06570   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
06571 #endif  // GTEST_OS_WINDOWS
06572 }
06573 
06574 // Verifies that StaticAssertTypeEq works in a namespace scope.
06575 
06576 static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
06577 static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
06578     StaticAssertTypeEq<const int, const int>();
06579 
06580 // Verifies that StaticAssertTypeEq works in a class.
06581 
06582 template <typename T>
06583 class StaticAssertTypeEqTestHelper {
06584  public:
06585   StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
06586 };
06587 
06588 TEST(StaticAssertTypeEqTest, WorksInClass) {
06589   StaticAssertTypeEqTestHelper<bool>();
06590 }
06591 
06592 // Verifies that StaticAssertTypeEq works inside a function.
06593 
06594 typedef int IntAlias;
06595 
06596 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
06597   StaticAssertTypeEq<int, IntAlias>();
06598   StaticAssertTypeEq<int*, IntAlias*>();
06599 }
06600 
06601 TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
06602   testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
06603 
06604   // We don't have a stack walker in Google Test yet.
06605   EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
06606   EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
06607 }
06608 
06609 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
06610   EXPECT_FALSE(HasNonfatalFailure());
06611 }
06612 
06613 static void FailFatally() { FAIL(); }
06614 
06615 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
06616   FailFatally();
06617   const bool has_nonfatal_failure = HasNonfatalFailure();
06618   ClearCurrentTestPartResults();
06619   EXPECT_FALSE(has_nonfatal_failure);
06620 }
06621 
06622 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
06623   ADD_FAILURE();
06624   const bool has_nonfatal_failure = HasNonfatalFailure();
06625   ClearCurrentTestPartResults();
06626   EXPECT_TRUE(has_nonfatal_failure);
06627 }
06628 
06629 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
06630   FailFatally();
06631   ADD_FAILURE();
06632   const bool has_nonfatal_failure = HasNonfatalFailure();
06633   ClearCurrentTestPartResults();
06634   EXPECT_TRUE(has_nonfatal_failure);
06635 }
06636 
06637 // A wrapper for calling HasNonfatalFailure outside of a test body.
06638 static bool HasNonfatalFailureHelper() {
06639   return testing::Test::HasNonfatalFailure();
06640 }
06641 
06642 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
06643   EXPECT_FALSE(HasNonfatalFailureHelper());
06644 }
06645 
06646 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
06647   ADD_FAILURE();
06648   const bool has_nonfatal_failure = HasNonfatalFailureHelper();
06649   ClearCurrentTestPartResults();
06650   EXPECT_TRUE(has_nonfatal_failure);
06651 }
06652 
06653 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
06654   EXPECT_FALSE(HasFailure());
06655 }
06656 
06657 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
06658   FailFatally();
06659   const bool has_failure = HasFailure();
06660   ClearCurrentTestPartResults();
06661   EXPECT_TRUE(has_failure);
06662 }
06663 
06664 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
06665   ADD_FAILURE();
06666   const bool has_failure = HasFailure();
06667   ClearCurrentTestPartResults();
06668   EXPECT_TRUE(has_failure);
06669 }
06670 
06671 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
06672   FailFatally();
06673   ADD_FAILURE();
06674   const bool has_failure = HasFailure();
06675   ClearCurrentTestPartResults();
06676   EXPECT_TRUE(has_failure);
06677 }
06678 
06679 // A wrapper for calling HasFailure outside of a test body.
06680 static bool HasFailureHelper() { return testing::Test::HasFailure(); }
06681 
06682 TEST(HasFailureTest, WorksOutsideOfTestBody) {
06683   EXPECT_FALSE(HasFailureHelper());
06684 }
06685 
06686 TEST(HasFailureTest, WorksOutsideOfTestBody2) {
06687   ADD_FAILURE();
06688   const bool has_failure = HasFailureHelper();
06689   ClearCurrentTestPartResults();
06690   EXPECT_TRUE(has_failure);
06691 }
06692 
06693 class TestListener : public EmptyTestEventListener {
06694  public:
06695   TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
06696   TestListener(int* on_start_counter, bool* is_destroyed)
06697       : on_start_counter_(on_start_counter),
06698         is_destroyed_(is_destroyed) {}
06699 
06700   virtual ~TestListener() {
06701     if (is_destroyed_)
06702       *is_destroyed_ = true;
06703   }
06704 
06705  protected:
06706   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
06707     if (on_start_counter_ != NULL)
06708       (*on_start_counter_)++;
06709   }
06710 
06711  private:
06712   int* on_start_counter_;
06713   bool* is_destroyed_;
06714 };
06715 
06716 // Tests the constructor.
06717 TEST(TestEventListenersTest, ConstructionWorks) {
06718   TestEventListeners listeners;
06719 
06720   EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
06721   EXPECT_TRUE(listeners.default_result_printer() == NULL);
06722   EXPECT_TRUE(listeners.default_xml_generator() == NULL);
06723 }
06724 
06725 // Tests that the TestEventListeners destructor deletes all the listeners it
06726 // owns.
06727 TEST(TestEventListenersTest, DestructionWorks) {
06728   bool default_result_printer_is_destroyed = false;
06729   bool default_xml_printer_is_destroyed = false;
06730   bool extra_listener_is_destroyed = false;
06731   TestListener* default_result_printer = new TestListener(
06732       NULL, &default_result_printer_is_destroyed);
06733   TestListener* default_xml_printer = new TestListener(
06734       NULL, &default_xml_printer_is_destroyed);
06735   TestListener* extra_listener = new TestListener(
06736       NULL, &extra_listener_is_destroyed);
06737 
06738   {
06739     TestEventListeners listeners;
06740     TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
06741                                                         default_result_printer);
06742     TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
06743                                                        default_xml_printer);
06744     listeners.Append(extra_listener);
06745   }
06746   EXPECT_TRUE(default_result_printer_is_destroyed);
06747   EXPECT_TRUE(default_xml_printer_is_destroyed);
06748   EXPECT_TRUE(extra_listener_is_destroyed);
06749 }
06750 
06751 // Tests that a listener Append'ed to a TestEventListeners list starts
06752 // receiving events.
06753 TEST(TestEventListenersTest, Append) {
06754   int on_start_counter = 0;
06755   bool is_destroyed = false;
06756   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
06757   {
06758     TestEventListeners listeners;
06759     listeners.Append(listener);
06760     TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
06761         *UnitTest::GetInstance());
06762     EXPECT_EQ(1, on_start_counter);
06763   }
06764   EXPECT_TRUE(is_destroyed);
06765 }
06766 
06767 // Tests that listeners receive events in the order they were appended to
06768 // the list, except for *End requests, which must be received in the reverse
06769 // order.
06770 class SequenceTestingListener : public EmptyTestEventListener {
06771  public:
06772   SequenceTestingListener(std::vector<std::string>* vector, const char* id)
06773       : vector_(vector), id_(id) {}
06774 
06775  protected:
06776   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
06777     vector_->push_back(GetEventDescription("OnTestProgramStart"));
06778   }
06779 
06780   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
06781     vector_->push_back(GetEventDescription("OnTestProgramEnd"));
06782   }
06783 
06784   virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
06785                                     int /*iteration*/) {
06786     vector_->push_back(GetEventDescription("OnTestIterationStart"));
06787   }
06788 
06789   virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
06790                                   int /*iteration*/) {
06791     vector_->push_back(GetEventDescription("OnTestIterationEnd"));
06792   }
06793 
06794  private:
06795   std::string GetEventDescription(const char* method) {
06796     Message message;
06797     message << id_ << "." << method;
06798     return message.GetString();
06799   }
06800 
06801   std::vector<std::string>* vector_;
06802   const char* const id_;
06803 
06804   GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
06805 };
06806 
06807 TEST(EventListenerTest, AppendKeepsOrder) {
06808   std::vector<std::string> vec;
06809   TestEventListeners listeners;
06810   listeners.Append(new SequenceTestingListener(&vec, "1st"));
06811   listeners.Append(new SequenceTestingListener(&vec, "2nd"));
06812   listeners.Append(new SequenceTestingListener(&vec, "3rd"));
06813 
06814   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
06815       *UnitTest::GetInstance());
06816   ASSERT_EQ(3U, vec.size());
06817   EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
06818   EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
06819   EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
06820 
06821   vec.clear();
06822   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
06823       *UnitTest::GetInstance());
06824   ASSERT_EQ(3U, vec.size());
06825   EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
06826   EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
06827   EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
06828 
06829   vec.clear();
06830   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
06831       *UnitTest::GetInstance(), 0);
06832   ASSERT_EQ(3U, vec.size());
06833   EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
06834   EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
06835   EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
06836 
06837   vec.clear();
06838   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
06839       *UnitTest::GetInstance(), 0);
06840   ASSERT_EQ(3U, vec.size());
06841   EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
06842   EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
06843   EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
06844 }
06845 
06846 // Tests that a listener removed from a TestEventListeners list stops receiving
06847 // events and is not deleted when the list is destroyed.
06848 TEST(TestEventListenersTest, Release) {
06849   int on_start_counter = 0;
06850   bool is_destroyed = false;
06851   // Although Append passes the ownership of this object to the list,
06852   // the following calls release it, and we need to delete it before the
06853   // test ends.
06854   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
06855   {
06856     TestEventListeners listeners;
06857     listeners.Append(listener);
06858     EXPECT_EQ(listener, listeners.Release(listener));
06859     TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
06860         *UnitTest::GetInstance());
06861     EXPECT_TRUE(listeners.Release(listener) == NULL);
06862   }
06863   EXPECT_EQ(0, on_start_counter);
06864   EXPECT_FALSE(is_destroyed);
06865   delete listener;
06866 }
06867 
06868 // Tests that no events are forwarded when event forwarding is disabled.
06869 TEST(EventListenerTest, SuppressEventForwarding) {
06870   int on_start_counter = 0;
06871   TestListener* listener = new TestListener(&on_start_counter, NULL);
06872 
06873   TestEventListeners listeners;
06874   listeners.Append(listener);
06875   ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
06876   TestEventListenersAccessor::SuppressEventForwarding(&listeners);
06877   ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
06878   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
06879       *UnitTest::GetInstance());
06880   EXPECT_EQ(0, on_start_counter);
06881 }
06882 
06883 // Tests that events generated by Google Test are not forwarded in
06884 // death test subprocesses.
06885 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
06886   EXPECT_DEATH_IF_SUPPORTED({
06887       GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
06888           *GetUnitTestImpl()->listeners())) << "expected failure";},
06889       "expected failure");
06890 }
06891 
06892 // Tests that a listener installed via SetDefaultResultPrinter() starts
06893 // receiving events and is returned via default_result_printer() and that
06894 // the previous default_result_printer is removed from the list and deleted.
06895 TEST(EventListenerTest, default_result_printer) {
06896   int on_start_counter = 0;
06897   bool is_destroyed = false;
06898   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
06899 
06900   TestEventListeners listeners;
06901   TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
06902 
06903   EXPECT_EQ(listener, listeners.default_result_printer());
06904 
06905   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
06906       *UnitTest::GetInstance());
06907 
06908   EXPECT_EQ(1, on_start_counter);
06909 
06910   // Replacing default_result_printer with something else should remove it
06911   // from the list and destroy it.
06912   TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
06913 
06914   EXPECT_TRUE(listeners.default_result_printer() == NULL);
06915   EXPECT_TRUE(is_destroyed);
06916 
06917   // After broadcasting an event the counter is still the same, indicating
06918   // the listener is not in the list anymore.
06919   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
06920       *UnitTest::GetInstance());
06921   EXPECT_EQ(1, on_start_counter);
06922 }
06923 
06924 // Tests that the default_result_printer listener stops receiving events
06925 // when removed via Release and that is not owned by the list anymore.
06926 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
06927   int on_start_counter = 0;
06928   bool is_destroyed = false;
06929   // Although Append passes the ownership of this object to the list,
06930   // the following calls release it, and we need to delete it before the
06931   // test ends.
06932   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
06933   {
06934     TestEventListeners listeners;
06935     TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
06936 
06937     EXPECT_EQ(listener, listeners.Release(listener));
06938     EXPECT_TRUE(listeners.default_result_printer() == NULL);
06939     EXPECT_FALSE(is_destroyed);
06940 
06941     // Broadcasting events now should not affect default_result_printer.
06942     TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
06943         *UnitTest::GetInstance());
06944     EXPECT_EQ(0, on_start_counter);
06945   }
06946   // Destroying the list should not affect the listener now, too.
06947   EXPECT_FALSE(is_destroyed);
06948   delete listener;
06949 }
06950 
06951 // Tests that a listener installed via SetDefaultXmlGenerator() starts
06952 // receiving events and is returned via default_xml_generator() and that
06953 // the previous default_xml_generator is removed from the list and deleted.
06954 TEST(EventListenerTest, default_xml_generator) {
06955   int on_start_counter = 0;
06956   bool is_destroyed = false;
06957   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
06958 
06959   TestEventListeners listeners;
06960   TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
06961 
06962   EXPECT_EQ(listener, listeners.default_xml_generator());
06963 
06964   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
06965       *UnitTest::GetInstance());
06966 
06967   EXPECT_EQ(1, on_start_counter);
06968 
06969   // Replacing default_xml_generator with something else should remove it
06970   // from the list and destroy it.
06971   TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
06972 
06973   EXPECT_TRUE(listeners.default_xml_generator() == NULL);
06974   EXPECT_TRUE(is_destroyed);
06975 
06976   // After broadcasting an event the counter is still the same, indicating
06977   // the listener is not in the list anymore.
06978   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
06979       *UnitTest::GetInstance());
06980   EXPECT_EQ(1, on_start_counter);
06981 }
06982 
06983 // Tests that the default_xml_generator listener stops receiving events
06984 // when removed via Release and that is not owned by the list anymore.
06985 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
06986   int on_start_counter = 0;
06987   bool is_destroyed = false;
06988   // Although Append passes the ownership of this object to the list,
06989   // the following calls release it, and we need to delete it before the
06990   // test ends.
06991   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
06992   {
06993     TestEventListeners listeners;
06994     TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
06995 
06996     EXPECT_EQ(listener, listeners.Release(listener));
06997     EXPECT_TRUE(listeners.default_xml_generator() == NULL);
06998     EXPECT_FALSE(is_destroyed);
06999 
07000     // Broadcasting events now should not affect default_xml_generator.
07001     TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
07002         *UnitTest::GetInstance());
07003     EXPECT_EQ(0, on_start_counter);
07004   }
07005   // Destroying the list should not affect the listener now, too.
07006   EXPECT_FALSE(is_destroyed);
07007   delete listener;
07008 }
07009 
07010 // Sanity tests to ensure that the alternative, verbose spellings of
07011 // some of the macros work.  We don't test them thoroughly as that
07012 // would be quite involved.  Since their implementations are
07013 // straightforward, and they are rarely used, we'll just rely on the
07014 // users to tell us when they are broken.
07015 GTEST_TEST(AlternativeNameTest, Works) {  // GTEST_TEST is the same as TEST.
07016   GTEST_SUCCEED() << "OK";  // GTEST_SUCCEED is the same as SUCCEED.
07017 
07018   // GTEST_FAIL is the same as FAIL.
07019   EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
07020                        "An expected failure");
07021 
07022   // GTEST_ASSERT_XY is the same as ASSERT_XY.
07023 
07024   GTEST_ASSERT_EQ(0, 0);
07025   EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
07026                        "An expected failure");
07027   EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
07028                        "An expected failure");
07029 
07030   GTEST_ASSERT_NE(0, 1);
07031   GTEST_ASSERT_NE(1, 0);
07032   EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
07033                        "An expected failure");
07034 
07035   GTEST_ASSERT_LE(0, 0);
07036   GTEST_ASSERT_LE(0, 1);
07037   EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
07038                        "An expected failure");
07039 
07040   GTEST_ASSERT_LT(0, 1);
07041   EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
07042                        "An expected failure");
07043   EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
07044                        "An expected failure");
07045 
07046   GTEST_ASSERT_GE(0, 0);
07047   GTEST_ASSERT_GE(1, 0);
07048   EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
07049                        "An expected failure");
07050 
07051   GTEST_ASSERT_GT(1, 0);
07052   EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
07053                        "An expected failure");
07054   EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
07055                        "An expected failure");
07056 }
07057 
07058 // Tests for internal utilities necessary for implementation of the universal
07059 // printing.
07060 // TODO(vladl@google.com): Find a better home for them.
07061 
07062 class ConversionHelperBase {};
07063 class ConversionHelperDerived : public ConversionHelperBase {};
07064 
07065 // Tests that IsAProtocolMessage<T>::value is a compile-time constant.
07066 TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
07067   GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value,
07068                         const_true);
07069   GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
07070 }
07071 
07072 // Tests that IsAProtocolMessage<T>::value is true when T is
07073 // proto2::Message or a sub-class of it.
07074 TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
07075   EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
07076   EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
07077 }
07078 
07079 // Tests that IsAProtocolMessage<T>::value is false when T is neither
07080 // ProtocolMessage nor a sub-class of it.
07081 TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
07082   EXPECT_FALSE(IsAProtocolMessage<int>::value);
07083   EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
07084 }
07085 
07086 // Tests that CompileAssertTypesEqual compiles when the type arguments are
07087 // equal.
07088 TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
07089   CompileAssertTypesEqual<void, void>();
07090   CompileAssertTypesEqual<int*, int*>();
07091 }
07092 
07093 // Tests that RemoveReference does not affect non-reference types.
07094 TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
07095   CompileAssertTypesEqual<int, RemoveReference<int>::type>();
07096   CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
07097 }
07098 
07099 // Tests that RemoveReference removes reference from reference types.
07100 TEST(RemoveReferenceTest, RemovesReference) {
07101   CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
07102   CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
07103 }
07104 
07105 // Tests GTEST_REMOVE_REFERENCE_.
07106 
07107 template <typename T1, typename T2>
07108 void TestGTestRemoveReference() {
07109   CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
07110 }
07111 
07112 TEST(RemoveReferenceTest, MacroVersion) {
07113   TestGTestRemoveReference<int, int>();
07114   TestGTestRemoveReference<const char, const char&>();
07115 }
07116 
07117 
07118 // Tests that RemoveConst does not affect non-const types.
07119 TEST(RemoveConstTest, DoesNotAffectNonConstType) {
07120   CompileAssertTypesEqual<int, RemoveConst<int>::type>();
07121   CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
07122 }
07123 
07124 // Tests that RemoveConst removes const from const types.
07125 TEST(RemoveConstTest, RemovesConst) {
07126   CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
07127   CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
07128   CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
07129 }
07130 
07131 // Tests GTEST_REMOVE_CONST_.
07132 
07133 template <typename T1, typename T2>
07134 void TestGTestRemoveConst() {
07135   CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
07136 }
07137 
07138 TEST(RemoveConstTest, MacroVersion) {
07139   TestGTestRemoveConst<int, int>();
07140   TestGTestRemoveConst<double&, double&>();
07141   TestGTestRemoveConst<char, const char>();
07142 }
07143 
07144 // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
07145 
07146 template <typename T1, typename T2>
07147 void TestGTestRemoveReferenceAndConst() {
07148   CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
07149 }
07150 
07151 TEST(RemoveReferenceToConstTest, Works) {
07152   TestGTestRemoveReferenceAndConst<int, int>();
07153   TestGTestRemoveReferenceAndConst<double, double&>();
07154   TestGTestRemoveReferenceAndConst<char, const char>();
07155   TestGTestRemoveReferenceAndConst<char, const char&>();
07156   TestGTestRemoveReferenceAndConst<const char*, const char*>();
07157 }
07158 
07159 // Tests that AddReference does not affect reference types.
07160 TEST(AddReferenceTest, DoesNotAffectReferenceType) {
07161   CompileAssertTypesEqual<int&, AddReference<int&>::type>();
07162   CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
07163 }
07164 
07165 // Tests that AddReference adds reference to non-reference types.
07166 TEST(AddReferenceTest, AddsReference) {
07167   CompileAssertTypesEqual<int&, AddReference<int>::type>();
07168   CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
07169 }
07170 
07171 // Tests GTEST_ADD_REFERENCE_.
07172 
07173 template <typename T1, typename T2>
07174 void TestGTestAddReference() {
07175   CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
07176 }
07177 
07178 TEST(AddReferenceTest, MacroVersion) {
07179   TestGTestAddReference<int&, int>();
07180   TestGTestAddReference<const char&, const char&>();
07181 }
07182 
07183 // Tests GTEST_REFERENCE_TO_CONST_.
07184 
07185 template <typename T1, typename T2>
07186 void TestGTestReferenceToConst() {
07187   CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
07188 }
07189 
07190 TEST(GTestReferenceToConstTest, Works) {
07191   TestGTestReferenceToConst<const char&, char>();
07192   TestGTestReferenceToConst<const int&, const int>();
07193   TestGTestReferenceToConst<const double&, double>();
07194   TestGTestReferenceToConst<const std::string&, const std::string&>();
07195 }
07196 
07197 // Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
07198 TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
07199   GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true);
07200   GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value),
07201                         const_false);
07202 }
07203 
07204 // Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
07205 // be implicitly converted to T2.
07206 TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
07207   EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
07208   EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
07209   EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
07210   EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
07211   EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&,
07212                                      const ConversionHelperBase&>::value));
07213   EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase,
07214                                      ConversionHelperBase>::value));
07215 }
07216 
07217 // Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
07218 // cannot be implicitly converted to T2.
07219 TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
07220   EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
07221   EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
07222   EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
07223   EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&,
07224                                       ConversionHelperDerived&>::value));
07225 }
07226 
07227 // Tests IsContainerTest.
07228 
07229 class NonContainer {};
07230 
07231 TEST(IsContainerTestTest, WorksForNonContainer) {
07232   EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
07233   EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
07234   EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
07235 }
07236 
07237 TEST(IsContainerTestTest, WorksForContainer) {
07238   EXPECT_EQ(sizeof(IsContainer),
07239             sizeof(IsContainerTest<std::vector<bool> >(0)));
07240   EXPECT_EQ(sizeof(IsContainer),
07241             sizeof(IsContainerTest<std::map<int, double> >(0)));
07242 }
07243 
07244 // Tests ArrayEq().
07245 
07246 TEST(ArrayEqTest, WorksForDegeneratedArrays) {
07247   EXPECT_TRUE(ArrayEq(5, 5L));
07248   EXPECT_FALSE(ArrayEq('a', 0));
07249 }
07250 
07251 TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
07252   // Note that a and b are distinct but compatible types.
07253   const int a[] = { 0, 1 };
07254   long b[] = { 0, 1 };
07255   EXPECT_TRUE(ArrayEq(a, b));
07256   EXPECT_TRUE(ArrayEq(a, 2, b));
07257 
07258   b[0] = 2;
07259   EXPECT_FALSE(ArrayEq(a, b));
07260   EXPECT_FALSE(ArrayEq(a, 1, b));
07261 }
07262 
07263 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
07264   const char a[][3] = { "hi", "lo" };
07265   const char b[][3] = { "hi", "lo" };
07266   const char c[][3] = { "hi", "li" };
07267 
07268   EXPECT_TRUE(ArrayEq(a, b));
07269   EXPECT_TRUE(ArrayEq(a, 2, b));
07270 
07271   EXPECT_FALSE(ArrayEq(a, c));
07272   EXPECT_FALSE(ArrayEq(a, 2, c));
07273 }
07274 
07275 // Tests ArrayAwareFind().
07276 
07277 TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
07278   const char a[] = "hello";
07279   EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
07280   EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
07281 }
07282 
07283 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
07284   int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
07285   const int b[2] = { 2, 3 };
07286   EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
07287 
07288   const int c[2] = { 6, 7 };
07289   EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
07290 }
07291 
07292 // Tests CopyArray().
07293 
07294 TEST(CopyArrayTest, WorksForDegeneratedArrays) {
07295   int n = 0;
07296   CopyArray('a', &n);
07297   EXPECT_EQ('a', n);
07298 }
07299 
07300 TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
07301   const char a[3] = "hi";
07302   int b[3];
07303 #ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.
07304   CopyArray(a, &b);
07305   EXPECT_TRUE(ArrayEq(a, b));
07306 #endif
07307 
07308   int c[3];
07309   CopyArray(a, 3, c);
07310   EXPECT_TRUE(ArrayEq(a, c));
07311 }
07312 
07313 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
07314   const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
07315   int b[2][3];
07316 #ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.
07317   CopyArray(a, &b);
07318   EXPECT_TRUE(ArrayEq(a, b));
07319 #endif
07320 
07321   int c[2][3];
07322   CopyArray(a, 2, c);
07323   EXPECT_TRUE(ArrayEq(a, c));
07324 }
07325 
07326 // Tests NativeArray.
07327 
07328 TEST(NativeArrayTest, ConstructorFromArrayWorks) {
07329   const int a[3] = { 0, 1, 2 };
07330   NativeArray<int> na(a, 3, kReference);
07331   EXPECT_EQ(3U, na.size());
07332   EXPECT_EQ(a, na.begin());
07333 }
07334 
07335 TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
07336   typedef int Array[2];
07337   Array* a = new Array[1];
07338   (*a)[0] = 0;
07339   (*a)[1] = 1;
07340   NativeArray<int> na(*a, 2, kCopy);
07341   EXPECT_NE(*a, na.begin());
07342   delete[] a;
07343   EXPECT_EQ(0, na.begin()[0]);
07344   EXPECT_EQ(1, na.begin()[1]);
07345 
07346   // We rely on the heap checker to verify that na deletes the copy of
07347   // array.
07348 }
07349 
07350 TEST(NativeArrayTest, TypeMembersAreCorrect) {
07351   StaticAssertTypeEq<char, NativeArray<char>::value_type>();
07352   StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
07353 
07354   StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
07355   StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
07356 }
07357 
07358 TEST(NativeArrayTest, MethodsWork) {
07359   const int a[3] = { 0, 1, 2 };
07360   NativeArray<int> na(a, 3, kCopy);
07361   ASSERT_EQ(3U, na.size());
07362   EXPECT_EQ(3, na.end() - na.begin());
07363 
07364   NativeArray<int>::const_iterator it = na.begin();
07365   EXPECT_EQ(0, *it);
07366   ++it;
07367   EXPECT_EQ(1, *it);
07368   it++;
07369   EXPECT_EQ(2, *it);
07370   ++it;
07371   EXPECT_EQ(na.end(), it);
07372 
07373   EXPECT_TRUE(na == na);
07374 
07375   NativeArray<int> na2(a, 3, kReference);
07376   EXPECT_TRUE(na == na2);
07377 
07378   const int b1[3] = { 0, 1, 1 };
07379   const int b2[4] = { 0, 1, 2, 3 };
07380   EXPECT_FALSE(na == NativeArray<int>(b1, 3, kReference));
07381   EXPECT_FALSE(na == NativeArray<int>(b2, 4, kCopy));
07382 }
07383 
07384 TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
07385   const char a[2][3] = { "hi", "lo" };
07386   NativeArray<char[3]> na(a, 2, kReference);
07387   ASSERT_EQ(2U, na.size());
07388   EXPECT_EQ(a, na.begin());
07389 }
07390 
07391 // Tests SkipPrefix().
07392 
07393 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
07394   const char* const str = "hello";
07395 
07396   const char* p = str;
07397   EXPECT_TRUE(SkipPrefix("", &p));
07398   EXPECT_EQ(str, p);
07399 
07400   p = str;
07401   EXPECT_TRUE(SkipPrefix("hell", &p));
07402   EXPECT_EQ(str + 4, p);
07403 }
07404 
07405 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
07406   const char* const str = "world";
07407 
07408   const char* p = str;
07409   EXPECT_FALSE(SkipPrefix("W", &p));
07410   EXPECT_EQ(str, p);
07411 
07412   p = str;
07413   EXPECT_FALSE(SkipPrefix("world!", &p));
07414   EXPECT_EQ(str, p);
07415 }


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Sat Jun 8 2019 18:24:56