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


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:04