michael@0: // Copyright 2005, Google Inc. michael@0: // All rights reserved. michael@0: // michael@0: // Redistribution and use in source and binary forms, with or without michael@0: // modification, are permitted provided that the following conditions are michael@0: // met: michael@0: // michael@0: // * Redistributions of source code must retain the above copyright michael@0: // notice, this list of conditions and the following disclaimer. michael@0: // * Redistributions in binary form must reproduce the above michael@0: // copyright notice, this list of conditions and the following disclaimer michael@0: // in the documentation and/or other materials provided with the michael@0: // distribution. michael@0: // * Neither the name of Google Inc. nor the names of its michael@0: // contributors may be used to endorse or promote products derived from michael@0: // this software without specific prior written permission. michael@0: // michael@0: // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS michael@0: // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT michael@0: // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR michael@0: // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT michael@0: // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, michael@0: // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT michael@0: // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, michael@0: // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY michael@0: // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT michael@0: // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE michael@0: // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. michael@0: // michael@0: // Author: wan@google.com (Zhanyong Wan) michael@0: // michael@0: // Tests for Google Test itself. This verifies that the basic constructs of michael@0: // Google Test work. michael@0: michael@0: #include "gtest/gtest.h" michael@0: michael@0: // Verifies that the command line flag variables can be accessed michael@0: // in code once has been #included. michael@0: // Do not move it after other #includes. michael@0: TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { michael@0: bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) michael@0: || testing::GTEST_FLAG(break_on_failure) michael@0: || testing::GTEST_FLAG(catch_exceptions) michael@0: || testing::GTEST_FLAG(color) != "unknown" michael@0: || testing::GTEST_FLAG(filter) != "unknown" michael@0: || testing::GTEST_FLAG(list_tests) michael@0: || testing::GTEST_FLAG(output) != "unknown" michael@0: || testing::GTEST_FLAG(print_time) michael@0: || testing::GTEST_FLAG(random_seed) michael@0: || testing::GTEST_FLAG(repeat) > 0 michael@0: || testing::GTEST_FLAG(show_internal_stack_frames) michael@0: || testing::GTEST_FLAG(shuffle) michael@0: || testing::GTEST_FLAG(stack_trace_depth) > 0 michael@0: || testing::GTEST_FLAG(stream_result_to) != "unknown" michael@0: || testing::GTEST_FLAG(throw_on_failure); michael@0: EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused. michael@0: } michael@0: michael@0: #include // For INT_MAX. michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include "gtest/gtest-spi.h" michael@0: michael@0: // Indicates that this translation unit is part of Google Test's michael@0: // implementation. It must come before gtest-internal-inl.h is michael@0: // included, or there will be a compiler error. This trick is to michael@0: // prevent a user from accidentally including gtest-internal-inl.h in michael@0: // his code. michael@0: #define GTEST_IMPLEMENTATION_ 1 michael@0: #include "src/gtest-internal-inl.h" michael@0: #undef GTEST_IMPLEMENTATION_ michael@0: michael@0: namespace testing { michael@0: namespace internal { michael@0: michael@0: // Provides access to otherwise private parts of the TestEventListeners class michael@0: // that are needed to test it. michael@0: class TestEventListenersAccessor { michael@0: public: michael@0: static TestEventListener* GetRepeater(TestEventListeners* listeners) { michael@0: return listeners->repeater(); michael@0: } michael@0: michael@0: static void SetDefaultResultPrinter(TestEventListeners* listeners, michael@0: TestEventListener* listener) { michael@0: listeners->SetDefaultResultPrinter(listener); michael@0: } michael@0: static void SetDefaultXmlGenerator(TestEventListeners* listeners, michael@0: TestEventListener* listener) { michael@0: listeners->SetDefaultXmlGenerator(listener); michael@0: } michael@0: michael@0: static bool EventForwardingEnabled(const TestEventListeners& listeners) { michael@0: return listeners.EventForwardingEnabled(); michael@0: } michael@0: michael@0: static void SuppressEventForwarding(TestEventListeners* listeners) { michael@0: listeners->SuppressEventForwarding(); michael@0: } michael@0: }; michael@0: michael@0: } // namespace internal michael@0: } // namespace testing michael@0: michael@0: using testing::AssertionFailure; michael@0: using testing::AssertionResult; michael@0: using testing::AssertionSuccess; michael@0: using testing::DoubleLE; michael@0: using testing::EmptyTestEventListener; michael@0: using testing::FloatLE; michael@0: using testing::GTEST_FLAG(also_run_disabled_tests); michael@0: using testing::GTEST_FLAG(break_on_failure); michael@0: using testing::GTEST_FLAG(catch_exceptions); michael@0: using testing::GTEST_FLAG(color); michael@0: using testing::GTEST_FLAG(death_test_use_fork); michael@0: using testing::GTEST_FLAG(filter); michael@0: using testing::GTEST_FLAG(list_tests); michael@0: using testing::GTEST_FLAG(output); michael@0: using testing::GTEST_FLAG(print_time); michael@0: using testing::GTEST_FLAG(random_seed); michael@0: using testing::GTEST_FLAG(repeat); michael@0: using testing::GTEST_FLAG(show_internal_stack_frames); michael@0: using testing::GTEST_FLAG(shuffle); michael@0: using testing::GTEST_FLAG(stack_trace_depth); michael@0: using testing::GTEST_FLAG(stream_result_to); michael@0: using testing::GTEST_FLAG(throw_on_failure); michael@0: using testing::IsNotSubstring; michael@0: using testing::IsSubstring; michael@0: using testing::Message; michael@0: using testing::ScopedFakeTestPartResultReporter; michael@0: using testing::StaticAssertTypeEq; michael@0: using testing::Test; michael@0: using testing::TestCase; michael@0: using testing::TestEventListeners; michael@0: using testing::TestPartResult; michael@0: using testing::TestPartResultArray; michael@0: using testing::TestProperty; michael@0: using testing::TestResult; michael@0: using testing::TimeInMillis; michael@0: using testing::UnitTest; michael@0: using testing::kMaxStackTraceDepth; michael@0: using testing::internal::AddReference; michael@0: using testing::internal::AlwaysFalse; michael@0: using testing::internal::AlwaysTrue; michael@0: using testing::internal::AppendUserMessage; michael@0: using testing::internal::ArrayAwareFind; michael@0: using testing::internal::ArrayEq; michael@0: using testing::internal::CodePointToUtf8; michael@0: using testing::internal::CompileAssertTypesEqual; michael@0: using testing::internal::CopyArray; michael@0: using testing::internal::CountIf; michael@0: using testing::internal::EqFailure; michael@0: using testing::internal::FloatingPoint; michael@0: using testing::internal::ForEach; michael@0: using testing::internal::FormatEpochTimeInMillisAsIso8601; michael@0: using testing::internal::FormatTimeInMillisAsSeconds; michael@0: using testing::internal::GTestFlagSaver; michael@0: using testing::internal::GetCurrentOsStackTraceExceptTop; michael@0: using testing::internal::GetElementOr; michael@0: using testing::internal::GetNextRandomSeed; michael@0: using testing::internal::GetRandomSeedFromFlag; michael@0: using testing::internal::GetTestTypeId; michael@0: using testing::internal::GetTimeInMillis; michael@0: using testing::internal::GetTypeId; michael@0: using testing::internal::GetUnitTestImpl; michael@0: using testing::internal::ImplicitlyConvertible; michael@0: using testing::internal::Int32; michael@0: using testing::internal::Int32FromEnvOrDie; michael@0: using testing::internal::IsAProtocolMessage; michael@0: using testing::internal::IsContainer; michael@0: using testing::internal::IsContainerTest; michael@0: using testing::internal::IsNotContainer; michael@0: using testing::internal::NativeArray; michael@0: using testing::internal::ParseInt32Flag; michael@0: using testing::internal::RemoveConst; michael@0: using testing::internal::RemoveReference; michael@0: using testing::internal::ShouldRunTestOnShard; michael@0: using testing::internal::ShouldShard; michael@0: using testing::internal::ShouldUseColor; michael@0: using testing::internal::Shuffle; michael@0: using testing::internal::ShuffleRange; michael@0: using testing::internal::SkipPrefix; michael@0: using testing::internal::StreamableToString; michael@0: using testing::internal::String; michael@0: using testing::internal::TestEventListenersAccessor; michael@0: using testing::internal::TestResultAccessor; michael@0: using testing::internal::UInt32; michael@0: using testing::internal::WideStringToUtf8; michael@0: using testing::internal::kCopy; michael@0: using testing::internal::kMaxRandomSeed; michael@0: using testing::internal::kReference; michael@0: using testing::internal::kTestTypeIdInGoogleTest; michael@0: using testing::internal::scoped_ptr; michael@0: michael@0: #if GTEST_HAS_STREAM_REDIRECTION michael@0: using testing::internal::CaptureStdout; michael@0: using testing::internal::GetCapturedStdout; michael@0: #endif michael@0: michael@0: #if GTEST_IS_THREADSAFE michael@0: using testing::internal::ThreadWithParam; michael@0: #endif michael@0: michael@0: class TestingVector : public std::vector { michael@0: }; michael@0: michael@0: ::std::ostream& operator<<(::std::ostream& os, michael@0: const TestingVector& vector) { michael@0: os << "{ "; michael@0: for (size_t i = 0; i < vector.size(); i++) { michael@0: os << vector[i] << " "; michael@0: } michael@0: os << "}"; michael@0: return os; michael@0: } michael@0: michael@0: // This line tests that we can define tests in an unnamed namespace. michael@0: namespace { michael@0: michael@0: TEST(GetRandomSeedFromFlagTest, HandlesZero) { michael@0: const int seed = GetRandomSeedFromFlag(0); michael@0: EXPECT_LE(1, seed); michael@0: EXPECT_LE(seed, static_cast(kMaxRandomSeed)); michael@0: } michael@0: michael@0: TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) { michael@0: EXPECT_EQ(1, GetRandomSeedFromFlag(1)); michael@0: EXPECT_EQ(2, GetRandomSeedFromFlag(2)); michael@0: EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1)); michael@0: EXPECT_EQ(static_cast(kMaxRandomSeed), michael@0: GetRandomSeedFromFlag(kMaxRandomSeed)); michael@0: } michael@0: michael@0: TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) { michael@0: const int seed1 = GetRandomSeedFromFlag(-1); michael@0: EXPECT_LE(1, seed1); michael@0: EXPECT_LE(seed1, static_cast(kMaxRandomSeed)); michael@0: michael@0: const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1); michael@0: EXPECT_LE(1, seed2); michael@0: EXPECT_LE(seed2, static_cast(kMaxRandomSeed)); michael@0: } michael@0: michael@0: TEST(GetNextRandomSeedTest, WorksForValidInput) { michael@0: EXPECT_EQ(2, GetNextRandomSeed(1)); michael@0: EXPECT_EQ(3, GetNextRandomSeed(2)); michael@0: EXPECT_EQ(static_cast(kMaxRandomSeed), michael@0: GetNextRandomSeed(kMaxRandomSeed - 1)); michael@0: EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed)); michael@0: michael@0: // We deliberately don't test GetNextRandomSeed() with invalid michael@0: // inputs, as that requires death tests, which are expensive. This michael@0: // is fine as GetNextRandomSeed() is internal and has a michael@0: // straightforward definition. michael@0: } michael@0: michael@0: static void ClearCurrentTestPartResults() { michael@0: TestResultAccessor::ClearTestPartResults( michael@0: GetUnitTestImpl()->current_test_result()); michael@0: } michael@0: michael@0: // Tests GetTypeId. michael@0: michael@0: TEST(GetTypeIdTest, ReturnsSameValueForSameType) { michael@0: EXPECT_EQ(GetTypeId(), GetTypeId()); michael@0: EXPECT_EQ(GetTypeId(), GetTypeId()); michael@0: } michael@0: michael@0: class SubClassOfTest : public Test {}; michael@0: class AnotherSubClassOfTest : public Test {}; michael@0: michael@0: TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) { michael@0: EXPECT_NE(GetTypeId(), GetTypeId()); michael@0: EXPECT_NE(GetTypeId(), GetTypeId()); michael@0: EXPECT_NE(GetTypeId(), GetTestTypeId()); michael@0: EXPECT_NE(GetTypeId(), GetTestTypeId()); michael@0: EXPECT_NE(GetTypeId(), GetTestTypeId()); michael@0: EXPECT_NE(GetTypeId(), GetTypeId()); michael@0: } michael@0: michael@0: // Verifies that GetTestTypeId() returns the same value, no matter it michael@0: // is called from inside Google Test or outside of it. michael@0: TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { michael@0: EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); michael@0: } michael@0: michael@0: // Tests FormatTimeInMillisAsSeconds(). michael@0: michael@0: TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { michael@0: EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0)); michael@0: } michael@0: michael@0: TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) { michael@0: EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3)); michael@0: EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10)); michael@0: EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200)); michael@0: EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200)); michael@0: EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000)); michael@0: } michael@0: michael@0: TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) { michael@0: EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3)); michael@0: EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10)); michael@0: EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200)); michael@0: EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200)); michael@0: EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000)); michael@0: } michael@0: michael@0: // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion michael@0: // for particular dates below was verified in Python using michael@0: // datetime.datetime.fromutctimestamp(/1000). michael@0: michael@0: // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we michael@0: // have to set up a particular timezone to obtain predictable results. michael@0: class FormatEpochTimeInMillisAsIso8601Test : public Test { michael@0: public: michael@0: // On Cygwin, GCC doesn't allow unqualified integer literals to exceed michael@0: // 32 bits, even when 64-bit integer types are available. We have to michael@0: // force the constants to have a 64-bit type here. michael@0: static const TimeInMillis kMillisPerSec = 1000; michael@0: michael@0: private: michael@0: virtual void SetUp() { michael@0: saved_tz_ = NULL; michael@0: #if _MSC_VER michael@0: # pragma warning(push) // Saves the current warning state. michael@0: # pragma warning(disable:4996) // Temporarily disables warning 4996 michael@0: // (function or variable may be unsafe michael@0: // for getenv, function is deprecated for michael@0: // strdup). michael@0: if (getenv("TZ")) michael@0: saved_tz_ = strdup(getenv("TZ")); michael@0: # pragma warning(pop) // Restores the warning state again. michael@0: #else michael@0: if (getenv("TZ")) michael@0: saved_tz_ = strdup(getenv("TZ")); michael@0: #endif michael@0: michael@0: // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We michael@0: // cannot use the local time zone because the function's output depends michael@0: // on the time zone. michael@0: SetTimeZone("UTC+00"); michael@0: } michael@0: michael@0: virtual void TearDown() { michael@0: SetTimeZone(saved_tz_); michael@0: free(const_cast(saved_tz_)); michael@0: saved_tz_ = NULL; michael@0: } michael@0: michael@0: static void SetTimeZone(const char* time_zone) { michael@0: // tzset() distinguishes between the TZ variable being present and empty michael@0: // and not being present, so we have to consider the case of time_zone michael@0: // being NULL. michael@0: #if _MSC_VER michael@0: // ...Unless it's MSVC, whose standard library's _putenv doesn't michael@0: // distinguish between an empty and a missing variable. michael@0: const std::string env_var = michael@0: std::string("TZ=") + (time_zone ? time_zone : ""); michael@0: _putenv(env_var.c_str()); michael@0: # pragma warning(push) // Saves the current warning state. michael@0: # pragma warning(disable:4996) // Temporarily disables warning 4996 michael@0: // (function is deprecated). michael@0: tzset(); michael@0: # pragma warning(pop) // Restores the warning state again. michael@0: #else michael@0: if (time_zone) { michael@0: setenv(("TZ"), time_zone, 1); michael@0: } else { michael@0: unsetenv("TZ"); michael@0: } michael@0: tzset(); michael@0: #endif michael@0: } michael@0: michael@0: const char* saved_tz_; michael@0: }; michael@0: michael@0: const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec; michael@0: michael@0: TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) { michael@0: EXPECT_EQ("2011-10-31T18:52:42", michael@0: FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec)); michael@0: } michael@0: michael@0: TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) { michael@0: EXPECT_EQ( michael@0: "2011-10-31T18:52:42", michael@0: FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); michael@0: } michael@0: michael@0: TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) { michael@0: EXPECT_EQ("2011-09-03T05:07:02", michael@0: FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec)); michael@0: } michael@0: michael@0: TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) { michael@0: EXPECT_EQ("2011-09-28T17:08:22", michael@0: FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec)); michael@0: } michael@0: michael@0: TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { michael@0: EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0)); michael@0: } michael@0: michael@0: #if GTEST_CAN_COMPARE_NULL michael@0: michael@0: # ifdef __BORLANDC__ michael@0: // Silences warnings: "Condition is always true", "Unreachable code" michael@0: # pragma option push -w-ccc -w-rch michael@0: # endif michael@0: michael@0: // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null michael@0: // pointer literal. michael@0: TEST(NullLiteralTest, IsTrueForNullLiterals) { michael@0: EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL)); michael@0: EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0)); michael@0: EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U)); michael@0: EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L)); michael@0: michael@0: # ifndef __BORLANDC__ michael@0: michael@0: // Some compilers may fail to detect some null pointer literals; michael@0: // as long as users of the framework don't use such literals, this michael@0: // is harmless. michael@0: EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1)); michael@0: michael@0: # endif michael@0: } michael@0: michael@0: // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null michael@0: // pointer literal. michael@0: TEST(NullLiteralTest, IsFalseForNonNullLiterals) { michael@0: EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1)); michael@0: EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0)); michael@0: EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a')); michael@0: EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast(NULL))); michael@0: } michael@0: michael@0: # ifdef __BORLANDC__ michael@0: // Restores warnings after previous "#pragma option push" suppressed them. michael@0: # pragma option pop michael@0: # endif michael@0: michael@0: #endif // GTEST_CAN_COMPARE_NULL michael@0: // michael@0: // Tests CodePointToUtf8(). michael@0: michael@0: // Tests that the NUL character L'\0' is encoded correctly. michael@0: TEST(CodePointToUtf8Test, CanEncodeNul) { michael@0: char buffer[32]; michael@0: EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer)); michael@0: } michael@0: michael@0: // Tests that ASCII characters are encoded correctly. michael@0: TEST(CodePointToUtf8Test, CanEncodeAscii) { michael@0: char buffer[32]; michael@0: EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer)); michael@0: EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer)); michael@0: EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer)); michael@0: EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer)); michael@0: } michael@0: michael@0: // Tests that Unicode code-points that have 8 to 11 bits are encoded michael@0: // as 110xxxxx 10xxxxxx. michael@0: TEST(CodePointToUtf8Test, CanEncode8To11Bits) { michael@0: char buffer[32]; michael@0: // 000 1101 0011 => 110-00011 10-010011 michael@0: EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer)); michael@0: michael@0: // 101 0111 0110 => 110-10101 10-110110 michael@0: // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints michael@0: // in wide strings and wide chars. In order to accomodate them, we have to michael@0: // introduce such character constants as integers. michael@0: EXPECT_STREQ("\xD5\xB6", michael@0: CodePointToUtf8(static_cast(0x576), buffer)); michael@0: } michael@0: michael@0: // Tests that Unicode code-points that have 12 to 16 bits are encoded michael@0: // as 1110xxxx 10xxxxxx 10xxxxxx. michael@0: TEST(CodePointToUtf8Test, CanEncode12To16Bits) { michael@0: char buffer[32]; michael@0: // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 michael@0: EXPECT_STREQ("\xE0\xA3\x93", michael@0: CodePointToUtf8(static_cast(0x8D3), buffer)); michael@0: michael@0: // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 michael@0: EXPECT_STREQ("\xEC\x9D\x8D", michael@0: CodePointToUtf8(static_cast(0xC74D), buffer)); michael@0: } michael@0: michael@0: #if !GTEST_WIDE_STRING_USES_UTF16_ michael@0: // Tests in this group require a wchar_t to hold > 16 bits, and thus michael@0: // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is michael@0: // 16-bit wide. This code may not compile on those systems. michael@0: michael@0: // Tests that Unicode code-points that have 17 to 21 bits are encoded michael@0: // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. michael@0: TEST(CodePointToUtf8Test, CanEncode17To21Bits) { michael@0: char buffer[32]; michael@0: // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 michael@0: EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer)); michael@0: michael@0: // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000 michael@0: EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer)); michael@0: michael@0: // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 michael@0: EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer)); michael@0: } michael@0: michael@0: // Tests that encoding an invalid code-point generates the expected result. michael@0: TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) { michael@0: char buffer[32]; michael@0: EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)", michael@0: CodePointToUtf8(L'\x1234ABCD', buffer)); michael@0: } michael@0: michael@0: #endif // !GTEST_WIDE_STRING_USES_UTF16_ michael@0: michael@0: // Tests WideStringToUtf8(). michael@0: michael@0: // Tests that the NUL character L'\0' is encoded correctly. michael@0: TEST(WideStringToUtf8Test, CanEncodeNul) { michael@0: EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str()); michael@0: EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str()); michael@0: } michael@0: michael@0: // Tests that ASCII strings are encoded correctly. michael@0: TEST(WideStringToUtf8Test, CanEncodeAscii) { michael@0: EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str()); michael@0: EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str()); michael@0: EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str()); michael@0: EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str()); michael@0: } michael@0: michael@0: // Tests that Unicode code-points that have 8 to 11 bits are encoded michael@0: // as 110xxxxx 10xxxxxx. michael@0: TEST(WideStringToUtf8Test, CanEncode8To11Bits) { michael@0: // 000 1101 0011 => 110-00011 10-010011 michael@0: EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str()); michael@0: EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); michael@0: michael@0: // 101 0111 0110 => 110-10101 10-110110 michael@0: const wchar_t s[] = { 0x576, '\0' }; michael@0: EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); michael@0: EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); michael@0: } michael@0: michael@0: // Tests that Unicode code-points that have 12 to 16 bits are encoded michael@0: // as 1110xxxx 10xxxxxx 10xxxxxx. michael@0: TEST(WideStringToUtf8Test, CanEncode12To16Bits) { michael@0: // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 michael@0: const wchar_t s1[] = { 0x8D3, '\0' }; michael@0: EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); michael@0: EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); michael@0: michael@0: // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 michael@0: const wchar_t s2[] = { 0xC74D, '\0' }; michael@0: EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); michael@0: EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); michael@0: } michael@0: michael@0: // Tests that the conversion stops when the function encounters \0 character. michael@0: TEST(WideStringToUtf8Test, StopsOnNulCharacter) { michael@0: EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str()); michael@0: } michael@0: michael@0: // Tests that the conversion stops when the function reaches the limit michael@0: // specified by the 'length' parameter. michael@0: TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) { michael@0: EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str()); michael@0: } michael@0: michael@0: #if !GTEST_WIDE_STRING_USES_UTF16_ michael@0: // Tests that Unicode code-points that have 17 to 21 bits are encoded michael@0: // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile michael@0: // on the systems using UTF-16 encoding. michael@0: TEST(WideStringToUtf8Test, CanEncode17To21Bits) { michael@0: // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 michael@0: EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str()); michael@0: EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str()); michael@0: michael@0: // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 michael@0: EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str()); michael@0: EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str()); michael@0: } michael@0: michael@0: // Tests that encoding an invalid code-point generates the expected result. michael@0: TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { michael@0: EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", michael@0: WideStringToUtf8(L"\xABCDFF", -1).c_str()); michael@0: } michael@0: #else // !GTEST_WIDE_STRING_USES_UTF16_ michael@0: // Tests that surrogate pairs are encoded correctly on the systems using michael@0: // UTF-16 encoding in the wide strings. michael@0: TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { michael@0: const wchar_t s[] = { 0xD801, 0xDC00, '\0' }; michael@0: EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); michael@0: } michael@0: michael@0: // Tests that encoding an invalid UTF-16 surrogate pair michael@0: // generates the expected result. michael@0: TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { michael@0: // Leading surrogate is at the end of the string. michael@0: const wchar_t s1[] = { 0xD800, '\0' }; michael@0: EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); michael@0: // Leading surrogate is not followed by the trailing surrogate. michael@0: const wchar_t s2[] = { 0xD800, 'M', '\0' }; michael@0: EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); michael@0: // Trailing surrogate appearas without a leading surrogate. michael@0: const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' }; michael@0: EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); michael@0: } michael@0: #endif // !GTEST_WIDE_STRING_USES_UTF16_ michael@0: michael@0: // Tests that codepoint concatenation works correctly. michael@0: #if !GTEST_WIDE_STRING_USES_UTF16_ michael@0: TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { michael@0: const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; michael@0: EXPECT_STREQ( michael@0: "\xF4\x88\x98\xB4" michael@0: "\xEC\x9D\x8D" michael@0: "\n" michael@0: "\xD5\xB6" michael@0: "\xE0\xA3\x93" michael@0: "\xF4\x88\x98\xB4", michael@0: WideStringToUtf8(s, -1).c_str()); michael@0: } michael@0: #else michael@0: TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { michael@0: const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'}; michael@0: EXPECT_STREQ( michael@0: "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", michael@0: WideStringToUtf8(s, -1).c_str()); michael@0: } michael@0: #endif // !GTEST_WIDE_STRING_USES_UTF16_ michael@0: michael@0: // Tests the Random class. michael@0: michael@0: TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { michael@0: testing::internal::Random random(42); michael@0: EXPECT_DEATH_IF_SUPPORTED( michael@0: random.Generate(0), michael@0: "Cannot generate a number in the range \\[0, 0\\)"); michael@0: EXPECT_DEATH_IF_SUPPORTED( michael@0: random.Generate(testing::internal::Random::kMaxRange + 1), michael@0: "Generation of a number in \\[0, 2147483649\\) was requested, " michael@0: "but this can only generate numbers in \\[0, 2147483648\\)"); michael@0: } michael@0: michael@0: TEST(RandomTest, GeneratesNumbersWithinRange) { michael@0: const UInt32 kRange = 10000; michael@0: testing::internal::Random random(12345); michael@0: for (int i = 0; i < 10; i++) { michael@0: EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i; michael@0: } michael@0: michael@0: testing::internal::Random random2(testing::internal::Random::kMaxRange); michael@0: for (int i = 0; i < 10; i++) { michael@0: EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i; michael@0: } michael@0: } michael@0: michael@0: TEST(RandomTest, RepeatsWhenReseeded) { michael@0: const int kSeed = 123; michael@0: const int kArraySize = 10; michael@0: const UInt32 kRange = 10000; michael@0: UInt32 values[kArraySize]; michael@0: michael@0: testing::internal::Random random(kSeed); michael@0: for (int i = 0; i < kArraySize; i++) { michael@0: values[i] = random.Generate(kRange); michael@0: } michael@0: michael@0: random.Reseed(kSeed); michael@0: for (int i = 0; i < kArraySize; i++) { michael@0: EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i; michael@0: } michael@0: } michael@0: michael@0: // Tests STL container utilities. michael@0: michael@0: // Tests CountIf(). michael@0: michael@0: static bool IsPositive(int n) { return n > 0; } michael@0: michael@0: TEST(ContainerUtilityTest, CountIf) { michael@0: std::vector v; michael@0: EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container. michael@0: michael@0: v.push_back(-1); michael@0: v.push_back(0); michael@0: EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies. michael@0: michael@0: v.push_back(2); michael@0: v.push_back(-10); michael@0: v.push_back(10); michael@0: EXPECT_EQ(2, CountIf(v, IsPositive)); michael@0: } michael@0: michael@0: // Tests ForEach(). michael@0: michael@0: static int g_sum = 0; michael@0: static void Accumulate(int n) { g_sum += n; } michael@0: michael@0: TEST(ContainerUtilityTest, ForEach) { michael@0: std::vector v; michael@0: g_sum = 0; michael@0: ForEach(v, Accumulate); michael@0: EXPECT_EQ(0, g_sum); // Works for an empty container; michael@0: michael@0: g_sum = 0; michael@0: v.push_back(1); michael@0: ForEach(v, Accumulate); michael@0: EXPECT_EQ(1, g_sum); // Works for a container with one element. michael@0: michael@0: g_sum = 0; michael@0: v.push_back(20); michael@0: v.push_back(300); michael@0: ForEach(v, Accumulate); michael@0: EXPECT_EQ(321, g_sum); michael@0: } michael@0: michael@0: // Tests GetElementOr(). michael@0: TEST(ContainerUtilityTest, GetElementOr) { michael@0: std::vector a; michael@0: EXPECT_EQ('x', GetElementOr(a, 0, 'x')); michael@0: michael@0: a.push_back('a'); michael@0: a.push_back('b'); michael@0: EXPECT_EQ('a', GetElementOr(a, 0, 'x')); michael@0: EXPECT_EQ('b', GetElementOr(a, 1, 'x')); michael@0: EXPECT_EQ('x', GetElementOr(a, -2, 'x')); michael@0: EXPECT_EQ('x', GetElementOr(a, 2, 'x')); michael@0: } michael@0: michael@0: TEST(ContainerUtilityDeathTest, ShuffleRange) { michael@0: std::vector a; michael@0: a.push_back(0); michael@0: a.push_back(1); michael@0: a.push_back(2); michael@0: testing::internal::Random random(1); michael@0: michael@0: EXPECT_DEATH_IF_SUPPORTED( michael@0: ShuffleRange(&random, -1, 1, &a), michael@0: "Invalid shuffle range start -1: must be in range \\[0, 3\\]"); michael@0: EXPECT_DEATH_IF_SUPPORTED( michael@0: ShuffleRange(&random, 4, 4, &a), michael@0: "Invalid shuffle range start 4: must be in range \\[0, 3\\]"); michael@0: EXPECT_DEATH_IF_SUPPORTED( michael@0: ShuffleRange(&random, 3, 2, &a), michael@0: "Invalid shuffle range finish 2: must be in range \\[3, 3\\]"); michael@0: EXPECT_DEATH_IF_SUPPORTED( michael@0: ShuffleRange(&random, 3, 4, &a), michael@0: "Invalid shuffle range finish 4: must be in range \\[3, 3\\]"); michael@0: } michael@0: michael@0: class VectorShuffleTest : public Test { michael@0: protected: michael@0: static const int kVectorSize = 20; michael@0: michael@0: VectorShuffleTest() : random_(1) { michael@0: for (int i = 0; i < kVectorSize; i++) { michael@0: vector_.push_back(i); michael@0: } michael@0: } michael@0: michael@0: static bool VectorIsCorrupt(const TestingVector& vector) { michael@0: if (kVectorSize != static_cast(vector.size())) { michael@0: return true; michael@0: } michael@0: michael@0: bool found_in_vector[kVectorSize] = { false }; michael@0: for (size_t i = 0; i < vector.size(); i++) { michael@0: const int e = vector[i]; michael@0: if (e < 0 || e >= kVectorSize || found_in_vector[e]) { michael@0: return true; michael@0: } michael@0: found_in_vector[e] = true; michael@0: } michael@0: michael@0: // Vector size is correct, elements' range is correct, no michael@0: // duplicate elements. Therefore no corruption has occurred. michael@0: return false; michael@0: } michael@0: michael@0: static bool VectorIsNotCorrupt(const TestingVector& vector) { michael@0: return !VectorIsCorrupt(vector); michael@0: } michael@0: michael@0: static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) { michael@0: for (int i = begin; i < end; i++) { michael@0: if (i != vector[i]) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: static bool RangeIsUnshuffled( michael@0: const TestingVector& vector, int begin, int end) { michael@0: return !RangeIsShuffled(vector, begin, end); michael@0: } michael@0: michael@0: static bool VectorIsShuffled(const TestingVector& vector) { michael@0: return RangeIsShuffled(vector, 0, static_cast(vector.size())); michael@0: } michael@0: michael@0: static bool VectorIsUnshuffled(const TestingVector& vector) { michael@0: return !VectorIsShuffled(vector); michael@0: } michael@0: michael@0: testing::internal::Random random_; michael@0: TestingVector vector_; michael@0: }; // class VectorShuffleTest michael@0: michael@0: const int VectorShuffleTest::kVectorSize; michael@0: michael@0: TEST_F(VectorShuffleTest, HandlesEmptyRange) { michael@0: // Tests an empty range at the beginning... michael@0: ShuffleRange(&random_, 0, 0, &vector_); michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: ASSERT_PRED1(VectorIsUnshuffled, vector_); michael@0: michael@0: // ...in the middle... michael@0: ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_); michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: ASSERT_PRED1(VectorIsUnshuffled, vector_); michael@0: michael@0: // ...at the end... michael@0: ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_); michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: ASSERT_PRED1(VectorIsUnshuffled, vector_); michael@0: michael@0: // ...and past the end. michael@0: ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_); michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: ASSERT_PRED1(VectorIsUnshuffled, vector_); michael@0: } michael@0: michael@0: TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) { michael@0: // Tests a size one range at the beginning... michael@0: ShuffleRange(&random_, 0, 1, &vector_); michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: ASSERT_PRED1(VectorIsUnshuffled, vector_); michael@0: michael@0: // ...in the middle... michael@0: ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_); michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: ASSERT_PRED1(VectorIsUnshuffled, vector_); michael@0: michael@0: // ...and at the end. michael@0: ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_); michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: ASSERT_PRED1(VectorIsUnshuffled, vector_); michael@0: } michael@0: michael@0: // Because we use our own random number generator and a fixed seed, michael@0: // we can guarantee that the following "random" tests will succeed. michael@0: michael@0: TEST_F(VectorShuffleTest, ShufflesEntireVector) { michael@0: Shuffle(&random_, &vector_); michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_; michael@0: michael@0: // Tests the first and last elements in particular to ensure that michael@0: // there are no off-by-one problems in our shuffle algorithm. michael@0: EXPECT_NE(0, vector_[0]); michael@0: EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]); michael@0: } michael@0: michael@0: TEST_F(VectorShuffleTest, ShufflesStartOfVector) { michael@0: const int kRangeSize = kVectorSize/2; michael@0: michael@0: ShuffleRange(&random_, 0, kRangeSize, &vector_); michael@0: michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize); michael@0: EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize); michael@0: } michael@0: michael@0: TEST_F(VectorShuffleTest, ShufflesEndOfVector) { michael@0: const int kRangeSize = kVectorSize / 2; michael@0: ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_); michael@0: michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); michael@0: EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize); michael@0: } michael@0: michael@0: TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) { michael@0: int kRangeSize = kVectorSize/3; michael@0: ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_); michael@0: michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); michael@0: EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize); michael@0: EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize); michael@0: } michael@0: michael@0: TEST_F(VectorShuffleTest, ShufflesRepeatably) { michael@0: TestingVector vector2; michael@0: for (int i = 0; i < kVectorSize; i++) { michael@0: vector2.push_back(i); michael@0: } michael@0: michael@0: random_.Reseed(1234); michael@0: Shuffle(&random_, &vector_); michael@0: random_.Reseed(1234); michael@0: Shuffle(&random_, &vector2); michael@0: michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector_); michael@0: ASSERT_PRED1(VectorIsNotCorrupt, vector2); michael@0: michael@0: for (int i = 0; i < kVectorSize; i++) { michael@0: EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i; michael@0: } michael@0: } michael@0: michael@0: // Tests the size of the AssertHelper class. michael@0: michael@0: TEST(AssertHelperTest, AssertHelperIsSmall) { michael@0: // To avoid breaking clients that use lots of assertions in one michael@0: // function, we cannot grow the size of AssertHelper. michael@0: EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*)); michael@0: } michael@0: michael@0: // Tests the String class. michael@0: michael@0: // Tests String's constructors. michael@0: TEST(StringTest, Constructors) { michael@0: // Default ctor. michael@0: String s1; michael@0: // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing michael@0: // pointers with NULL isn't supported on all platforms. michael@0: EXPECT_EQ(0U, s1.length()); michael@0: EXPECT_TRUE(NULL == s1.c_str()); michael@0: michael@0: // Implicitly constructs from a C-string. michael@0: String s2 = "Hi"; michael@0: EXPECT_EQ(2U, s2.length()); michael@0: EXPECT_STREQ("Hi", s2.c_str()); michael@0: michael@0: // Constructs from a C-string and a length. michael@0: String s3("hello", 3); michael@0: EXPECT_EQ(3U, s3.length()); michael@0: EXPECT_STREQ("hel", s3.c_str()); michael@0: michael@0: // The empty String should be created when String is constructed with michael@0: // a NULL pointer and length 0. michael@0: EXPECT_EQ(0U, String(NULL, 0).length()); michael@0: EXPECT_FALSE(String(NULL, 0).c_str() == NULL); michael@0: michael@0: // Constructs a String that contains '\0'. michael@0: String s4("a\0bcd", 4); michael@0: EXPECT_EQ(4U, s4.length()); michael@0: EXPECT_EQ('a', s4.c_str()[0]); michael@0: EXPECT_EQ('\0', s4.c_str()[1]); michael@0: EXPECT_EQ('b', s4.c_str()[2]); michael@0: EXPECT_EQ('c', s4.c_str()[3]); michael@0: michael@0: // Copy ctor where the source is NULL. michael@0: const String null_str; michael@0: String s5 = null_str; michael@0: EXPECT_TRUE(s5.c_str() == NULL); michael@0: michael@0: // Copy ctor where the source isn't NULL. michael@0: String s6 = s3; michael@0: EXPECT_EQ(3U, s6.length()); michael@0: EXPECT_STREQ("hel", s6.c_str()); michael@0: michael@0: // Copy ctor where the source contains '\0'. michael@0: String s7 = s4; michael@0: EXPECT_EQ(4U, s7.length()); michael@0: EXPECT_EQ('a', s7.c_str()[0]); michael@0: EXPECT_EQ('\0', s7.c_str()[1]); michael@0: EXPECT_EQ('b', s7.c_str()[2]); michael@0: EXPECT_EQ('c', s7.c_str()[3]); michael@0: } michael@0: michael@0: TEST(StringTest, ConvertsFromStdString) { michael@0: // An empty std::string. michael@0: const std::string src1(""); michael@0: const String dest1 = src1; michael@0: EXPECT_EQ(0U, dest1.length()); michael@0: EXPECT_STREQ("", dest1.c_str()); michael@0: michael@0: // A normal std::string. michael@0: const std::string src2("Hi"); michael@0: const String dest2 = src2; michael@0: EXPECT_EQ(2U, dest2.length()); michael@0: EXPECT_STREQ("Hi", dest2.c_str()); michael@0: michael@0: // An std::string with an embedded NUL character. michael@0: const char src3[] = "a\0b"; michael@0: const String dest3 = std::string(src3, sizeof(src3)); michael@0: EXPECT_EQ(sizeof(src3), dest3.length()); michael@0: EXPECT_EQ('a', dest3.c_str()[0]); michael@0: EXPECT_EQ('\0', dest3.c_str()[1]); michael@0: EXPECT_EQ('b', dest3.c_str()[2]); michael@0: } michael@0: michael@0: TEST(StringTest, ConvertsToStdString) { michael@0: // An empty String. michael@0: const String src1(""); michael@0: const std::string dest1 = src1; michael@0: EXPECT_EQ("", dest1); michael@0: michael@0: // A normal String. michael@0: const String src2("Hi"); michael@0: const std::string dest2 = src2; michael@0: EXPECT_EQ("Hi", dest2); michael@0: michael@0: // A String containing a '\0'. michael@0: const String src3("x\0y", 3); michael@0: const std::string dest3 = src3; michael@0: EXPECT_EQ(std::string("x\0y", 3), dest3); michael@0: } michael@0: michael@0: #if GTEST_HAS_GLOBAL_STRING michael@0: michael@0: TEST(StringTest, ConvertsFromGlobalString) { michael@0: // An empty ::string. michael@0: const ::string src1(""); michael@0: const String dest1 = src1; michael@0: EXPECT_EQ(0U, dest1.length()); michael@0: EXPECT_STREQ("", dest1.c_str()); michael@0: michael@0: // A normal ::string. michael@0: const ::string src2("Hi"); michael@0: const String dest2 = src2; michael@0: EXPECT_EQ(2U, dest2.length()); michael@0: EXPECT_STREQ("Hi", dest2.c_str()); michael@0: michael@0: // An ::string with an embedded NUL character. michael@0: const char src3[] = "x\0y"; michael@0: const String dest3 = ::string(src3, sizeof(src3)); michael@0: EXPECT_EQ(sizeof(src3), dest3.length()); michael@0: EXPECT_EQ('x', dest3.c_str()[0]); michael@0: EXPECT_EQ('\0', dest3.c_str()[1]); michael@0: EXPECT_EQ('y', dest3.c_str()[2]); michael@0: } michael@0: michael@0: TEST(StringTest, ConvertsToGlobalString) { michael@0: // An empty String. michael@0: const String src1(""); michael@0: const ::string dest1 = src1; michael@0: EXPECT_EQ("", dest1); michael@0: michael@0: // A normal String. michael@0: const String src2("Hi"); michael@0: const ::string dest2 = src2; michael@0: EXPECT_EQ("Hi", dest2); michael@0: michael@0: const String src3("x\0y", 3); michael@0: const ::string dest3 = src3; michael@0: EXPECT_EQ(::string("x\0y", 3), dest3); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_GLOBAL_STRING michael@0: michael@0: // Tests String::empty(). michael@0: TEST(StringTest, Empty) { michael@0: EXPECT_TRUE(String("").empty()); michael@0: EXPECT_FALSE(String().empty()); michael@0: EXPECT_FALSE(String(NULL).empty()); michael@0: EXPECT_FALSE(String("a").empty()); michael@0: EXPECT_FALSE(String("\0", 1).empty()); michael@0: } michael@0: michael@0: // Tests String::Compare(). michael@0: TEST(StringTest, Compare) { michael@0: // NULL vs NULL. michael@0: EXPECT_EQ(0, String().Compare(String())); michael@0: michael@0: // NULL vs non-NULL. michael@0: EXPECT_EQ(-1, String().Compare(String(""))); michael@0: michael@0: // Non-NULL vs NULL. michael@0: EXPECT_EQ(1, String("").Compare(String())); michael@0: michael@0: // The following covers non-NULL vs non-NULL. michael@0: michael@0: // "" vs "". michael@0: EXPECT_EQ(0, String("").Compare(String(""))); michael@0: michael@0: // "" vs non-"". michael@0: EXPECT_EQ(-1, String("").Compare(String("\0", 1))); michael@0: EXPECT_EQ(-1, String("").Compare(" ")); michael@0: michael@0: // Non-"" vs "". michael@0: EXPECT_EQ(1, String("a").Compare(String(""))); michael@0: michael@0: // The following covers non-"" vs non-"". michael@0: michael@0: // Same length and equal. michael@0: EXPECT_EQ(0, String("a").Compare(String("a"))); michael@0: michael@0: // Same length and different. michael@0: EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3))); michael@0: EXPECT_EQ(1, String("b").Compare(String("a"))); michael@0: michael@0: // Different lengths. michael@0: EXPECT_EQ(-1, String("a").Compare(String("ab"))); michael@0: EXPECT_EQ(-1, String("a").Compare(String("a\0", 2))); michael@0: EXPECT_EQ(1, String("abc").Compare(String("aacd"))); michael@0: } michael@0: michael@0: // Tests String::operator==(). michael@0: TEST(StringTest, Equals) { michael@0: const String null(NULL); michael@0: EXPECT_TRUE(null == NULL); // NOLINT michael@0: EXPECT_FALSE(null == ""); // NOLINT michael@0: EXPECT_FALSE(null == "bar"); // NOLINT michael@0: michael@0: const String empty(""); michael@0: EXPECT_FALSE(empty == NULL); // NOLINT michael@0: EXPECT_TRUE(empty == ""); // NOLINT michael@0: EXPECT_FALSE(empty == "bar"); // NOLINT michael@0: michael@0: const String foo("foo"); michael@0: EXPECT_FALSE(foo == NULL); // NOLINT michael@0: EXPECT_FALSE(foo == ""); // NOLINT michael@0: EXPECT_FALSE(foo == "bar"); // NOLINT michael@0: EXPECT_TRUE(foo == "foo"); // NOLINT michael@0: michael@0: const String bar("x\0y", 3); michael@0: EXPECT_NE(bar, "x"); michael@0: } michael@0: michael@0: // Tests String::operator!=(). michael@0: TEST(StringTest, NotEquals) { michael@0: const String null(NULL); michael@0: EXPECT_FALSE(null != NULL); // NOLINT michael@0: EXPECT_TRUE(null != ""); // NOLINT michael@0: EXPECT_TRUE(null != "bar"); // NOLINT michael@0: michael@0: const String empty(""); michael@0: EXPECT_TRUE(empty != NULL); // NOLINT michael@0: EXPECT_FALSE(empty != ""); // NOLINT michael@0: EXPECT_TRUE(empty != "bar"); // NOLINT michael@0: michael@0: const String foo("foo"); michael@0: EXPECT_TRUE(foo != NULL); // NOLINT michael@0: EXPECT_TRUE(foo != ""); // NOLINT michael@0: EXPECT_TRUE(foo != "bar"); // NOLINT michael@0: EXPECT_FALSE(foo != "foo"); // NOLINT michael@0: michael@0: const String bar("x\0y", 3); michael@0: EXPECT_NE(bar, "x"); michael@0: } michael@0: michael@0: // Tests String::length(). michael@0: TEST(StringTest, Length) { michael@0: EXPECT_EQ(0U, String().length()); michael@0: EXPECT_EQ(0U, String("").length()); michael@0: EXPECT_EQ(2U, String("ab").length()); michael@0: EXPECT_EQ(3U, String("a\0b", 3).length()); michael@0: } michael@0: michael@0: // Tests String::EndsWith(). michael@0: TEST(StringTest, EndsWith) { michael@0: EXPECT_TRUE(String("foobar").EndsWith("bar")); michael@0: EXPECT_TRUE(String("foobar").EndsWith("")); michael@0: EXPECT_TRUE(String("").EndsWith("")); michael@0: michael@0: EXPECT_FALSE(String("foobar").EndsWith("foo")); michael@0: EXPECT_FALSE(String("").EndsWith("foo")); michael@0: } michael@0: michael@0: // Tests String::EndsWithCaseInsensitive(). michael@0: TEST(StringTest, EndsWithCaseInsensitive) { michael@0: EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR")); michael@0: EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar")); michael@0: EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("")); michael@0: EXPECT_TRUE(String("").EndsWithCaseInsensitive("")); michael@0: michael@0: EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo")); michael@0: EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo")); michael@0: EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo")); michael@0: } michael@0: michael@0: // C++Builder's preprocessor is buggy; it fails to expand macros that michael@0: // appear in macro parameters after wide char literals. Provide an alias michael@0: // for NULL as a workaround. michael@0: static const wchar_t* const kNull = NULL; michael@0: michael@0: // Tests String::CaseInsensitiveWideCStringEquals michael@0: TEST(StringTest, CaseInsensitiveWideCStringEquals) { michael@0: EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL)); michael@0: EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"")); michael@0: EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull)); michael@0: EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar")); michael@0: EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull)); michael@0: EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar")); michael@0: EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR")); michael@0: EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar")); michael@0: } michael@0: michael@0: // Tests that NULL can be assigned to a String. michael@0: TEST(StringTest, CanBeAssignedNULL) { michael@0: const String src(NULL); michael@0: String dest; michael@0: michael@0: dest = src; michael@0: EXPECT_STREQ(NULL, dest.c_str()); michael@0: } michael@0: michael@0: // Tests that the empty string "" can be assigned to a String. michael@0: TEST(StringTest, CanBeAssignedEmpty) { michael@0: const String src(""); michael@0: String dest; michael@0: michael@0: dest = src; michael@0: EXPECT_STREQ("", dest.c_str()); michael@0: } michael@0: michael@0: // Tests that a non-empty string can be assigned to a String. michael@0: TEST(StringTest, CanBeAssignedNonEmpty) { michael@0: const String src("hello"); michael@0: String dest; michael@0: dest = src; michael@0: EXPECT_EQ(5U, dest.length()); michael@0: EXPECT_STREQ("hello", dest.c_str()); michael@0: michael@0: const String src2("x\0y", 3); michael@0: String dest2; michael@0: dest2 = src2; michael@0: EXPECT_EQ(3U, dest2.length()); michael@0: EXPECT_EQ('x', dest2.c_str()[0]); michael@0: EXPECT_EQ('\0', dest2.c_str()[1]); michael@0: EXPECT_EQ('y', dest2.c_str()[2]); michael@0: } michael@0: michael@0: // Tests that a String can be assigned to itself. michael@0: TEST(StringTest, CanBeAssignedSelf) { michael@0: String dest("hello"); michael@0: michael@0: // Use explicit function call notation here to suppress self-assign warning. michael@0: dest.operator=(dest); michael@0: EXPECT_STREQ("hello", dest.c_str()); michael@0: } michael@0: michael@0: // Sun Studio < 12 incorrectly rejects this code due to an overloading michael@0: // ambiguity. michael@0: #if !(defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) michael@0: // Tests streaming a String. michael@0: TEST(StringTest, Streams) { michael@0: EXPECT_EQ(StreamableToString(String()), "(null)"); michael@0: EXPECT_EQ(StreamableToString(String("")), ""); michael@0: EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b"); michael@0: } michael@0: #endif michael@0: michael@0: // Tests that String::Format() works. michael@0: TEST(StringTest, FormatWorks) { michael@0: // Normal case: the format spec is valid, the arguments match the michael@0: // spec, and the result is < 4095 characters. michael@0: EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str()); michael@0: michael@0: // Edge case: the result is 4095 characters. michael@0: char buffer[4096]; michael@0: const size_t kSize = sizeof(buffer); michael@0: memset(buffer, 'a', kSize - 1); michael@0: buffer[kSize - 1] = '\0'; michael@0: EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str()); michael@0: michael@0: // The result needs to be 4096 characters, exceeding Format()'s limit. michael@0: EXPECT_STREQ("", michael@0: String::Format("x%s", buffer).c_str()); michael@0: michael@0: #if GTEST_OS_LINUX michael@0: // On Linux, invalid format spec should lead to an error message. michael@0: // In other environment (e.g. MSVC on Windows), String::Format() may michael@0: // simply ignore a bad format spec, so this assertion is run on michael@0: // Linux only. michael@0: EXPECT_STREQ("", michael@0: String::Format("%").c_str()); michael@0: #endif michael@0: } michael@0: michael@0: #if GTEST_OS_WINDOWS michael@0: michael@0: // Tests String::ShowWideCString(). michael@0: TEST(StringTest, ShowWideCString) { michael@0: EXPECT_STREQ("(null)", michael@0: String::ShowWideCString(NULL).c_str()); michael@0: EXPECT_STREQ("", String::ShowWideCString(L"").c_str()); michael@0: EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str()); michael@0: } michael@0: michael@0: # if GTEST_OS_WINDOWS_MOBILE michael@0: TEST(StringTest, AnsiAndUtf16Null) { michael@0: EXPECT_EQ(NULL, String::AnsiToUtf16(NULL)); michael@0: EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL)); michael@0: } michael@0: michael@0: TEST(StringTest, AnsiAndUtf16ConvertBasic) { michael@0: const char* ansi = String::Utf16ToAnsi(L"str"); michael@0: EXPECT_STREQ("str", ansi); michael@0: delete [] ansi; michael@0: const WCHAR* utf16 = String::AnsiToUtf16("str"); michael@0: EXPECT_EQ(0, wcsncmp(L"str", utf16, 3)); michael@0: delete [] utf16; michael@0: } michael@0: michael@0: TEST(StringTest, AnsiAndUtf16ConvertPathChars) { michael@0: const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?"); michael@0: EXPECT_STREQ(".:\\ \"*?", ansi); michael@0: delete [] ansi; michael@0: const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?"); michael@0: EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3)); michael@0: delete [] utf16; michael@0: } michael@0: # endif // GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: #endif // GTEST_OS_WINDOWS michael@0: michael@0: // Tests TestProperty construction. michael@0: TEST(TestPropertyTest, StringValue) { michael@0: TestProperty property("key", "1"); michael@0: EXPECT_STREQ("key", property.key()); michael@0: EXPECT_STREQ("1", property.value()); michael@0: } michael@0: michael@0: // Tests TestProperty replacing a value. michael@0: TEST(TestPropertyTest, ReplaceStringValue) { michael@0: TestProperty property("key", "1"); michael@0: EXPECT_STREQ("1", property.value()); michael@0: property.SetValue("2"); michael@0: EXPECT_STREQ("2", property.value()); michael@0: } michael@0: michael@0: // AddFatalFailure() and AddNonfatalFailure() must be stand-alone michael@0: // functions (i.e. their definitions cannot be inlined at the call michael@0: // sites), or C++Builder won't compile the code. michael@0: static void AddFatalFailure() { michael@0: FAIL() << "Expected fatal failure."; michael@0: } michael@0: michael@0: static void AddNonfatalFailure() { michael@0: ADD_FAILURE() << "Expected non-fatal failure."; michael@0: } michael@0: michael@0: class ScopedFakeTestPartResultReporterTest : public Test { michael@0: public: // Must be public and not protected due to a bug in g++ 3.4.2. michael@0: enum FailureMode { michael@0: FATAL_FAILURE, michael@0: NONFATAL_FAILURE michael@0: }; michael@0: static void AddFailure(FailureMode failure) { michael@0: if (failure == FATAL_FAILURE) { michael@0: AddFatalFailure(); michael@0: } else { michael@0: AddNonfatalFailure(); michael@0: } michael@0: } michael@0: }; michael@0: michael@0: // Tests that ScopedFakeTestPartResultReporter intercepts test michael@0: // failures. michael@0: TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) { michael@0: TestPartResultArray results; michael@0: { michael@0: ScopedFakeTestPartResultReporter reporter( michael@0: ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, michael@0: &results); michael@0: AddFailure(NONFATAL_FAILURE); michael@0: AddFailure(FATAL_FAILURE); michael@0: } michael@0: michael@0: EXPECT_EQ(2, results.size()); michael@0: EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); michael@0: EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); michael@0: } michael@0: michael@0: TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) { michael@0: TestPartResultArray results; michael@0: { michael@0: // Tests, that the deprecated constructor still works. michael@0: ScopedFakeTestPartResultReporter reporter(&results); michael@0: AddFailure(NONFATAL_FAILURE); michael@0: } michael@0: EXPECT_EQ(1, results.size()); michael@0: } michael@0: michael@0: #if GTEST_IS_THREADSAFE michael@0: michael@0: class ScopedFakeTestPartResultReporterWithThreadsTest michael@0: : public ScopedFakeTestPartResultReporterTest { michael@0: protected: michael@0: static void AddFailureInOtherThread(FailureMode failure) { michael@0: ThreadWithParam thread(&AddFailure, failure, NULL); michael@0: thread.Join(); michael@0: } michael@0: }; michael@0: michael@0: TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest, michael@0: InterceptsTestFailuresInAllThreads) { michael@0: TestPartResultArray results; michael@0: { michael@0: ScopedFakeTestPartResultReporter reporter( michael@0: ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results); michael@0: AddFailure(NONFATAL_FAILURE); michael@0: AddFailure(FATAL_FAILURE); michael@0: AddFailureInOtherThread(NONFATAL_FAILURE); michael@0: AddFailureInOtherThread(FATAL_FAILURE); michael@0: } michael@0: michael@0: EXPECT_EQ(4, results.size()); michael@0: EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); michael@0: EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); michael@0: EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed()); michael@0: EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed()); michael@0: } michael@0: michael@0: #endif // GTEST_IS_THREADSAFE michael@0: michael@0: // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they michael@0: // work even if the failure is generated in a called function rather than michael@0: // the current context. michael@0: michael@0: typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest; michael@0: michael@0: TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) { michael@0: EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure."); michael@0: } michael@0: michael@0: #if GTEST_HAS_GLOBAL_STRING michael@0: TEST_F(ExpectFatalFailureTest, AcceptsStringObject) { michael@0: EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure.")); michael@0: } michael@0: #endif michael@0: michael@0: TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) { michael@0: EXPECT_FATAL_FAILURE(AddFatalFailure(), michael@0: ::std::string("Expected fatal failure.")); michael@0: } michael@0: michael@0: TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) { michael@0: // We have another test below to verify that the macro catches fatal michael@0: // failures generated on another thread. michael@0: EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(), michael@0: "Expected fatal failure."); michael@0: } michael@0: michael@0: #ifdef __BORLANDC__ michael@0: // Silences warnings: "Condition is always true" michael@0: # pragma option push -w-ccc michael@0: #endif michael@0: michael@0: // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void michael@0: // function even when the statement in it contains ASSERT_*. michael@0: michael@0: int NonVoidFunction() { michael@0: EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); michael@0: EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); michael@0: return 0; michael@0: } michael@0: michael@0: TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) { michael@0: NonVoidFunction(); michael@0: } michael@0: michael@0: // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the michael@0: // current function even though 'statement' generates a fatal failure. michael@0: michael@0: void DoesNotAbortHelper(bool* aborted) { michael@0: EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); michael@0: EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); michael@0: michael@0: *aborted = false; michael@0: } michael@0: michael@0: #ifdef __BORLANDC__ michael@0: // Restores warnings after previous "#pragma option push" suppressed them. michael@0: # pragma option pop michael@0: #endif michael@0: michael@0: TEST_F(ExpectFatalFailureTest, DoesNotAbort) { michael@0: bool aborted = true; michael@0: DoesNotAbortHelper(&aborted); michael@0: EXPECT_FALSE(aborted); michael@0: } michael@0: michael@0: // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a michael@0: // statement that contains a macro which expands to code containing an michael@0: // unprotected comma. michael@0: michael@0: static int global_var = 0; michael@0: #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++ michael@0: michael@0: TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { michael@0: #ifndef __BORLANDC__ michael@0: // ICE's in C++Builder. michael@0: EXPECT_FATAL_FAILURE({ michael@0: GTEST_USE_UNPROTECTED_COMMA_; michael@0: AddFatalFailure(); michael@0: }, ""); michael@0: #endif michael@0: michael@0: EXPECT_FATAL_FAILURE_ON_ALL_THREADS({ michael@0: GTEST_USE_UNPROTECTED_COMMA_; michael@0: AddFatalFailure(); michael@0: }, ""); michael@0: } michael@0: michael@0: // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}. michael@0: michael@0: typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest; michael@0: michael@0: TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { michael@0: EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), michael@0: "Expected non-fatal failure."); michael@0: } michael@0: michael@0: #if GTEST_HAS_GLOBAL_STRING michael@0: TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) { michael@0: EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), michael@0: ::string("Expected non-fatal failure.")); michael@0: } michael@0: #endif michael@0: michael@0: TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) { michael@0: EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), michael@0: ::std::string("Expected non-fatal failure.")); michael@0: } michael@0: michael@0: TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { michael@0: // We have another test below to verify that the macro catches michael@0: // non-fatal failures generated on another thread. michael@0: EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(), michael@0: "Expected non-fatal failure."); michael@0: } michael@0: michael@0: // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a michael@0: // statement that contains a macro which expands to code containing an michael@0: // unprotected comma. michael@0: TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { michael@0: EXPECT_NONFATAL_FAILURE({ michael@0: GTEST_USE_UNPROTECTED_COMMA_; michael@0: AddNonfatalFailure(); michael@0: }, ""); michael@0: michael@0: EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({ michael@0: GTEST_USE_UNPROTECTED_COMMA_; michael@0: AddNonfatalFailure(); michael@0: }, ""); michael@0: } michael@0: michael@0: #if GTEST_IS_THREADSAFE michael@0: michael@0: typedef ScopedFakeTestPartResultReporterWithThreadsTest michael@0: ExpectFailureWithThreadsTest; michael@0: michael@0: TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) { michael@0: EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE), michael@0: "Expected fatal failure."); michael@0: } michael@0: michael@0: TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) { michael@0: EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( michael@0: AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure."); michael@0: } michael@0: michael@0: #endif // GTEST_IS_THREADSAFE michael@0: michael@0: // Tests the TestProperty class. michael@0: michael@0: TEST(TestPropertyTest, ConstructorWorks) { michael@0: const TestProperty property("key", "value"); michael@0: EXPECT_STREQ("key", property.key()); michael@0: EXPECT_STREQ("value", property.value()); michael@0: } michael@0: michael@0: TEST(TestPropertyTest, SetValue) { michael@0: TestProperty property("key", "value_1"); michael@0: EXPECT_STREQ("key", property.key()); michael@0: property.SetValue("value_2"); michael@0: EXPECT_STREQ("key", property.key()); michael@0: EXPECT_STREQ("value_2", property.value()); michael@0: } michael@0: michael@0: // Tests the TestResult class michael@0: michael@0: // The test fixture for testing TestResult. michael@0: class TestResultTest : public Test { michael@0: protected: michael@0: typedef std::vector TPRVector; michael@0: michael@0: // We make use of 2 TestPartResult objects, michael@0: TestPartResult * pr1, * pr2; michael@0: michael@0: // ... and 3 TestResult objects. michael@0: TestResult * r0, * r1, * r2; michael@0: michael@0: virtual void SetUp() { michael@0: // pr1 is for success. michael@0: pr1 = new TestPartResult(TestPartResult::kSuccess, michael@0: "foo/bar.cc", michael@0: 10, michael@0: "Success!"); michael@0: michael@0: // pr2 is for fatal failure. michael@0: pr2 = new TestPartResult(TestPartResult::kFatalFailure, michael@0: "foo/bar.cc", michael@0: -1, // This line number means "unknown" michael@0: "Failure!"); michael@0: michael@0: // Creates the TestResult objects. michael@0: r0 = new TestResult(); michael@0: r1 = new TestResult(); michael@0: r2 = new TestResult(); michael@0: michael@0: // In order to test TestResult, we need to modify its internal michael@0: // state, in particular the TestPartResult vector it holds. michael@0: // test_part_results() returns a const reference to this vector. michael@0: // We cast it to a non-const object s.t. it can be modified (yes, michael@0: // this is a hack). michael@0: TPRVector* results1 = const_cast( michael@0: &TestResultAccessor::test_part_results(*r1)); michael@0: TPRVector* results2 = const_cast( michael@0: &TestResultAccessor::test_part_results(*r2)); michael@0: michael@0: // r0 is an empty TestResult. michael@0: michael@0: // r1 contains a single SUCCESS TestPartResult. michael@0: results1->push_back(*pr1); michael@0: michael@0: // r2 contains a SUCCESS, and a FAILURE. michael@0: results2->push_back(*pr1); michael@0: results2->push_back(*pr2); michael@0: } michael@0: michael@0: virtual void TearDown() { michael@0: delete pr1; michael@0: delete pr2; michael@0: michael@0: delete r0; michael@0: delete r1; michael@0: delete r2; michael@0: } michael@0: michael@0: // Helper that compares two two TestPartResults. michael@0: static void CompareTestPartResult(const TestPartResult& expected, michael@0: const TestPartResult& actual) { michael@0: EXPECT_EQ(expected.type(), actual.type()); michael@0: EXPECT_STREQ(expected.file_name(), actual.file_name()); michael@0: EXPECT_EQ(expected.line_number(), actual.line_number()); michael@0: EXPECT_STREQ(expected.summary(), actual.summary()); michael@0: EXPECT_STREQ(expected.message(), actual.message()); michael@0: EXPECT_EQ(expected.passed(), actual.passed()); michael@0: EXPECT_EQ(expected.failed(), actual.failed()); michael@0: EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed()); michael@0: EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed()); michael@0: } michael@0: }; michael@0: michael@0: // Tests TestResult::total_part_count(). michael@0: TEST_F(TestResultTest, total_part_count) { michael@0: ASSERT_EQ(0, r0->total_part_count()); michael@0: ASSERT_EQ(1, r1->total_part_count()); michael@0: ASSERT_EQ(2, r2->total_part_count()); michael@0: } michael@0: michael@0: // Tests TestResult::Passed(). michael@0: TEST_F(TestResultTest, Passed) { michael@0: ASSERT_TRUE(r0->Passed()); michael@0: ASSERT_TRUE(r1->Passed()); michael@0: ASSERT_FALSE(r2->Passed()); michael@0: } michael@0: michael@0: // Tests TestResult::Failed(). michael@0: TEST_F(TestResultTest, Failed) { michael@0: ASSERT_FALSE(r0->Failed()); michael@0: ASSERT_FALSE(r1->Failed()); michael@0: ASSERT_TRUE(r2->Failed()); michael@0: } michael@0: michael@0: // Tests TestResult::GetTestPartResult(). michael@0: michael@0: typedef TestResultTest TestResultDeathTest; michael@0: michael@0: TEST_F(TestResultDeathTest, GetTestPartResult) { michael@0: CompareTestPartResult(*pr1, r2->GetTestPartResult(0)); michael@0: CompareTestPartResult(*pr2, r2->GetTestPartResult(1)); michael@0: EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), ""); michael@0: EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), ""); michael@0: } michael@0: michael@0: // Tests TestResult has no properties when none are added. michael@0: TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) { michael@0: TestResult test_result; michael@0: ASSERT_EQ(0, test_result.test_property_count()); michael@0: } michael@0: michael@0: // Tests TestResult has the expected property when added. michael@0: TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) { michael@0: TestResult test_result; michael@0: TestProperty property("key_1", "1"); michael@0: TestResultAccessor::RecordProperty(&test_result, property); michael@0: ASSERT_EQ(1, test_result.test_property_count()); michael@0: const TestProperty& actual_property = test_result.GetTestProperty(0); michael@0: EXPECT_STREQ("key_1", actual_property.key()); michael@0: EXPECT_STREQ("1", actual_property.value()); michael@0: } michael@0: michael@0: // Tests TestResult has multiple properties when added. michael@0: TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) { michael@0: TestResult test_result; michael@0: TestProperty property_1("key_1", "1"); michael@0: TestProperty property_2("key_2", "2"); michael@0: TestResultAccessor::RecordProperty(&test_result, property_1); michael@0: TestResultAccessor::RecordProperty(&test_result, property_2); michael@0: ASSERT_EQ(2, test_result.test_property_count()); michael@0: const TestProperty& actual_property_1 = test_result.GetTestProperty(0); michael@0: EXPECT_STREQ("key_1", actual_property_1.key()); michael@0: EXPECT_STREQ("1", actual_property_1.value()); michael@0: michael@0: const TestProperty& actual_property_2 = test_result.GetTestProperty(1); michael@0: EXPECT_STREQ("key_2", actual_property_2.key()); michael@0: EXPECT_STREQ("2", actual_property_2.value()); michael@0: } michael@0: michael@0: // Tests TestResult::RecordProperty() overrides values for duplicate keys. michael@0: TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) { michael@0: TestResult test_result; michael@0: TestProperty property_1_1("key_1", "1"); michael@0: TestProperty property_2_1("key_2", "2"); michael@0: TestProperty property_1_2("key_1", "12"); michael@0: TestProperty property_2_2("key_2", "22"); michael@0: TestResultAccessor::RecordProperty(&test_result, property_1_1); michael@0: TestResultAccessor::RecordProperty(&test_result, property_2_1); michael@0: TestResultAccessor::RecordProperty(&test_result, property_1_2); michael@0: TestResultAccessor::RecordProperty(&test_result, property_2_2); michael@0: michael@0: ASSERT_EQ(2, test_result.test_property_count()); michael@0: const TestProperty& actual_property_1 = test_result.GetTestProperty(0); michael@0: EXPECT_STREQ("key_1", actual_property_1.key()); michael@0: EXPECT_STREQ("12", actual_property_1.value()); michael@0: michael@0: const TestProperty& actual_property_2 = test_result.GetTestProperty(1); michael@0: EXPECT_STREQ("key_2", actual_property_2.key()); michael@0: EXPECT_STREQ("22", actual_property_2.value()); michael@0: } michael@0: michael@0: // Tests TestResult::GetTestProperty(). michael@0: TEST(TestResultPropertyDeathTest, GetTestProperty) { michael@0: TestResult test_result; michael@0: TestProperty property_1("key_1", "1"); michael@0: TestProperty property_2("key_2", "2"); michael@0: TestProperty property_3("key_3", "3"); michael@0: TestResultAccessor::RecordProperty(&test_result, property_1); michael@0: TestResultAccessor::RecordProperty(&test_result, property_2); michael@0: TestResultAccessor::RecordProperty(&test_result, property_3); michael@0: michael@0: const TestProperty& fetched_property_1 = test_result.GetTestProperty(0); michael@0: const TestProperty& fetched_property_2 = test_result.GetTestProperty(1); michael@0: const TestProperty& fetched_property_3 = test_result.GetTestProperty(2); michael@0: michael@0: EXPECT_STREQ("key_1", fetched_property_1.key()); michael@0: EXPECT_STREQ("1", fetched_property_1.value()); michael@0: michael@0: EXPECT_STREQ("key_2", fetched_property_2.key()); michael@0: EXPECT_STREQ("2", fetched_property_2.value()); michael@0: michael@0: EXPECT_STREQ("key_3", fetched_property_3.key()); michael@0: EXPECT_STREQ("3", fetched_property_3.value()); michael@0: michael@0: EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), ""); michael@0: EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), ""); michael@0: } michael@0: michael@0: // When a property using a reserved key is supplied to this function, it tests michael@0: // that a non-fatal failure is added, a fatal failure is not added, and that the michael@0: // property is not recorded. michael@0: void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) { michael@0: TestResult test_result; michael@0: TestProperty property(key, "1"); michael@0: EXPECT_NONFATAL_FAILURE( michael@0: TestResultAccessor::RecordProperty(&test_result, property), michael@0: "Reserved key"); michael@0: ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded"; michael@0: } michael@0: michael@0: // Attempting to recording a property with the Reserved literal "name" michael@0: // should add a non-fatal failure and the property should not be recorded. michael@0: TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) { michael@0: ExpectNonFatalFailureRecordingPropertyWithReservedKey("name"); michael@0: } michael@0: michael@0: // Attempting to recording a property with the Reserved literal "status" michael@0: // should add a non-fatal failure and the property should not be recorded. michael@0: TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) { michael@0: ExpectNonFatalFailureRecordingPropertyWithReservedKey("status"); michael@0: } michael@0: michael@0: // Attempting to recording a property with the Reserved literal "time" michael@0: // should add a non-fatal failure and the property should not be recorded. michael@0: TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) { michael@0: ExpectNonFatalFailureRecordingPropertyWithReservedKey("time"); michael@0: } michael@0: michael@0: // Attempting to recording a property with the Reserved literal "classname" michael@0: // should add a non-fatal failure and the property should not be recorded. michael@0: TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) { michael@0: ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname"); michael@0: } michael@0: michael@0: // Tests that GTestFlagSaver works on Windows and Mac. michael@0: michael@0: class GTestFlagSaverTest : public Test { michael@0: protected: michael@0: // Saves the Google Test flags such that we can restore them later, and michael@0: // then sets them to their default values. This will be called michael@0: // before the first test in this test case is run. michael@0: static void SetUpTestCase() { michael@0: saver_ = new GTestFlagSaver; michael@0: michael@0: GTEST_FLAG(also_run_disabled_tests) = false; michael@0: GTEST_FLAG(break_on_failure) = false; michael@0: GTEST_FLAG(catch_exceptions) = false; michael@0: GTEST_FLAG(death_test_use_fork) = false; michael@0: GTEST_FLAG(color) = "auto"; michael@0: GTEST_FLAG(filter) = ""; michael@0: GTEST_FLAG(list_tests) = false; michael@0: GTEST_FLAG(output) = ""; michael@0: GTEST_FLAG(print_time) = true; michael@0: GTEST_FLAG(random_seed) = 0; michael@0: GTEST_FLAG(repeat) = 1; michael@0: GTEST_FLAG(shuffle) = false; michael@0: GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; michael@0: GTEST_FLAG(stream_result_to) = ""; michael@0: GTEST_FLAG(throw_on_failure) = false; michael@0: } michael@0: michael@0: // Restores the Google Test flags that the tests have modified. This will michael@0: // be called after the last test in this test case is run. michael@0: static void TearDownTestCase() { michael@0: delete saver_; michael@0: saver_ = NULL; michael@0: } michael@0: michael@0: // Verifies that the Google Test flags have their default values, and then michael@0: // modifies each of them. michael@0: void VerifyAndModifyFlags() { michael@0: EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests)); michael@0: EXPECT_FALSE(GTEST_FLAG(break_on_failure)); michael@0: EXPECT_FALSE(GTEST_FLAG(catch_exceptions)); michael@0: EXPECT_STREQ("auto", GTEST_FLAG(color).c_str()); michael@0: EXPECT_FALSE(GTEST_FLAG(death_test_use_fork)); michael@0: EXPECT_STREQ("", GTEST_FLAG(filter).c_str()); michael@0: EXPECT_FALSE(GTEST_FLAG(list_tests)); michael@0: EXPECT_STREQ("", GTEST_FLAG(output).c_str()); michael@0: EXPECT_TRUE(GTEST_FLAG(print_time)); michael@0: EXPECT_EQ(0, GTEST_FLAG(random_seed)); michael@0: EXPECT_EQ(1, GTEST_FLAG(repeat)); michael@0: EXPECT_FALSE(GTEST_FLAG(shuffle)); michael@0: EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth)); michael@0: EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str()); michael@0: EXPECT_FALSE(GTEST_FLAG(throw_on_failure)); michael@0: michael@0: GTEST_FLAG(also_run_disabled_tests) = true; michael@0: GTEST_FLAG(break_on_failure) = true; michael@0: GTEST_FLAG(catch_exceptions) = true; michael@0: GTEST_FLAG(color) = "no"; michael@0: GTEST_FLAG(death_test_use_fork) = true; michael@0: GTEST_FLAG(filter) = "abc"; michael@0: GTEST_FLAG(list_tests) = true; michael@0: GTEST_FLAG(output) = "xml:foo.xml"; michael@0: GTEST_FLAG(print_time) = false; michael@0: GTEST_FLAG(random_seed) = 1; michael@0: GTEST_FLAG(repeat) = 100; michael@0: GTEST_FLAG(shuffle) = true; michael@0: GTEST_FLAG(stack_trace_depth) = 1; michael@0: GTEST_FLAG(stream_result_to) = "localhost:1234"; michael@0: GTEST_FLAG(throw_on_failure) = true; michael@0: } michael@0: michael@0: private: michael@0: // For saving Google Test flags during this test case. michael@0: static GTestFlagSaver* saver_; michael@0: }; michael@0: michael@0: GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL; michael@0: michael@0: // Google Test doesn't guarantee the order of tests. The following two michael@0: // tests are designed to work regardless of their order. michael@0: michael@0: // Modifies the Google Test flags in the test body. michael@0: TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { michael@0: VerifyAndModifyFlags(); michael@0: } michael@0: michael@0: // Verifies that the Google Test flags in the body of the previous test were michael@0: // restored to their original values. michael@0: TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { michael@0: VerifyAndModifyFlags(); michael@0: } michael@0: michael@0: // Sets an environment variable with the given name to the given michael@0: // value. If the value argument is "", unsets the environment michael@0: // variable. The caller must ensure that both arguments are not NULL. michael@0: static void SetEnv(const char* name, const char* value) { michael@0: #if GTEST_OS_WINDOWS_MOBILE michael@0: // Environment variables are not supported on Windows CE. michael@0: return; michael@0: #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) michael@0: // C++Builder's putenv only stores a pointer to its parameter; we have to michael@0: // ensure that the string remains valid as long as it might be needed. michael@0: // We use an std::map to do so. michael@0: static std::map added_env; michael@0: michael@0: // Because putenv stores a pointer to the string buffer, we can't delete the michael@0: // previous string (if present) until after it's replaced. michael@0: String *prev_env = NULL; michael@0: if (added_env.find(name) != added_env.end()) { michael@0: prev_env = added_env[name]; michael@0: } michael@0: added_env[name] = new String((Message() << name << "=" << value).GetString()); michael@0: michael@0: // The standard signature of putenv accepts a 'char*' argument. Other michael@0: // implementations, like C++Builder's, accept a 'const char*'. michael@0: // We cast away the 'const' since that would work for both variants. michael@0: putenv(const_cast(added_env[name]->c_str())); michael@0: delete prev_env; michael@0: #elif GTEST_OS_WINDOWS // If we are on Windows proper. michael@0: _putenv((Message() << name << "=" << value).GetString().c_str()); michael@0: #else michael@0: if (*value == '\0') { michael@0: unsetenv(name); michael@0: } else { michael@0: setenv(name, value, 1); michael@0: } michael@0: #endif // GTEST_OS_WINDOWS_MOBILE michael@0: } michael@0: michael@0: #if !GTEST_OS_WINDOWS_MOBILE michael@0: // Environment variables are not supported on Windows CE. michael@0: michael@0: using testing::internal::Int32FromGTestEnv; michael@0: michael@0: // Tests Int32FromGTestEnv(). michael@0: michael@0: // Tests that Int32FromGTestEnv() returns the default value when the michael@0: // environment variable is not set. michael@0: TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) { michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", ""); michael@0: EXPECT_EQ(10, Int32FromGTestEnv("temp", 10)); michael@0: } michael@0: michael@0: // Tests that Int32FromGTestEnv() returns the default value when the michael@0: // environment variable overflows as an Int32. michael@0: TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) { michael@0: printf("(expecting 2 warnings)\n"); michael@0: michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321"); michael@0: EXPECT_EQ(20, Int32FromGTestEnv("temp", 20)); michael@0: michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321"); michael@0: EXPECT_EQ(30, Int32FromGTestEnv("temp", 30)); michael@0: } michael@0: michael@0: // Tests that Int32FromGTestEnv() returns the default value when the michael@0: // environment variable does not represent a valid decimal integer. michael@0: TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) { michael@0: printf("(expecting 2 warnings)\n"); michael@0: michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1"); michael@0: EXPECT_EQ(40, Int32FromGTestEnv("temp", 40)); michael@0: michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X"); michael@0: EXPECT_EQ(50, Int32FromGTestEnv("temp", 50)); michael@0: } michael@0: michael@0: // Tests that Int32FromGTestEnv() parses and returns the value of the michael@0: // environment variable when it represents a valid decimal integer in michael@0: // the range of an Int32. michael@0: TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) { michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123"); michael@0: EXPECT_EQ(123, Int32FromGTestEnv("temp", 0)); michael@0: michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321"); michael@0: EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0)); michael@0: } michael@0: #endif // !GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: // Tests ParseInt32Flag(). michael@0: michael@0: // Tests that ParseInt32Flag() returns false and doesn't change the michael@0: // output value when the flag has wrong format michael@0: TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { michael@0: Int32 value = 123; michael@0: EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value)); michael@0: EXPECT_EQ(123, value); michael@0: michael@0: EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value)); michael@0: EXPECT_EQ(123, value); michael@0: } michael@0: michael@0: // Tests that ParseInt32Flag() returns false and doesn't change the michael@0: // output value when the flag overflows as an Int32. michael@0: TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { michael@0: printf("(expecting 2 warnings)\n"); michael@0: michael@0: Int32 value = 123; michael@0: EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value)); michael@0: EXPECT_EQ(123, value); michael@0: michael@0: EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value)); michael@0: EXPECT_EQ(123, value); michael@0: } michael@0: michael@0: // Tests that ParseInt32Flag() returns false and doesn't change the michael@0: // output value when the flag does not represent a valid decimal michael@0: // integer. michael@0: TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { michael@0: printf("(expecting 2 warnings)\n"); michael@0: michael@0: Int32 value = 123; michael@0: EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value)); michael@0: EXPECT_EQ(123, value); michael@0: michael@0: EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value)); michael@0: EXPECT_EQ(123, value); michael@0: } michael@0: michael@0: // Tests that ParseInt32Flag() parses the value of the flag and michael@0: // returns true when the flag represents a valid decimal integer in michael@0: // the range of an Int32. michael@0: TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) { michael@0: Int32 value = 123; michael@0: EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); michael@0: EXPECT_EQ(456, value); michael@0: michael@0: EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789", michael@0: "abc", &value)); michael@0: EXPECT_EQ(-789, value); michael@0: } michael@0: michael@0: // Tests that Int32FromEnvOrDie() parses the value of the var or michael@0: // returns the correct default. michael@0: // Environment variables are not supported on Windows CE. michael@0: #if !GTEST_OS_WINDOWS_MOBILE michael@0: TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { michael@0: EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123"); michael@0: EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123"); michael@0: EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); michael@0: } michael@0: #endif // !GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: // Tests that Int32FromEnvOrDie() aborts with an error message michael@0: // if the variable is not an Int32. michael@0: TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); michael@0: EXPECT_DEATH_IF_SUPPORTED( michael@0: Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), michael@0: ".*"); michael@0: } michael@0: michael@0: // Tests that Int32FromEnvOrDie() aborts with an error message michael@0: // if the variable cannot be represnted by an Int32. michael@0: TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { michael@0: SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); michael@0: EXPECT_DEATH_IF_SUPPORTED( michael@0: Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), michael@0: ".*"); michael@0: } michael@0: michael@0: // Tests that ShouldRunTestOnShard() selects all tests michael@0: // where there is 1 shard. michael@0: TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) { michael@0: EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0)); michael@0: EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1)); michael@0: EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2)); michael@0: EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3)); michael@0: EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4)); michael@0: } michael@0: michael@0: class ShouldShardTest : public testing::Test { michael@0: protected: michael@0: virtual void SetUp() { michael@0: index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX"; michael@0: total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL"; michael@0: } michael@0: michael@0: virtual void TearDown() { michael@0: SetEnv(index_var_, ""); michael@0: SetEnv(total_var_, ""); michael@0: } michael@0: michael@0: const char* index_var_; michael@0: const char* total_var_; michael@0: }; michael@0: michael@0: // Tests that sharding is disabled if neither of the environment variables michael@0: // are set. michael@0: TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) { michael@0: SetEnv(index_var_, ""); michael@0: SetEnv(total_var_, ""); michael@0: michael@0: EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); michael@0: EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); michael@0: } michael@0: michael@0: // Tests that sharding is not enabled if total_shards == 1. michael@0: TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) { michael@0: SetEnv(index_var_, "0"); michael@0: SetEnv(total_var_, "1"); michael@0: EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); michael@0: EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); michael@0: } michael@0: michael@0: // Tests that sharding is enabled if total_shards > 1 and michael@0: // we are not in a death test subprocess. michael@0: // Environment variables are not supported on Windows CE. michael@0: #if !GTEST_OS_WINDOWS_MOBILE michael@0: TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) { michael@0: SetEnv(index_var_, "4"); michael@0: SetEnv(total_var_, "22"); michael@0: EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); michael@0: EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); michael@0: michael@0: SetEnv(index_var_, "8"); michael@0: SetEnv(total_var_, "9"); michael@0: EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); michael@0: EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); michael@0: michael@0: SetEnv(index_var_, "0"); michael@0: SetEnv(total_var_, "9"); michael@0: EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); michael@0: EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); michael@0: } michael@0: #endif // !GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: // Tests that we exit in error if the sharding values are not valid. michael@0: michael@0: typedef ShouldShardTest ShouldShardDeathTest; michael@0: michael@0: TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) { michael@0: SetEnv(index_var_, "4"); michael@0: SetEnv(total_var_, "4"); michael@0: EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); michael@0: michael@0: SetEnv(index_var_, "4"); michael@0: SetEnv(total_var_, "-2"); michael@0: EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); michael@0: michael@0: SetEnv(index_var_, "5"); michael@0: SetEnv(total_var_, ""); michael@0: EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); michael@0: michael@0: SetEnv(index_var_, ""); michael@0: SetEnv(total_var_, "5"); michael@0: EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); michael@0: } michael@0: michael@0: // Tests that ShouldRunTestOnShard is a partition when 5 michael@0: // shards are used. michael@0: TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) { michael@0: // Choose an arbitrary number of tests and shards. michael@0: const int num_tests = 17; michael@0: const int num_shards = 5; michael@0: michael@0: // Check partitioning: each test should be on exactly 1 shard. michael@0: for (int test_id = 0; test_id < num_tests; test_id++) { michael@0: int prev_selected_shard_index = -1; michael@0: for (int shard_index = 0; shard_index < num_shards; shard_index++) { michael@0: if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) { michael@0: if (prev_selected_shard_index < 0) { michael@0: prev_selected_shard_index = shard_index; michael@0: } else { michael@0: ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and " michael@0: << shard_index << " are both selected to run test " << test_id; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Check balance: This is not required by the sharding protocol, but is a michael@0: // desirable property for performance. michael@0: for (int shard_index = 0; shard_index < num_shards; shard_index++) { michael@0: int num_tests_on_shard = 0; michael@0: for (int test_id = 0; test_id < num_tests; test_id++) { michael@0: num_tests_on_shard += michael@0: ShouldRunTestOnShard(num_shards, shard_index, test_id); michael@0: } michael@0: EXPECT_GE(num_tests_on_shard, num_tests / num_shards); michael@0: } michael@0: } michael@0: michael@0: // For the same reason we are not explicitly testing everything in the michael@0: // Test class, there are no separate tests for the following classes michael@0: // (except for some trivial cases): michael@0: // michael@0: // TestCase, UnitTest, UnitTestResultPrinter. michael@0: // michael@0: // Similarly, there are no separate tests for the following macros: michael@0: // michael@0: // TEST, TEST_F, RUN_ALL_TESTS michael@0: michael@0: TEST(UnitTestTest, CanGetOriginalWorkingDir) { michael@0: ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL); michael@0: EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), ""); michael@0: } michael@0: michael@0: TEST(UnitTestTest, ReturnsPlausibleTimestamp) { michael@0: EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp()); michael@0: EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis()); michael@0: } michael@0: michael@0: // This group of tests is for predicate assertions (ASSERT_PRED*, etc) michael@0: // of various arities. They do not attempt to be exhaustive. Rather, michael@0: // view them as smoke tests that can be easily reviewed and verified. michael@0: // A more complete set of tests for predicate assertions can be found michael@0: // in gtest_pred_impl_unittest.cc. michael@0: michael@0: // First, some predicates and predicate-formatters needed by the tests. michael@0: michael@0: // Returns true iff the argument is an even number. michael@0: bool IsEven(int n) { michael@0: return (n % 2) == 0; michael@0: } michael@0: michael@0: // A functor that returns true iff the argument is an even number. michael@0: struct IsEvenFunctor { michael@0: bool operator()(int n) { return IsEven(n); } michael@0: }; michael@0: michael@0: // A predicate-formatter function that asserts the argument is an even michael@0: // number. michael@0: AssertionResult AssertIsEven(const char* expr, int n) { michael@0: if (IsEven(n)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: Message msg; michael@0: msg << expr << " evaluates to " << n << ", which is not even."; michael@0: return AssertionFailure(msg); michael@0: } michael@0: michael@0: // A predicate function that returns AssertionResult for use in michael@0: // EXPECT/ASSERT_TRUE/FALSE. michael@0: AssertionResult ResultIsEven(int n) { michael@0: if (IsEven(n)) michael@0: return AssertionSuccess() << n << " is even"; michael@0: else michael@0: return AssertionFailure() << n << " is odd"; michael@0: } michael@0: michael@0: // A predicate function that returns AssertionResult but gives no michael@0: // explanation why it succeeds. Needed for testing that michael@0: // EXPECT/ASSERT_FALSE handles such functions correctly. michael@0: AssertionResult ResultIsEvenNoExplanation(int n) { michael@0: if (IsEven(n)) michael@0: return AssertionSuccess(); michael@0: else michael@0: return AssertionFailure() << n << " is odd"; michael@0: } michael@0: michael@0: // A predicate-formatter functor that asserts the argument is an even michael@0: // number. michael@0: struct AssertIsEvenFunctor { michael@0: AssertionResult operator()(const char* expr, int n) { michael@0: return AssertIsEven(expr, n); michael@0: } michael@0: }; michael@0: michael@0: // Returns true iff the sum of the arguments is an even number. michael@0: bool SumIsEven2(int n1, int n2) { michael@0: return IsEven(n1 + n2); michael@0: } michael@0: michael@0: // A functor that returns true iff the sum of the arguments is an even michael@0: // number. michael@0: struct SumIsEven3Functor { michael@0: bool operator()(int n1, int n2, int n3) { michael@0: return IsEven(n1 + n2 + n3); michael@0: } michael@0: }; michael@0: michael@0: // A predicate-formatter function that asserts the sum of the michael@0: // arguments is an even number. michael@0: AssertionResult AssertSumIsEven4( michael@0: const char* e1, const char* e2, const char* e3, const char* e4, michael@0: int n1, int n2, int n3, int n4) { michael@0: const int sum = n1 + n2 + n3 + n4; michael@0: if (IsEven(sum)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: Message msg; michael@0: msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 michael@0: << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 michael@0: << ") evaluates to " << sum << ", which is not even."; michael@0: return AssertionFailure(msg); michael@0: } michael@0: michael@0: // A predicate-formatter functor that asserts the sum of the arguments michael@0: // is an even number. michael@0: struct AssertSumIsEven5Functor { michael@0: AssertionResult operator()( michael@0: const char* e1, const char* e2, const char* e3, const char* e4, michael@0: const char* e5, int n1, int n2, int n3, int n4, int n5) { michael@0: const int sum = n1 + n2 + n3 + n4 + n5; michael@0: if (IsEven(sum)) { michael@0: return AssertionSuccess(); michael@0: } michael@0: michael@0: Message msg; michael@0: msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 michael@0: << " (" michael@0: << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5 michael@0: << ") evaluates to " << sum << ", which is not even."; michael@0: return AssertionFailure(msg); michael@0: } michael@0: }; michael@0: michael@0: michael@0: // Tests unary predicate assertions. michael@0: michael@0: // Tests unary predicate assertions that don't use a custom formatter. michael@0: TEST(Pred1Test, WithoutFormat) { michael@0: // Success cases. michael@0: EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!"; michael@0: ASSERT_PRED1(IsEven, 4); michael@0: michael@0: // Failure cases. michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED1(IsEven, 5) << "This failure is expected."; michael@0: }, "This failure is expected."); michael@0: EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), michael@0: "evaluates to false"); michael@0: } michael@0: michael@0: // Tests unary predicate assertions that use a custom formatter. michael@0: TEST(Pred1Test, WithFormat) { michael@0: // Success cases. michael@0: EXPECT_PRED_FORMAT1(AssertIsEven, 2); michael@0: ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4) michael@0: << "This failure is UNEXPECTED!"; michael@0: michael@0: // Failure cases. michael@0: const int n = 5; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n), michael@0: "n evaluates to 5, which is not even."); michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected."; michael@0: }, "This failure is expected."); michael@0: } michael@0: michael@0: // Tests that unary predicate assertions evaluates their arguments michael@0: // exactly once. michael@0: TEST(Pred1Test, SingleEvaluationOnFailure) { michael@0: // A success case. michael@0: static int n = 0; michael@0: EXPECT_PRED1(IsEven, n++); michael@0: EXPECT_EQ(1, n) << "The argument is not evaluated exactly once."; michael@0: michael@0: // A failure case. michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++) michael@0: << "This failure is expected."; michael@0: }, "This failure is expected."); michael@0: EXPECT_EQ(2, n) << "The argument is not evaluated exactly once."; michael@0: } michael@0: michael@0: michael@0: // Tests predicate assertions whose arity is >= 2. michael@0: michael@0: // Tests predicate assertions that don't use a custom formatter. michael@0: TEST(PredTest, WithoutFormat) { michael@0: // Success cases. michael@0: ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!"; michael@0: EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8); michael@0: michael@0: // Failure cases. michael@0: const int n1 = 1; michael@0: const int n2 = 2; michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected."; michael@0: }, "This failure is expected."); michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4); michael@0: }, "evaluates to false"); michael@0: } michael@0: michael@0: // Tests predicate assertions that use a custom formatter. michael@0: TEST(PredTest, WithFormat) { michael@0: // Success cases. michael@0: ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) << michael@0: "This failure is UNEXPECTED!"; michael@0: EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10); michael@0: michael@0: // Failure cases. michael@0: const int n1 = 1; michael@0: const int n2 = 2; michael@0: const int n3 = 4; michael@0: const int n4 = 6; michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4); michael@0: }, "evaluates to 13, which is not even."); michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8) michael@0: << "This failure is expected."; michael@0: }, "This failure is expected."); michael@0: } michael@0: michael@0: // Tests that predicate assertions evaluates their arguments michael@0: // exactly once. michael@0: TEST(PredTest, SingleEvaluationOnFailure) { michael@0: // A success case. michael@0: int n1 = 0; michael@0: int n2 = 0; michael@0: EXPECT_PRED2(SumIsEven2, n1++, n2++); michael@0: EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; michael@0: michael@0: // Another success case. michael@0: n1 = n2 = 0; michael@0: int n3 = 0; michael@0: int n4 = 0; michael@0: int n5 = 0; michael@0: ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), michael@0: n1++, n2++, n3++, n4++, n5++) michael@0: << "This failure is UNEXPECTED!"; michael@0: EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once."; michael@0: michael@0: // A failure case. michael@0: n1 = n2 = n3 = 0; michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++) michael@0: << "This failure is expected."; michael@0: }, "This failure is expected."); michael@0: EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; michael@0: michael@0: // Another failure case. michael@0: n1 = n2 = n3 = n4 = 0; michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++); michael@0: }, "evaluates to 1, which is not even."); michael@0: EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; michael@0: EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; michael@0: } michael@0: michael@0: michael@0: // Some helper functions for testing using overloaded/template michael@0: // functions with ASSERT_PREDn and EXPECT_PREDn. michael@0: michael@0: bool IsPositive(double x) { michael@0: return x > 0; michael@0: } michael@0: michael@0: template michael@0: bool IsNegative(T x) { michael@0: return x < 0; michael@0: } michael@0: michael@0: template michael@0: bool GreaterThan(T1 x1, T2 x2) { michael@0: return x1 > x2; michael@0: } michael@0: michael@0: // Tests that overloaded functions can be used in *_PRED* as long as michael@0: // their types are explicitly specified. michael@0: TEST(PredicateAssertionTest, AcceptsOverloadedFunction) { michael@0: // C++Builder requires C-style casts rather than static_cast. michael@0: EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT michael@0: ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT michael@0: } michael@0: michael@0: // Tests that template functions can be used in *_PRED* as long as michael@0: // their types are explicitly specified. michael@0: TEST(PredicateAssertionTest, AcceptsTemplateFunction) { michael@0: EXPECT_PRED1(IsNegative, -5); michael@0: // Makes sure that we can handle templates with more than one michael@0: // parameter. michael@0: ASSERT_PRED2((GreaterThan), 5, 0); michael@0: } michael@0: michael@0: michael@0: // Some helper functions for testing using overloaded/template michael@0: // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn. michael@0: michael@0: AssertionResult IsPositiveFormat(const char* /* expr */, int n) { michael@0: return n > 0 ? AssertionSuccess() : michael@0: AssertionFailure(Message() << "Failure"); michael@0: } michael@0: michael@0: AssertionResult IsPositiveFormat(const char* /* expr */, double x) { michael@0: return x > 0 ? AssertionSuccess() : michael@0: AssertionFailure(Message() << "Failure"); michael@0: } michael@0: michael@0: template michael@0: AssertionResult IsNegativeFormat(const char* /* expr */, T x) { michael@0: return x < 0 ? AssertionSuccess() : michael@0: AssertionFailure(Message() << "Failure"); michael@0: } michael@0: michael@0: template michael@0: AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */, michael@0: const T1& x1, const T2& x2) { michael@0: return x1 == x2 ? AssertionSuccess() : michael@0: AssertionFailure(Message() << "Failure"); michael@0: } michael@0: michael@0: // Tests that overloaded functions can be used in *_PRED_FORMAT* michael@0: // without explicitly specifying their types. michael@0: TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) { michael@0: EXPECT_PRED_FORMAT1(IsPositiveFormat, 5); michael@0: ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0); michael@0: } michael@0: michael@0: // Tests that template functions can be used in *_PRED_FORMAT* without michael@0: // explicitly specifying their types. michael@0: TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) { michael@0: EXPECT_PRED_FORMAT1(IsNegativeFormat, -5); michael@0: ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3); michael@0: } michael@0: michael@0: michael@0: // Tests string assertions. michael@0: michael@0: // Tests ASSERT_STREQ with non-NULL arguments. michael@0: TEST(StringAssertionTest, ASSERT_STREQ) { michael@0: const char * const p1 = "good"; michael@0: ASSERT_STREQ(p1, p1); michael@0: michael@0: // Let p2 have the same content as p1, but be at a different address. michael@0: const char p2[] = "good"; michael@0: ASSERT_STREQ(p1, p2); michael@0: michael@0: EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), michael@0: "Expected: \"bad\""); michael@0: } michael@0: michael@0: // Tests ASSERT_STREQ with NULL arguments. michael@0: TEST(StringAssertionTest, ASSERT_STREQ_Null) { michael@0: ASSERT_STREQ(static_cast(NULL), NULL); michael@0: EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"), michael@0: "non-null"); michael@0: } michael@0: michael@0: // Tests ASSERT_STREQ with NULL arguments. michael@0: TEST(StringAssertionTest, ASSERT_STREQ_Null2) { michael@0: EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL), michael@0: "non-null"); michael@0: } michael@0: michael@0: // Tests ASSERT_STRNE. michael@0: TEST(StringAssertionTest, ASSERT_STRNE) { michael@0: ASSERT_STRNE("hi", "Hi"); michael@0: ASSERT_STRNE("Hi", NULL); michael@0: ASSERT_STRNE(NULL, "Hi"); michael@0: ASSERT_STRNE("", NULL); michael@0: ASSERT_STRNE(NULL, ""); michael@0: ASSERT_STRNE("", "Hi"); michael@0: ASSERT_STRNE("Hi", ""); michael@0: EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), michael@0: "\"Hi\" vs \"Hi\""); michael@0: } michael@0: michael@0: // Tests ASSERT_STRCASEEQ. michael@0: TEST(StringAssertionTest, ASSERT_STRCASEEQ) { michael@0: ASSERT_STRCASEEQ("hi", "Hi"); michael@0: ASSERT_STRCASEEQ(static_cast(NULL), NULL); michael@0: michael@0: ASSERT_STRCASEEQ("", ""); michael@0: EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), michael@0: "(ignoring case)"); michael@0: } michael@0: michael@0: // Tests ASSERT_STRCASENE. michael@0: TEST(StringAssertionTest, ASSERT_STRCASENE) { michael@0: ASSERT_STRCASENE("hi1", "Hi2"); michael@0: ASSERT_STRCASENE("Hi", NULL); michael@0: ASSERT_STRCASENE(NULL, "Hi"); michael@0: ASSERT_STRCASENE("", NULL); michael@0: ASSERT_STRCASENE(NULL, ""); michael@0: ASSERT_STRCASENE("", "Hi"); michael@0: ASSERT_STRCASENE("Hi", ""); michael@0: EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), michael@0: "(ignoring case)"); michael@0: } michael@0: michael@0: // Tests *_STREQ on wide strings. michael@0: TEST(StringAssertionTest, STREQ_Wide) { michael@0: // NULL strings. michael@0: ASSERT_STREQ(static_cast(NULL), NULL); michael@0: michael@0: // Empty strings. michael@0: ASSERT_STREQ(L"", L""); michael@0: michael@0: // Non-null vs NULL. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL), michael@0: "non-null"); michael@0: michael@0: // Equal strings. michael@0: EXPECT_STREQ(L"Hi", L"Hi"); michael@0: michael@0: // Unequal strings. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), michael@0: "Abc"); michael@0: michael@0: // Strings containing wide characters. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), michael@0: "abc"); michael@0: michael@0: // The streaming variation. michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure"; michael@0: }, "Expected failure"); michael@0: } michael@0: michael@0: // Tests *_STRNE on wide strings. michael@0: TEST(StringAssertionTest, STRNE_Wide) { michael@0: // NULL strings. michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_STRNE(static_cast(NULL), NULL); michael@0: }, ""); michael@0: michael@0: // Empty strings. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), michael@0: "L\"\""); michael@0: michael@0: // Non-null vs NULL. michael@0: ASSERT_STRNE(L"non-null", NULL); michael@0: michael@0: // Equal strings. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), michael@0: "L\"Hi\""); michael@0: michael@0: // Unequal strings. michael@0: EXPECT_STRNE(L"abc", L"Abc"); michael@0: michael@0: // Strings containing wide characters. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), michael@0: "abc"); michael@0: michael@0: // The streaming variation. michael@0: ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen"; michael@0: } michael@0: michael@0: // Tests for ::testing::IsSubstring(). michael@0: michael@0: // Tests that IsSubstring() returns the correct result when the input michael@0: // argument type is const char*. michael@0: TEST(IsSubstringTest, ReturnsCorrectResultForCString) { michael@0: EXPECT_FALSE(IsSubstring("", "", NULL, "a")); michael@0: EXPECT_FALSE(IsSubstring("", "", "b", NULL)); michael@0: EXPECT_FALSE(IsSubstring("", "", "needle", "haystack")); michael@0: michael@0: EXPECT_TRUE(IsSubstring("", "", static_cast(NULL), NULL)); michael@0: EXPECT_TRUE(IsSubstring("", "", "needle", "two needles")); michael@0: } michael@0: michael@0: // Tests that IsSubstring() returns the correct result when the input michael@0: // argument type is const wchar_t*. michael@0: TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) { michael@0: EXPECT_FALSE(IsSubstring("", "", kNull, L"a")); michael@0: EXPECT_FALSE(IsSubstring("", "", L"b", kNull)); michael@0: EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack")); michael@0: michael@0: EXPECT_TRUE(IsSubstring("", "", static_cast(NULL), NULL)); michael@0: EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles")); michael@0: } michael@0: michael@0: // Tests that IsSubstring() generates the correct message when the input michael@0: // argument type is const char*. michael@0: TEST(IsSubstringTest, GeneratesCorrectMessageForCString) { michael@0: EXPECT_STREQ("Value of: needle_expr\n" michael@0: " Actual: \"needle\"\n" michael@0: "Expected: a substring of haystack_expr\n" michael@0: "Which is: \"haystack\"", michael@0: IsSubstring("needle_expr", "haystack_expr", michael@0: "needle", "haystack").failure_message()); michael@0: } michael@0: michael@0: // Tests that IsSubstring returns the correct result when the input michael@0: // argument type is ::std::string. michael@0: TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) { michael@0: EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob")); michael@0: EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world"))); michael@0: } michael@0: michael@0: #if GTEST_HAS_STD_WSTRING michael@0: // Tests that IsSubstring returns the correct result when the input michael@0: // argument type is ::std::wstring. michael@0: TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) { michael@0: EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles")); michael@0: EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack"))); michael@0: } michael@0: michael@0: // Tests that IsSubstring() generates the correct message when the input michael@0: // argument type is ::std::wstring. michael@0: TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) { michael@0: EXPECT_STREQ("Value of: needle_expr\n" michael@0: " Actual: L\"needle\"\n" michael@0: "Expected: a substring of haystack_expr\n" michael@0: "Which is: L\"haystack\"", michael@0: IsSubstring( michael@0: "needle_expr", "haystack_expr", michael@0: ::std::wstring(L"needle"), L"haystack").failure_message()); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_STD_WSTRING michael@0: michael@0: // Tests for ::testing::IsNotSubstring(). michael@0: michael@0: // Tests that IsNotSubstring() returns the correct result when the input michael@0: // argument type is const char*. michael@0: TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) { michael@0: EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack")); michael@0: EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles")); michael@0: } michael@0: michael@0: // Tests that IsNotSubstring() returns the correct result when the input michael@0: // argument type is const wchar_t*. michael@0: TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) { michael@0: EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack")); michael@0: EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles")); michael@0: } michael@0: michael@0: // Tests that IsNotSubstring() generates the correct message when the input michael@0: // argument type is const wchar_t*. michael@0: TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) { michael@0: EXPECT_STREQ("Value of: needle_expr\n" michael@0: " Actual: L\"needle\"\n" michael@0: "Expected: not a substring of haystack_expr\n" michael@0: "Which is: L\"two needles\"", michael@0: IsNotSubstring( michael@0: "needle_expr", "haystack_expr", michael@0: L"needle", L"two needles").failure_message()); michael@0: } michael@0: michael@0: // Tests that IsNotSubstring returns the correct result when the input michael@0: // argument type is ::std::string. michael@0: TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) { michael@0: EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob")); michael@0: EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world"))); michael@0: } michael@0: michael@0: // Tests that IsNotSubstring() generates the correct message when the input michael@0: // argument type is ::std::string. michael@0: TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) { michael@0: EXPECT_STREQ("Value of: needle_expr\n" michael@0: " Actual: \"needle\"\n" michael@0: "Expected: not a substring of haystack_expr\n" michael@0: "Which is: \"two needles\"", michael@0: IsNotSubstring( michael@0: "needle_expr", "haystack_expr", michael@0: ::std::string("needle"), "two needles").failure_message()); michael@0: } michael@0: michael@0: #if GTEST_HAS_STD_WSTRING michael@0: michael@0: // Tests that IsNotSubstring returns the correct result when the input michael@0: // argument type is ::std::wstring. michael@0: TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) { michael@0: EXPECT_FALSE( michael@0: IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles")); michael@0: EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack"))); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_STD_WSTRING michael@0: michael@0: // Tests floating-point assertions. michael@0: michael@0: template michael@0: class FloatingPointTest : public Test { michael@0: protected: michael@0: // Pre-calculated numbers to be used by the tests. michael@0: struct TestValues { michael@0: RawType close_to_positive_zero; michael@0: RawType close_to_negative_zero; michael@0: RawType further_from_negative_zero; michael@0: michael@0: RawType close_to_one; michael@0: RawType further_from_one; michael@0: michael@0: RawType infinity; michael@0: RawType close_to_infinity; michael@0: RawType further_from_infinity; michael@0: michael@0: RawType nan1; michael@0: RawType nan2; michael@0: }; michael@0: michael@0: typedef typename testing::internal::FloatingPoint Floating; michael@0: typedef typename Floating::Bits Bits; michael@0: michael@0: virtual void SetUp() { michael@0: const size_t max_ulps = Floating::kMaxUlps; michael@0: michael@0: // The bits that represent 0.0. michael@0: const Bits zero_bits = Floating(0).bits(); michael@0: michael@0: // Makes some numbers close to 0.0. michael@0: values_.close_to_positive_zero = Floating::ReinterpretBits( michael@0: zero_bits + max_ulps/2); michael@0: values_.close_to_negative_zero = -Floating::ReinterpretBits( michael@0: zero_bits + max_ulps - max_ulps/2); michael@0: values_.further_from_negative_zero = -Floating::ReinterpretBits( michael@0: zero_bits + max_ulps + 1 - max_ulps/2); michael@0: michael@0: // The bits that represent 1.0. michael@0: const Bits one_bits = Floating(1).bits(); michael@0: michael@0: // Makes some numbers close to 1.0. michael@0: values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps); michael@0: values_.further_from_one = Floating::ReinterpretBits( michael@0: one_bits + max_ulps + 1); michael@0: michael@0: // +infinity. michael@0: values_.infinity = Floating::Infinity(); michael@0: michael@0: // The bits that represent +infinity. michael@0: const Bits infinity_bits = Floating(values_.infinity).bits(); michael@0: michael@0: // Makes some numbers close to infinity. michael@0: values_.close_to_infinity = Floating::ReinterpretBits( michael@0: infinity_bits - max_ulps); michael@0: values_.further_from_infinity = Floating::ReinterpretBits( michael@0: infinity_bits - max_ulps - 1); michael@0: michael@0: // Makes some NAN's. Sets the most significant bit of the fraction so that michael@0: // our NaN's are quiet; trying to process a signaling NaN would raise an michael@0: // exception if our environment enables floating point exceptions. michael@0: values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask michael@0: | (static_cast(1) << (Floating::kFractionBitCount - 1)) | 1); michael@0: values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask michael@0: | (static_cast(1) << (Floating::kFractionBitCount - 1)) | 200); michael@0: } michael@0: michael@0: void TestSize() { michael@0: EXPECT_EQ(sizeof(RawType), sizeof(Bits)); michael@0: } michael@0: michael@0: static TestValues values_; michael@0: }; michael@0: michael@0: template michael@0: typename FloatingPointTest::TestValues michael@0: FloatingPointTest::values_; michael@0: michael@0: // Instantiates FloatingPointTest for testing *_FLOAT_EQ. michael@0: typedef FloatingPointTest FloatTest; michael@0: michael@0: // Tests that the size of Float::Bits matches the size of float. michael@0: TEST_F(FloatTest, Size) { michael@0: TestSize(); michael@0: } michael@0: michael@0: // Tests comparing with +0 and -0. michael@0: TEST_F(FloatTest, Zeros) { michael@0: EXPECT_FLOAT_EQ(0.0, -0.0); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), michael@0: "1.0"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), michael@0: "1.5"); michael@0: } michael@0: michael@0: // Tests comparing numbers close to 0. michael@0: // michael@0: // This ensures that *_FLOAT_EQ handles the sign correctly and no michael@0: // overflow occurs when comparing numbers whose absolute value is very michael@0: // small. michael@0: TEST_F(FloatTest, AlmostZeros) { michael@0: // In C++Builder, names within local classes (such as used by michael@0: // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the michael@0: // scoping class. Use a static local alias as a workaround. michael@0: // We use the assignment syntax since some compilers, like Sun Studio, michael@0: // don't allow initializing references using construction syntax michael@0: // (parentheses). michael@0: static const FloatTest::TestValues& v = this->values_; michael@0: michael@0: EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero); michael@0: EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero); michael@0: EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero); michael@0: michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_FLOAT_EQ(v.close_to_positive_zero, michael@0: v.further_from_negative_zero); michael@0: }, "v.further_from_negative_zero"); michael@0: } michael@0: michael@0: // Tests comparing numbers close to each other. michael@0: TEST_F(FloatTest, SmallDiff) { michael@0: EXPECT_FLOAT_EQ(1.0, values_.close_to_one); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one), michael@0: "values_.further_from_one"); michael@0: } michael@0: michael@0: // Tests comparing numbers far apart. michael@0: TEST_F(FloatTest, LargeDiff) { michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), michael@0: "3.0"); michael@0: } michael@0: michael@0: // Tests comparing with infinity. michael@0: // michael@0: // This ensures that no overflow occurs when comparing numbers whose michael@0: // absolute value is very large. michael@0: TEST_F(FloatTest, Infinity) { michael@0: EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity); michael@0: EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity); michael@0: #if !GTEST_OS_SYMBIAN michael@0: // Nokia's STLport crashes if we try to output infinity or NaN. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity), michael@0: "-values_.infinity"); michael@0: michael@0: // This is interesting as the representations of infinity and nan1 michael@0: // are only 1 DLP apart. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1), michael@0: "values_.nan1"); michael@0: #endif // !GTEST_OS_SYMBIAN michael@0: } michael@0: michael@0: // Tests that comparing with NAN always returns false. michael@0: TEST_F(FloatTest, NaN) { michael@0: #if !GTEST_OS_SYMBIAN michael@0: // Nokia's STLport crashes if we try to output infinity or NaN. michael@0: michael@0: // In C++Builder, names within local classes (such as used by michael@0: // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the michael@0: // scoping class. Use a static local alias as a workaround. michael@0: // We use the assignment syntax since some compilers, like Sun Studio, michael@0: // don't allow initializing references using construction syntax michael@0: // (parentheses). michael@0: static const FloatTest::TestValues& v = this->values_; michael@0: michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), michael@0: "v.nan1"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), michael@0: "v.nan2"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), michael@0: "v.nan1"); michael@0: michael@0: EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), michael@0: "v.infinity"); michael@0: #endif // !GTEST_OS_SYMBIAN michael@0: } michael@0: michael@0: // Tests that *_FLOAT_EQ are reflexive. michael@0: TEST_F(FloatTest, Reflexive) { michael@0: EXPECT_FLOAT_EQ(0.0, 0.0); michael@0: EXPECT_FLOAT_EQ(1.0, 1.0); michael@0: ASSERT_FLOAT_EQ(values_.infinity, values_.infinity); michael@0: } michael@0: michael@0: // Tests that *_FLOAT_EQ are commutative. michael@0: TEST_F(FloatTest, Commutative) { michael@0: // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one). michael@0: EXPECT_FLOAT_EQ(values_.close_to_one, 1.0); michael@0: michael@0: // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one). michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0), michael@0: "1.0"); michael@0: } michael@0: michael@0: // Tests EXPECT_NEAR. michael@0: TEST_F(FloatTest, EXPECT_NEAR) { michael@0: EXPECT_NEAR(-1.0f, -1.1f, 0.2f); michael@0: EXPECT_NEAR(2.0f, 3.0f, 1.0f); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT michael@0: "The difference between 1.0f and 1.5f is 0.5, " michael@0: "which exceeds 0.25f"); michael@0: // To work around a bug in gcc 2.95.0, there is intentionally no michael@0: // space after the first comma in the previous line. michael@0: } michael@0: michael@0: // Tests ASSERT_NEAR. michael@0: TEST_F(FloatTest, ASSERT_NEAR) { michael@0: ASSERT_NEAR(-1.0f, -1.1f, 0.2f); michael@0: ASSERT_NEAR(2.0f, 3.0f, 1.0f); michael@0: EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT michael@0: "The difference between 1.0f and 1.5f is 0.5, " michael@0: "which exceeds 0.25f"); michael@0: // To work around a bug in gcc 2.95.0, there is intentionally no michael@0: // space after the first comma in the previous line. michael@0: } michael@0: michael@0: // Tests the cases where FloatLE() should succeed. michael@0: TEST_F(FloatTest, FloatLESucceeds) { michael@0: EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2, michael@0: ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2, michael@0: michael@0: // or when val1 is greater than, but almost equals to, val2. michael@0: EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f); michael@0: } michael@0: michael@0: // Tests the cases where FloatLE() should fail. michael@0: TEST_F(FloatTest, FloatLEFails) { michael@0: // When val1 is greater than val2 by a large margin, michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f), michael@0: "(2.0f) <= (1.0f)"); michael@0: michael@0: // or by a small yet non-negligible margin, michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); michael@0: }, "(values_.further_from_one) <= (1.0f)"); michael@0: michael@0: #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) michael@0: // Nokia's STLport crashes if we try to output infinity or NaN. michael@0: // C++Builder gives bad results for ordered comparisons involving NaNs michael@0: // due to compiler bugs. michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity); michael@0: }, "(values_.nan1) <= (values_.infinity)"); michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1); michael@0: }, "(-values_.infinity) <= (values_.nan1)"); michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); michael@0: }, "(values_.nan1) <= (values_.nan1)"); michael@0: #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) michael@0: } michael@0: michael@0: // Instantiates FloatingPointTest for testing *_DOUBLE_EQ. michael@0: typedef FloatingPointTest DoubleTest; michael@0: michael@0: // Tests that the size of Double::Bits matches the size of double. michael@0: TEST_F(DoubleTest, Size) { michael@0: TestSize(); michael@0: } michael@0: michael@0: // Tests comparing with +0 and -0. michael@0: TEST_F(DoubleTest, Zeros) { michael@0: EXPECT_DOUBLE_EQ(0.0, -0.0); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), michael@0: "1.0"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), michael@0: "1.0"); michael@0: } michael@0: michael@0: // Tests comparing numbers close to 0. michael@0: // michael@0: // This ensures that *_DOUBLE_EQ handles the sign correctly and no michael@0: // overflow occurs when comparing numbers whose absolute value is very michael@0: // small. michael@0: TEST_F(DoubleTest, AlmostZeros) { michael@0: // In C++Builder, names within local classes (such as used by michael@0: // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the michael@0: // scoping class. Use a static local alias as a workaround. michael@0: // We use the assignment syntax since some compilers, like Sun Studio, michael@0: // don't allow initializing references using construction syntax michael@0: // (parentheses). michael@0: static const DoubleTest::TestValues& v = this->values_; michael@0: michael@0: EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero); michael@0: EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero); michael@0: EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero); michael@0: michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_DOUBLE_EQ(v.close_to_positive_zero, michael@0: v.further_from_negative_zero); michael@0: }, "v.further_from_negative_zero"); michael@0: } michael@0: michael@0: // Tests comparing numbers close to each other. michael@0: TEST_F(DoubleTest, SmallDiff) { michael@0: EXPECT_DOUBLE_EQ(1.0, values_.close_to_one); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one), michael@0: "values_.further_from_one"); michael@0: } michael@0: michael@0: // Tests comparing numbers far apart. michael@0: TEST_F(DoubleTest, LargeDiff) { michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), michael@0: "3.0"); michael@0: } michael@0: michael@0: // Tests comparing with infinity. michael@0: // michael@0: // This ensures that no overflow occurs when comparing numbers whose michael@0: // absolute value is very large. michael@0: TEST_F(DoubleTest, Infinity) { michael@0: EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity); michael@0: EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity); michael@0: #if !GTEST_OS_SYMBIAN michael@0: // Nokia's STLport crashes if we try to output infinity or NaN. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity), michael@0: "-values_.infinity"); michael@0: michael@0: // This is interesting as the representations of infinity_ and nan1_ michael@0: // are only 1 DLP apart. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1), michael@0: "values_.nan1"); michael@0: #endif // !GTEST_OS_SYMBIAN michael@0: } michael@0: michael@0: // Tests that comparing with NAN always returns false. michael@0: TEST_F(DoubleTest, NaN) { michael@0: #if !GTEST_OS_SYMBIAN michael@0: // In C++Builder, names within local classes (such as used by michael@0: // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the michael@0: // scoping class. Use a static local alias as a workaround. michael@0: // We use the assignment syntax since some compilers, like Sun Studio, michael@0: // don't allow initializing references using construction syntax michael@0: // (parentheses). michael@0: static const DoubleTest::TestValues& v = this->values_; michael@0: michael@0: // Nokia's STLport crashes if we try to output infinity or NaN. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), michael@0: "v.nan1"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), michael@0: "v.infinity"); michael@0: #endif // !GTEST_OS_SYMBIAN michael@0: } michael@0: michael@0: // Tests that *_DOUBLE_EQ are reflexive. michael@0: TEST_F(DoubleTest, Reflexive) { michael@0: EXPECT_DOUBLE_EQ(0.0, 0.0); michael@0: EXPECT_DOUBLE_EQ(1.0, 1.0); michael@0: #if !GTEST_OS_SYMBIAN michael@0: // Nokia's STLport crashes if we try to output infinity or NaN. michael@0: ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity); michael@0: #endif // !GTEST_OS_SYMBIAN michael@0: } michael@0: michael@0: // Tests that *_DOUBLE_EQ are commutative. michael@0: TEST_F(DoubleTest, Commutative) { michael@0: // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one). michael@0: EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0); michael@0: michael@0: // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one). michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0), michael@0: "1.0"); michael@0: } michael@0: michael@0: // Tests EXPECT_NEAR. michael@0: TEST_F(DoubleTest, EXPECT_NEAR) { michael@0: EXPECT_NEAR(-1.0, -1.1, 0.2); michael@0: EXPECT_NEAR(2.0, 3.0, 1.0); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT michael@0: "The difference between 1.0 and 1.5 is 0.5, " michael@0: "which exceeds 0.25"); michael@0: // To work around a bug in gcc 2.95.0, there is intentionally no michael@0: // space after the first comma in the previous statement. michael@0: } michael@0: michael@0: // Tests ASSERT_NEAR. michael@0: TEST_F(DoubleTest, ASSERT_NEAR) { michael@0: ASSERT_NEAR(-1.0, -1.1, 0.2); michael@0: ASSERT_NEAR(2.0, 3.0, 1.0); michael@0: EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT michael@0: "The difference between 1.0 and 1.5 is 0.5, " michael@0: "which exceeds 0.25"); michael@0: // To work around a bug in gcc 2.95.0, there is intentionally no michael@0: // space after the first comma in the previous statement. michael@0: } michael@0: michael@0: // Tests the cases where DoubleLE() should succeed. michael@0: TEST_F(DoubleTest, DoubleLESucceeds) { michael@0: EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2, michael@0: ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2, michael@0: michael@0: // or when val1 is greater than, but almost equals to, val2. michael@0: EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0); michael@0: } michael@0: michael@0: // Tests the cases where DoubleLE() should fail. michael@0: TEST_F(DoubleTest, DoubleLEFails) { michael@0: // When val1 is greater than val2 by a large margin, michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0), michael@0: "(2.0) <= (1.0)"); michael@0: michael@0: // or by a small yet non-negligible margin, michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); michael@0: }, "(values_.further_from_one) <= (1.0)"); michael@0: michael@0: #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) michael@0: // Nokia's STLport crashes if we try to output infinity or NaN. michael@0: // C++Builder gives bad results for ordered comparisons involving NaNs michael@0: // due to compiler bugs. michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity); michael@0: }, "(values_.nan1) <= (values_.infinity)"); michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1); michael@0: }, " (-values_.infinity) <= (values_.nan1)"); michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); michael@0: }, "(values_.nan1) <= (values_.nan1)"); michael@0: #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) michael@0: } michael@0: michael@0: michael@0: // Verifies that a test or test case whose name starts with DISABLED_ is michael@0: // not run. michael@0: michael@0: // A test whose name starts with DISABLED_. michael@0: // Should not run. michael@0: TEST(DisabledTest, DISABLED_TestShouldNotRun) { michael@0: FAIL() << "Unexpected failure: Disabled test should not be run."; michael@0: } michael@0: michael@0: // A test whose name does not start with DISABLED_. michael@0: // Should run. michael@0: TEST(DisabledTest, NotDISABLED_TestShouldRun) { michael@0: EXPECT_EQ(1, 1); michael@0: } michael@0: michael@0: // A test case whose name starts with DISABLED_. michael@0: // Should not run. michael@0: TEST(DISABLED_TestCase, TestShouldNotRun) { michael@0: FAIL() << "Unexpected failure: Test in disabled test case should not be run."; michael@0: } michael@0: michael@0: // A test case and test whose names start with DISABLED_. michael@0: // Should not run. michael@0: TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) { michael@0: FAIL() << "Unexpected failure: Test in disabled test case should not be run."; michael@0: } michael@0: michael@0: // Check that when all tests in a test case are disabled, SetupTestCase() and michael@0: // TearDownTestCase() are not called. michael@0: class DisabledTestsTest : public Test { michael@0: protected: michael@0: static void SetUpTestCase() { michael@0: FAIL() << "Unexpected failure: All tests disabled in test case. " michael@0: "SetupTestCase() should not be called."; michael@0: } michael@0: michael@0: static void TearDownTestCase() { michael@0: FAIL() << "Unexpected failure: All tests disabled in test case. " michael@0: "TearDownTestCase() should not be called."; michael@0: } michael@0: }; michael@0: michael@0: TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) { michael@0: FAIL() << "Unexpected failure: Disabled test should not be run."; michael@0: } michael@0: michael@0: TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) { michael@0: FAIL() << "Unexpected failure: Disabled test should not be run."; michael@0: } michael@0: michael@0: // Tests that disabled typed tests aren't run. michael@0: michael@0: #if GTEST_HAS_TYPED_TEST michael@0: michael@0: template michael@0: class TypedTest : public Test { michael@0: }; michael@0: michael@0: typedef testing::Types NumericTypes; michael@0: TYPED_TEST_CASE(TypedTest, NumericTypes); michael@0: michael@0: TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { michael@0: FAIL() << "Unexpected failure: Disabled typed test should not run."; michael@0: } michael@0: michael@0: template michael@0: class DISABLED_TypedTest : public Test { michael@0: }; michael@0: michael@0: TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes); michael@0: michael@0: TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { michael@0: FAIL() << "Unexpected failure: Disabled typed test should not run."; michael@0: } michael@0: michael@0: #endif // GTEST_HAS_TYPED_TEST michael@0: michael@0: // Tests that disabled type-parameterized tests aren't run. michael@0: michael@0: #if GTEST_HAS_TYPED_TEST_P michael@0: michael@0: template michael@0: class TypedTestP : public Test { michael@0: }; michael@0: michael@0: TYPED_TEST_CASE_P(TypedTestP); michael@0: michael@0: TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) { michael@0: FAIL() << "Unexpected failure: " michael@0: << "Disabled type-parameterized test should not run."; michael@0: } michael@0: michael@0: REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun); michael@0: michael@0: INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes); michael@0: michael@0: template michael@0: class DISABLED_TypedTestP : public Test { michael@0: }; michael@0: michael@0: TYPED_TEST_CASE_P(DISABLED_TypedTestP); michael@0: michael@0: TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) { michael@0: FAIL() << "Unexpected failure: " michael@0: << "Disabled type-parameterized test should not run."; michael@0: } michael@0: michael@0: REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun); michael@0: michael@0: INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes); michael@0: michael@0: #endif // GTEST_HAS_TYPED_TEST_P michael@0: michael@0: // Tests that assertion macros evaluate their arguments exactly once. michael@0: michael@0: class SingleEvaluationTest : public Test { michael@0: public: // Must be public and not protected due to a bug in g++ 3.4.2. michael@0: // This helper function is needed by the FailedASSERT_STREQ test michael@0: // below. It's public to work around C++Builder's bug with scoping local michael@0: // classes. michael@0: static void CompareAndIncrementCharPtrs() { michael@0: ASSERT_STREQ(p1_++, p2_++); michael@0: } michael@0: michael@0: // This helper function is needed by the FailedASSERT_NE test below. It's michael@0: // public to work around C++Builder's bug with scoping local classes. michael@0: static void CompareAndIncrementInts() { michael@0: ASSERT_NE(a_++, b_++); michael@0: } michael@0: michael@0: protected: michael@0: SingleEvaluationTest() { michael@0: p1_ = s1_; michael@0: p2_ = s2_; michael@0: a_ = 0; michael@0: b_ = 0; michael@0: } michael@0: michael@0: static const char* const s1_; michael@0: static const char* const s2_; michael@0: static const char* p1_; michael@0: static const char* p2_; michael@0: michael@0: static int a_; michael@0: static int b_; michael@0: }; michael@0: michael@0: const char* const SingleEvaluationTest::s1_ = "01234"; michael@0: const char* const SingleEvaluationTest::s2_ = "abcde"; michael@0: const char* SingleEvaluationTest::p1_; michael@0: const char* SingleEvaluationTest::p2_; michael@0: int SingleEvaluationTest::a_; michael@0: int SingleEvaluationTest::b_; michael@0: michael@0: // Tests that when ASSERT_STREQ fails, it evaluates its arguments michael@0: // exactly once. michael@0: TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) { michael@0: EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(), michael@0: "p2_++"); michael@0: EXPECT_EQ(s1_ + 1, p1_); michael@0: EXPECT_EQ(s2_ + 1, p2_); michael@0: } michael@0: michael@0: // Tests that string assertion arguments are evaluated exactly once. michael@0: TEST_F(SingleEvaluationTest, ASSERT_STR) { michael@0: // successful EXPECT_STRNE michael@0: EXPECT_STRNE(p1_++, p2_++); michael@0: EXPECT_EQ(s1_ + 1, p1_); michael@0: EXPECT_EQ(s2_ + 1, p2_); michael@0: michael@0: // failed EXPECT_STRCASEEQ michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), michael@0: "ignoring case"); michael@0: EXPECT_EQ(s1_ + 2, p1_); michael@0: EXPECT_EQ(s2_ + 2, p2_); michael@0: } michael@0: michael@0: // Tests that when ASSERT_NE fails, it evaluates its arguments exactly michael@0: // once. michael@0: TEST_F(SingleEvaluationTest, FailedASSERT_NE) { michael@0: EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(), michael@0: "(a_++) != (b_++)"); michael@0: EXPECT_EQ(1, a_); michael@0: EXPECT_EQ(1, b_); michael@0: } michael@0: michael@0: // Tests that assertion arguments are evaluated exactly once. michael@0: TEST_F(SingleEvaluationTest, OtherCases) { michael@0: // successful EXPECT_TRUE michael@0: EXPECT_TRUE(0 == a_++); // NOLINT michael@0: EXPECT_EQ(1, a_); michael@0: michael@0: // failed EXPECT_TRUE michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++"); michael@0: EXPECT_EQ(2, a_); michael@0: michael@0: // successful EXPECT_GT michael@0: EXPECT_GT(a_++, b_++); michael@0: EXPECT_EQ(3, a_); michael@0: EXPECT_EQ(1, b_); michael@0: michael@0: // failed EXPECT_LT michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)"); michael@0: EXPECT_EQ(4, a_); michael@0: EXPECT_EQ(2, b_); michael@0: michael@0: // successful ASSERT_TRUE michael@0: ASSERT_TRUE(0 < a_++); // NOLINT michael@0: EXPECT_EQ(5, a_); michael@0: michael@0: // successful ASSERT_GT michael@0: ASSERT_GT(a_++, b_++); michael@0: EXPECT_EQ(6, a_); michael@0: EXPECT_EQ(3, b_); michael@0: } michael@0: michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: michael@0: void ThrowAnInteger() { michael@0: throw 1; michael@0: } michael@0: michael@0: // Tests that assertion arguments are evaluated exactly once. michael@0: TEST_F(SingleEvaluationTest, ExceptionTests) { michael@0: // successful EXPECT_THROW michael@0: EXPECT_THROW({ // NOLINT michael@0: a_++; michael@0: ThrowAnInteger(); michael@0: }, int); michael@0: EXPECT_EQ(1, a_); michael@0: michael@0: // failed EXPECT_THROW, throws different michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT michael@0: a_++; michael@0: ThrowAnInteger(); michael@0: }, bool), "throws a different type"); michael@0: EXPECT_EQ(2, a_); michael@0: michael@0: // failed EXPECT_THROW, throws nothing michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing"); michael@0: EXPECT_EQ(3, a_); michael@0: michael@0: // successful EXPECT_NO_THROW michael@0: EXPECT_NO_THROW(a_++); michael@0: EXPECT_EQ(4, a_); michael@0: michael@0: // failed EXPECT_NO_THROW michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT michael@0: a_++; michael@0: ThrowAnInteger(); michael@0: }), "it throws"); michael@0: EXPECT_EQ(5, a_); michael@0: michael@0: // successful EXPECT_ANY_THROW michael@0: EXPECT_ANY_THROW({ // NOLINT michael@0: a_++; michael@0: ThrowAnInteger(); michael@0: }); michael@0: EXPECT_EQ(6, a_); michael@0: michael@0: // failed EXPECT_ANY_THROW michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't"); michael@0: EXPECT_EQ(7, a_); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_EXCEPTIONS michael@0: michael@0: // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE. michael@0: class NoFatalFailureTest : public Test { michael@0: protected: michael@0: void Succeeds() {} michael@0: void FailsNonFatal() { michael@0: ADD_FAILURE() << "some non-fatal failure"; michael@0: } michael@0: void Fails() { michael@0: FAIL() << "some fatal failure"; michael@0: } michael@0: michael@0: void DoAssertNoFatalFailureOnFails() { michael@0: ASSERT_NO_FATAL_FAILURE(Fails()); michael@0: ADD_FAILURE() << "shold not reach here."; michael@0: } michael@0: michael@0: void DoExpectNoFatalFailureOnFails() { michael@0: EXPECT_NO_FATAL_FAILURE(Fails()); michael@0: ADD_FAILURE() << "other failure"; michael@0: } michael@0: }; michael@0: michael@0: TEST_F(NoFatalFailureTest, NoFailure) { michael@0: EXPECT_NO_FATAL_FAILURE(Succeeds()); michael@0: ASSERT_NO_FATAL_FAILURE(Succeeds()); michael@0: } michael@0: michael@0: TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) { michael@0: EXPECT_NONFATAL_FAILURE( michael@0: EXPECT_NO_FATAL_FAILURE(FailsNonFatal()), michael@0: "some non-fatal failure"); michael@0: EXPECT_NONFATAL_FAILURE( michael@0: ASSERT_NO_FATAL_FAILURE(FailsNonFatal()), michael@0: "some non-fatal failure"); michael@0: } michael@0: michael@0: TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) { michael@0: TestPartResultArray gtest_failures; michael@0: { michael@0: ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); michael@0: DoAssertNoFatalFailureOnFails(); michael@0: } michael@0: ASSERT_EQ(2, gtest_failures.size()); michael@0: EXPECT_EQ(TestPartResult::kFatalFailure, michael@0: gtest_failures.GetTestPartResult(0).type()); michael@0: EXPECT_EQ(TestPartResult::kFatalFailure, michael@0: gtest_failures.GetTestPartResult(1).type()); michael@0: EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", michael@0: gtest_failures.GetTestPartResult(0).message()); michael@0: EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", michael@0: gtest_failures.GetTestPartResult(1).message()); michael@0: } michael@0: michael@0: TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) { michael@0: TestPartResultArray gtest_failures; michael@0: { michael@0: ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); michael@0: DoExpectNoFatalFailureOnFails(); michael@0: } michael@0: ASSERT_EQ(3, gtest_failures.size()); michael@0: EXPECT_EQ(TestPartResult::kFatalFailure, michael@0: gtest_failures.GetTestPartResult(0).type()); michael@0: EXPECT_EQ(TestPartResult::kNonFatalFailure, michael@0: gtest_failures.GetTestPartResult(1).type()); michael@0: EXPECT_EQ(TestPartResult::kNonFatalFailure, michael@0: gtest_failures.GetTestPartResult(2).type()); michael@0: EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", michael@0: gtest_failures.GetTestPartResult(0).message()); michael@0: EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", michael@0: gtest_failures.GetTestPartResult(1).message()); michael@0: EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure", michael@0: gtest_failures.GetTestPartResult(2).message()); michael@0: } michael@0: michael@0: TEST_F(NoFatalFailureTest, MessageIsStreamable) { michael@0: TestPartResultArray gtest_failures; michael@0: { michael@0: ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); michael@0: EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message"; michael@0: } michael@0: ASSERT_EQ(2, gtest_failures.size()); michael@0: EXPECT_EQ(TestPartResult::kNonFatalFailure, michael@0: gtest_failures.GetTestPartResult(0).type()); michael@0: EXPECT_EQ(TestPartResult::kNonFatalFailure, michael@0: gtest_failures.GetTestPartResult(1).type()); michael@0: EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo", michael@0: gtest_failures.GetTestPartResult(0).message()); michael@0: EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message", michael@0: gtest_failures.GetTestPartResult(1).message()); michael@0: } michael@0: michael@0: // Tests non-string assertions. michael@0: michael@0: // Tests EqFailure(), used for implementing *EQ* assertions. michael@0: TEST(AssertionTest, EqFailure) { michael@0: const String foo_val("5"), bar_val("6"); michael@0: const String msg1( michael@0: EqFailure("foo", "bar", foo_val, bar_val, false) michael@0: .failure_message()); michael@0: EXPECT_STREQ( michael@0: "Value of: bar\n" michael@0: " Actual: 6\n" michael@0: "Expected: foo\n" michael@0: "Which is: 5", michael@0: msg1.c_str()); michael@0: michael@0: const String msg2( michael@0: EqFailure("foo", "6", foo_val, bar_val, false) michael@0: .failure_message()); michael@0: EXPECT_STREQ( michael@0: "Value of: 6\n" michael@0: "Expected: foo\n" michael@0: "Which is: 5", michael@0: msg2.c_str()); michael@0: michael@0: const String msg3( michael@0: EqFailure("5", "bar", foo_val, bar_val, false) michael@0: .failure_message()); michael@0: EXPECT_STREQ( michael@0: "Value of: bar\n" michael@0: " Actual: 6\n" michael@0: "Expected: 5", michael@0: msg3.c_str()); michael@0: michael@0: const String msg4( michael@0: EqFailure("5", "6", foo_val, bar_val, false).failure_message()); michael@0: EXPECT_STREQ( michael@0: "Value of: 6\n" michael@0: "Expected: 5", michael@0: msg4.c_str()); michael@0: michael@0: const String msg5( michael@0: EqFailure("foo", "bar", michael@0: String("\"x\""), String("\"y\""), michael@0: true).failure_message()); michael@0: EXPECT_STREQ( michael@0: "Value of: bar\n" michael@0: " Actual: \"y\"\n" michael@0: "Expected: foo (ignoring case)\n" michael@0: "Which is: \"x\"", michael@0: msg5.c_str()); michael@0: } michael@0: michael@0: // Tests AppendUserMessage(), used for implementing the *EQ* macros. michael@0: TEST(AssertionTest, AppendUserMessage) { michael@0: const String foo("foo"); michael@0: michael@0: Message msg; michael@0: EXPECT_STREQ("foo", michael@0: AppendUserMessage(foo, msg).c_str()); michael@0: michael@0: msg << "bar"; michael@0: EXPECT_STREQ("foo\nbar", michael@0: AppendUserMessage(foo, msg).c_str()); michael@0: } michael@0: michael@0: #ifdef __BORLANDC__ michael@0: // Silences warnings: "Condition is always true", "Unreachable code" michael@0: # pragma option push -w-ccc -w-rch michael@0: #endif michael@0: michael@0: // Tests ASSERT_TRUE. michael@0: TEST(AssertionTest, ASSERT_TRUE) { michael@0: ASSERT_TRUE(2 > 1); // NOLINT michael@0: EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), michael@0: "2 < 1"); michael@0: } michael@0: michael@0: // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult. michael@0: TEST(AssertionTest, AssertTrueWithAssertionResult) { michael@0: ASSERT_TRUE(ResultIsEven(2)); michael@0: #ifndef __BORLANDC__ michael@0: // ICE's in C++Builder. michael@0: EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)), michael@0: "Value of: ResultIsEven(3)\n" michael@0: " Actual: false (3 is odd)\n" michael@0: "Expected: true"); michael@0: #endif michael@0: ASSERT_TRUE(ResultIsEvenNoExplanation(2)); michael@0: EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)), michael@0: "Value of: ResultIsEvenNoExplanation(3)\n" michael@0: " Actual: false (3 is odd)\n" michael@0: "Expected: true"); michael@0: } michael@0: michael@0: // Tests ASSERT_FALSE. michael@0: TEST(AssertionTest, ASSERT_FALSE) { michael@0: ASSERT_FALSE(2 < 1); // NOLINT michael@0: EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1), michael@0: "Value of: 2 > 1\n" michael@0: " Actual: true\n" michael@0: "Expected: false"); michael@0: } michael@0: michael@0: // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult. michael@0: TEST(AssertionTest, AssertFalseWithAssertionResult) { michael@0: ASSERT_FALSE(ResultIsEven(3)); michael@0: #ifndef __BORLANDC__ michael@0: // ICE's in C++Builder. michael@0: EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)), michael@0: "Value of: ResultIsEven(2)\n" michael@0: " Actual: true (2 is even)\n" michael@0: "Expected: false"); michael@0: #endif michael@0: ASSERT_FALSE(ResultIsEvenNoExplanation(3)); michael@0: EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)), michael@0: "Value of: ResultIsEvenNoExplanation(2)\n" michael@0: " Actual: true\n" michael@0: "Expected: false"); michael@0: } michael@0: michael@0: #ifdef __BORLANDC__ michael@0: // Restores warnings after previous "#pragma option push" supressed them michael@0: # pragma option pop michael@0: #endif michael@0: michael@0: // Tests using ASSERT_EQ on double values. The purpose is to make michael@0: // sure that the specialization we did for integer and anonymous enums michael@0: // isn't used for double arguments. michael@0: TEST(ExpectTest, ASSERT_EQ_Double) { michael@0: // A success. michael@0: ASSERT_EQ(5.6, 5.6); michael@0: michael@0: // A failure. michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), michael@0: "5.1"); michael@0: } michael@0: michael@0: // Tests ASSERT_EQ. michael@0: TEST(AssertionTest, ASSERT_EQ) { michael@0: ASSERT_EQ(5, 2 + 3); michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), michael@0: "Value of: 2*3\n" michael@0: " Actual: 6\n" michael@0: "Expected: 5"); michael@0: } michael@0: michael@0: // Tests ASSERT_EQ(NULL, pointer). michael@0: #if GTEST_CAN_COMPARE_NULL michael@0: TEST(AssertionTest, ASSERT_EQ_NULL) { michael@0: // A success. michael@0: const char* p = NULL; michael@0: // Some older GCC versions may issue a spurious waring in this or the next michael@0: // assertion statement. This warning should not be suppressed with michael@0: // static_cast since the test verifies the ability to use bare NULL as the michael@0: // expected parameter to the macro. michael@0: ASSERT_EQ(NULL, p); michael@0: michael@0: // A failure. michael@0: static int n = 0; michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n), michael@0: "Value of: &n\n"); michael@0: } michael@0: #endif // GTEST_CAN_COMPARE_NULL michael@0: michael@0: // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be michael@0: // treated as a null pointer by the compiler, we need to make sure michael@0: // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as michael@0: // ASSERT_EQ(static_cast(NULL), non_pointer). michael@0: TEST(ExpectTest, ASSERT_EQ_0) { michael@0: int n = 0; michael@0: michael@0: // A success. michael@0: ASSERT_EQ(0, n); michael@0: michael@0: // A failure. michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), michael@0: "Expected: 0"); michael@0: } michael@0: michael@0: // Tests ASSERT_NE. michael@0: TEST(AssertionTest, ASSERT_NE) { michael@0: ASSERT_NE(6, 7); michael@0: EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'), michael@0: "Expected: ('a') != ('a'), " michael@0: "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); michael@0: } michael@0: michael@0: // Tests ASSERT_LE. michael@0: TEST(AssertionTest, ASSERT_LE) { michael@0: ASSERT_LE(2, 3); michael@0: ASSERT_LE(2, 2); michael@0: EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), michael@0: "Expected: (2) <= (0), actual: 2 vs 0"); michael@0: } michael@0: michael@0: // Tests ASSERT_LT. michael@0: TEST(AssertionTest, ASSERT_LT) { michael@0: ASSERT_LT(2, 3); michael@0: EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), michael@0: "Expected: (2) < (2), actual: 2 vs 2"); michael@0: } michael@0: michael@0: // Tests ASSERT_GE. michael@0: TEST(AssertionTest, ASSERT_GE) { michael@0: ASSERT_GE(2, 1); michael@0: ASSERT_GE(2, 2); michael@0: EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), michael@0: "Expected: (2) >= (3), actual: 2 vs 3"); michael@0: } michael@0: michael@0: // Tests ASSERT_GT. michael@0: TEST(AssertionTest, ASSERT_GT) { michael@0: ASSERT_GT(2, 1); michael@0: EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), michael@0: "Expected: (2) > (2), actual: 2 vs 2"); michael@0: } michael@0: michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: michael@0: void ThrowNothing() {} michael@0: michael@0: // Tests ASSERT_THROW. michael@0: TEST(AssertionTest, ASSERT_THROW) { michael@0: ASSERT_THROW(ThrowAnInteger(), int); michael@0: michael@0: # ifndef __BORLANDC__ michael@0: michael@0: // ICE's in C++Builder 2007 and 2009. michael@0: EXPECT_FATAL_FAILURE( michael@0: ASSERT_THROW(ThrowAnInteger(), bool), michael@0: "Expected: ThrowAnInteger() throws an exception of type bool.\n" michael@0: " Actual: it throws a different type."); michael@0: # endif michael@0: michael@0: EXPECT_FATAL_FAILURE( michael@0: ASSERT_THROW(ThrowNothing(), bool), michael@0: "Expected: ThrowNothing() throws an exception of type bool.\n" michael@0: " Actual: it throws nothing."); michael@0: } michael@0: michael@0: // Tests ASSERT_NO_THROW. michael@0: TEST(AssertionTest, ASSERT_NO_THROW) { michael@0: ASSERT_NO_THROW(ThrowNothing()); michael@0: EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()), michael@0: "Expected: ThrowAnInteger() doesn't throw an exception." michael@0: "\n Actual: it throws."); michael@0: } michael@0: michael@0: // Tests ASSERT_ANY_THROW. michael@0: TEST(AssertionTest, ASSERT_ANY_THROW) { michael@0: ASSERT_ANY_THROW(ThrowAnInteger()); michael@0: EXPECT_FATAL_FAILURE( michael@0: ASSERT_ANY_THROW(ThrowNothing()), michael@0: "Expected: ThrowNothing() throws an exception.\n" michael@0: " Actual: it doesn't."); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_EXCEPTIONS michael@0: michael@0: // Makes sure we deal with the precedence of <<. This test should michael@0: // compile. michael@0: TEST(AssertionTest, AssertPrecedence) { michael@0: ASSERT_EQ(1 < 2, true); michael@0: bool false_value = false; michael@0: ASSERT_EQ(true && false_value, false); michael@0: } michael@0: michael@0: // A subroutine used by the following test. michael@0: void TestEq1(int x) { michael@0: ASSERT_EQ(1, x); michael@0: } michael@0: michael@0: // Tests calling a test subroutine that's not part of a fixture. michael@0: TEST(AssertionTest, NonFixtureSubroutine) { michael@0: EXPECT_FATAL_FAILURE(TestEq1(2), michael@0: "Value of: x"); michael@0: } michael@0: michael@0: // An uncopyable class. michael@0: class Uncopyable { michael@0: public: michael@0: explicit Uncopyable(int a_value) : value_(a_value) {} michael@0: michael@0: int value() const { return value_; } michael@0: bool operator==(const Uncopyable& rhs) const { michael@0: return value() == rhs.value(); michael@0: } michael@0: private: michael@0: // This constructor deliberately has no implementation, as we don't michael@0: // want this class to be copyable. michael@0: Uncopyable(const Uncopyable&); // NOLINT michael@0: michael@0: int value_; michael@0: }; michael@0: michael@0: ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) { michael@0: return os << value.value(); michael@0: } michael@0: michael@0: michael@0: bool IsPositiveUncopyable(const Uncopyable& x) { michael@0: return x.value() > 0; michael@0: } michael@0: michael@0: // A subroutine used by the following test. michael@0: void TestAssertNonPositive() { michael@0: Uncopyable y(-1); michael@0: ASSERT_PRED1(IsPositiveUncopyable, y); michael@0: } michael@0: // A subroutine used by the following test. michael@0: void TestAssertEqualsUncopyable() { michael@0: Uncopyable x(5); michael@0: Uncopyable y(-1); michael@0: ASSERT_EQ(x, y); michael@0: } michael@0: michael@0: // Tests that uncopyable objects can be used in assertions. michael@0: TEST(AssertionTest, AssertWorksWithUncopyableObject) { michael@0: Uncopyable x(5); michael@0: ASSERT_PRED1(IsPositiveUncopyable, x); michael@0: ASSERT_EQ(x, x); michael@0: EXPECT_FATAL_FAILURE(TestAssertNonPositive(), michael@0: "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); michael@0: EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(), michael@0: "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5"); michael@0: } michael@0: michael@0: // Tests that uncopyable objects can be used in expects. michael@0: TEST(AssertionTest, ExpectWorksWithUncopyableObject) { michael@0: Uncopyable x(5); michael@0: EXPECT_PRED1(IsPositiveUncopyable, x); michael@0: Uncopyable y(-1); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y), michael@0: "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); michael@0: EXPECT_EQ(x, x); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), michael@0: "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5"); michael@0: } michael@0: michael@0: enum NamedEnum { michael@0: kE1 = 0, michael@0: kE2 = 1 michael@0: }; michael@0: michael@0: TEST(AssertionTest, NamedEnum) { michael@0: EXPECT_EQ(kE1, kE1); michael@0: EXPECT_LT(kE1, kE2); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1"); michael@0: } michael@0: michael@0: // The version of gcc used in XCode 2.2 has a bug and doesn't allow michael@0: // anonymous enums in assertions. Therefore the following test is not michael@0: // done on Mac. michael@0: // Sun Studio and HP aCC also reject this code. michael@0: #if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC) michael@0: michael@0: // Tests using assertions with anonymous enums. michael@0: enum { michael@0: kCaseA = -1, michael@0: michael@0: # if GTEST_OS_LINUX michael@0: michael@0: // We want to test the case where the size of the anonymous enum is michael@0: // larger than sizeof(int), to make sure our implementation of the michael@0: // assertions doesn't truncate the enums. However, MSVC michael@0: // (incorrectly) doesn't allow an enum value to exceed the range of michael@0: // an int, so this has to be conditionally compiled. michael@0: // michael@0: // On Linux, kCaseB and kCaseA have the same value when truncated to michael@0: // int size. We want to test whether this will confuse the michael@0: // assertions. michael@0: kCaseB = testing::internal::kMaxBiggestInt, michael@0: michael@0: # else michael@0: michael@0: kCaseB = INT_MAX, michael@0: michael@0: # endif // GTEST_OS_LINUX michael@0: michael@0: kCaseC = 42 michael@0: }; michael@0: michael@0: TEST(AssertionTest, AnonymousEnum) { michael@0: # if GTEST_OS_LINUX michael@0: michael@0: EXPECT_EQ(static_cast(kCaseA), static_cast(kCaseB)); michael@0: michael@0: # endif // GTEST_OS_LINUX michael@0: michael@0: EXPECT_EQ(kCaseA, kCaseA); michael@0: EXPECT_NE(kCaseA, kCaseB); michael@0: EXPECT_LT(kCaseA, kCaseB); michael@0: EXPECT_LE(kCaseA, kCaseB); michael@0: EXPECT_GT(kCaseB, kCaseA); michael@0: EXPECT_GE(kCaseA, kCaseA); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), michael@0: "(kCaseA) >= (kCaseB)"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), michael@0: "-1 vs 42"); michael@0: michael@0: ASSERT_EQ(kCaseA, kCaseA); michael@0: ASSERT_NE(kCaseA, kCaseB); michael@0: ASSERT_LT(kCaseA, kCaseB); michael@0: ASSERT_LE(kCaseA, kCaseB); michael@0: ASSERT_GT(kCaseB, kCaseA); michael@0: ASSERT_GE(kCaseA, kCaseA); michael@0: michael@0: # ifndef __BORLANDC__ michael@0: michael@0: // ICE's in C++Builder. michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), michael@0: "Value of: kCaseB"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), michael@0: "Actual: 42"); michael@0: # endif michael@0: michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), michael@0: "Which is: -1"); michael@0: } michael@0: michael@0: #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC) michael@0: michael@0: #if GTEST_OS_WINDOWS michael@0: michael@0: static HRESULT UnexpectedHRESULTFailure() { michael@0: return E_UNEXPECTED; michael@0: } michael@0: michael@0: static HRESULT OkHRESULTSuccess() { michael@0: return S_OK; michael@0: } michael@0: michael@0: static HRESULT FalseHRESULTSuccess() { michael@0: return S_FALSE; michael@0: } michael@0: michael@0: // HRESULT assertion tests test both zero and non-zero michael@0: // success codes as well as failure message for each. michael@0: // michael@0: // Windows CE doesn't support message texts. michael@0: TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) { michael@0: EXPECT_HRESULT_SUCCEEDED(S_OK); michael@0: EXPECT_HRESULT_SUCCEEDED(S_FALSE); michael@0: michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), michael@0: "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" michael@0: " Actual: 0x8000FFFF"); michael@0: } michael@0: michael@0: TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) { michael@0: ASSERT_HRESULT_SUCCEEDED(S_OK); michael@0: ASSERT_HRESULT_SUCCEEDED(S_FALSE); michael@0: michael@0: EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), michael@0: "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" michael@0: " Actual: 0x8000FFFF"); michael@0: } michael@0: michael@0: TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) { michael@0: EXPECT_HRESULT_FAILED(E_UNEXPECTED); michael@0: michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()), michael@0: "Expected: (OkHRESULTSuccess()) fails.\n" michael@0: " Actual: 0x00000000"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()), michael@0: "Expected: (FalseHRESULTSuccess()) fails.\n" michael@0: " Actual: 0x00000001"); michael@0: } michael@0: michael@0: TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) { michael@0: ASSERT_HRESULT_FAILED(E_UNEXPECTED); michael@0: michael@0: # ifndef __BORLANDC__ michael@0: michael@0: // ICE's in C++Builder 2007 and 2009. michael@0: EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()), michael@0: "Expected: (OkHRESULTSuccess()) fails.\n" michael@0: " Actual: 0x00000000"); michael@0: # endif michael@0: michael@0: EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()), michael@0: "Expected: (FalseHRESULTSuccess()) fails.\n" michael@0: " Actual: 0x00000001"); michael@0: } michael@0: michael@0: // Tests that streaming to the HRESULT macros works. michael@0: TEST(HRESULTAssertionTest, Streaming) { michael@0: EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; michael@0: ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; michael@0: EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; michael@0: ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; michael@0: michael@0: EXPECT_NONFATAL_FAILURE( michael@0: EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", michael@0: "expected failure"); michael@0: michael@0: # ifndef __BORLANDC__ michael@0: michael@0: // ICE's in C++Builder 2007 and 2009. michael@0: EXPECT_FATAL_FAILURE( michael@0: ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", michael@0: "expected failure"); michael@0: # endif michael@0: michael@0: EXPECT_NONFATAL_FAILURE( michael@0: EXPECT_HRESULT_FAILED(S_OK) << "expected failure", michael@0: "expected failure"); michael@0: michael@0: EXPECT_FATAL_FAILURE( michael@0: ASSERT_HRESULT_FAILED(S_OK) << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: #endif // GTEST_OS_WINDOWS michael@0: michael@0: #ifdef __BORLANDC__ michael@0: // Silences warnings: "Condition is always true", "Unreachable code" michael@0: # pragma option push -w-ccc -w-rch michael@0: #endif michael@0: michael@0: // Tests that the assertion macros behave like single statements. michael@0: TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) { michael@0: if (AlwaysFalse()) michael@0: ASSERT_TRUE(false) << "This should never be executed; " michael@0: "It's a compilation test only."; michael@0: michael@0: if (AlwaysTrue()) michael@0: EXPECT_FALSE(false); michael@0: else michael@0: ; // NOLINT michael@0: michael@0: if (AlwaysFalse()) michael@0: ASSERT_LT(1, 3); michael@0: michael@0: if (AlwaysFalse()) michael@0: ; // NOLINT michael@0: else michael@0: EXPECT_GT(3, 2) << ""; michael@0: } michael@0: michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: // Tests that the compiler will not complain about unreachable code in the michael@0: // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros. michael@0: TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { michael@0: int n = 0; michael@0: michael@0: EXPECT_THROW(throw 1, int); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), ""); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), ""); michael@0: EXPECT_NO_THROW(n++); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), ""); michael@0: EXPECT_ANY_THROW(throw 1); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), ""); michael@0: } michael@0: michael@0: TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { michael@0: if (AlwaysFalse()) michael@0: EXPECT_THROW(ThrowNothing(), bool); michael@0: michael@0: if (AlwaysTrue()) michael@0: EXPECT_THROW(ThrowAnInteger(), int); michael@0: else michael@0: ; // NOLINT michael@0: michael@0: if (AlwaysFalse()) michael@0: EXPECT_NO_THROW(ThrowAnInteger()); michael@0: michael@0: if (AlwaysTrue()) michael@0: EXPECT_NO_THROW(ThrowNothing()); michael@0: else michael@0: ; // NOLINT michael@0: michael@0: if (AlwaysFalse()) michael@0: EXPECT_ANY_THROW(ThrowNothing()); michael@0: michael@0: if (AlwaysTrue()) michael@0: EXPECT_ANY_THROW(ThrowAnInteger()); michael@0: else michael@0: ; // NOLINT michael@0: } michael@0: #endif // GTEST_HAS_EXCEPTIONS michael@0: michael@0: TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) { michael@0: if (AlwaysFalse()) michael@0: EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. " michael@0: << "It's a compilation test only."; michael@0: else michael@0: ; // NOLINT michael@0: michael@0: if (AlwaysFalse()) michael@0: ASSERT_NO_FATAL_FAILURE(FAIL()) << ""; michael@0: else michael@0: ; // NOLINT michael@0: michael@0: if (AlwaysTrue()) michael@0: EXPECT_NO_FATAL_FAILURE(SUCCEED()); michael@0: else michael@0: ; // NOLINT michael@0: michael@0: if (AlwaysFalse()) michael@0: ; // NOLINT michael@0: else michael@0: ASSERT_NO_FATAL_FAILURE(SUCCEED()); michael@0: } michael@0: michael@0: // Tests that the assertion macros work well with switch statements. michael@0: TEST(AssertionSyntaxTest, WorksWithSwitch) { michael@0: switch (0) { michael@0: case 1: michael@0: break; michael@0: default: michael@0: ASSERT_TRUE(true); michael@0: } michael@0: michael@0: switch (0) michael@0: case 0: michael@0: EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case"; michael@0: michael@0: // Binary assertions are implemented using a different code path michael@0: // than the Boolean assertions. Hence we test them separately. michael@0: switch (0) { michael@0: case 1: michael@0: default: michael@0: ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler"; michael@0: } michael@0: michael@0: switch (0) michael@0: case 0: michael@0: EXPECT_NE(1, 2); michael@0: } michael@0: michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: michael@0: void ThrowAString() { michael@0: throw "String"; michael@0: } michael@0: michael@0: // Test that the exception assertion macros compile and work with const michael@0: // type qualifier. michael@0: TEST(AssertionSyntaxTest, WorksWithConst) { michael@0: ASSERT_THROW(ThrowAString(), const char*); michael@0: michael@0: EXPECT_THROW(ThrowAString(), const char*); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_EXCEPTIONS michael@0: michael@0: } // namespace michael@0: michael@0: namespace testing { michael@0: michael@0: // Tests that Google Test tracks SUCCEED*. michael@0: TEST(SuccessfulAssertionTest, SUCCEED) { michael@0: SUCCEED(); michael@0: SUCCEED() << "OK"; michael@0: EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count()); michael@0: } michael@0: michael@0: // Tests that Google Test doesn't track successful EXPECT_*. michael@0: TEST(SuccessfulAssertionTest, EXPECT) { michael@0: EXPECT_TRUE(true); michael@0: EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); michael@0: } michael@0: michael@0: // Tests that Google Test doesn't track successful EXPECT_STR*. michael@0: TEST(SuccessfulAssertionTest, EXPECT_STR) { michael@0: EXPECT_STREQ("", ""); michael@0: EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); michael@0: } michael@0: michael@0: // Tests that Google Test doesn't track successful ASSERT_*. michael@0: TEST(SuccessfulAssertionTest, ASSERT) { michael@0: ASSERT_TRUE(true); michael@0: EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); michael@0: } michael@0: michael@0: // Tests that Google Test doesn't track successful ASSERT_STR*. michael@0: TEST(SuccessfulAssertionTest, ASSERT_STR) { michael@0: ASSERT_STREQ("", ""); michael@0: EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); michael@0: } michael@0: michael@0: } // namespace testing michael@0: michael@0: namespace { michael@0: michael@0: // Tests the message streaming variation of assertions. michael@0: michael@0: TEST(AssertionWithMessageTest, EXPECT) { michael@0: EXPECT_EQ(1, 1) << "This should succeed."; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.", michael@0: "Expected failure #1"); michael@0: EXPECT_LE(1, 2) << "This should succeed."; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.", michael@0: "Expected failure #2."); michael@0: EXPECT_GE(1, 0) << "This should succeed."; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.", michael@0: "Expected failure #3."); michael@0: michael@0: EXPECT_STREQ("1", "1") << "This should succeed."; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.", michael@0: "Expected failure #4."); michael@0: EXPECT_STRCASEEQ("a", "A") << "This should succeed."; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.", michael@0: "Expected failure #5."); michael@0: michael@0: EXPECT_FLOAT_EQ(1, 1) << "This should succeed."; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.", michael@0: "Expected failure #6."); michael@0: EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed."; michael@0: } michael@0: michael@0: TEST(AssertionWithMessageTest, ASSERT) { michael@0: ASSERT_EQ(1, 1) << "This should succeed."; michael@0: ASSERT_NE(1, 2) << "This should succeed."; michael@0: ASSERT_LE(1, 2) << "This should succeed."; michael@0: ASSERT_LT(1, 2) << "This should succeed."; michael@0: ASSERT_GE(1, 0) << "This should succeed."; michael@0: EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.", michael@0: "Expected failure."); michael@0: } michael@0: michael@0: TEST(AssertionWithMessageTest, ASSERT_STR) { michael@0: ASSERT_STREQ("1", "1") << "This should succeed."; michael@0: ASSERT_STRNE("1", "2") << "This should succeed."; michael@0: ASSERT_STRCASEEQ("a", "A") << "This should succeed."; michael@0: EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.", michael@0: "Expected failure."); michael@0: } michael@0: michael@0: TEST(AssertionWithMessageTest, ASSERT_FLOATING) { michael@0: ASSERT_FLOAT_EQ(1, 1) << "This should succeed."; michael@0: ASSERT_DOUBLE_EQ(1, 1) << "This should succeed."; michael@0: EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT michael@0: "Expect failure."); michael@0: // To work around a bug in gcc 2.95.0, there is intentionally no michael@0: // space after the first comma in the previous statement. michael@0: } michael@0: michael@0: // Tests using ASSERT_FALSE with a streamed message. michael@0: TEST(AssertionWithMessageTest, ASSERT_FALSE) { michael@0: ASSERT_FALSE(false) << "This shouldn't fail."; michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1 michael@0: << " evaluates to " << true; michael@0: }, "Expected failure"); michael@0: } michael@0: michael@0: // Tests using FAIL with a streamed message. michael@0: TEST(AssertionWithMessageTest, FAIL) { michael@0: EXPECT_FATAL_FAILURE(FAIL() << 0, michael@0: "0"); michael@0: } michael@0: michael@0: // Tests using SUCCEED with a streamed message. michael@0: TEST(AssertionWithMessageTest, SUCCEED) { michael@0: SUCCEED() << "Success == " << 1; michael@0: } michael@0: michael@0: // Tests using ASSERT_TRUE with a streamed message. michael@0: TEST(AssertionWithMessageTest, ASSERT_TRUE) { michael@0: ASSERT_TRUE(true) << "This should succeed."; michael@0: ASSERT_TRUE(true) << true; michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_TRUE(false) << static_cast(NULL) michael@0: << static_cast(NULL); michael@0: }, "(null)(null)"); michael@0: } michael@0: michael@0: #if GTEST_OS_WINDOWS michael@0: // Tests using wide strings in assertion messages. michael@0: TEST(AssertionWithMessageTest, WideStringMessage) { michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_TRUE(false) << L"This failure is expected.\x8119"; michael@0: }, "This failure is expected."); michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_EQ(1, 2) << "This failure is " michael@0: << L"expected too.\x8120"; michael@0: }, "This failure is expected too."); michael@0: } michael@0: #endif // GTEST_OS_WINDOWS michael@0: michael@0: // Tests EXPECT_TRUE. michael@0: TEST(ExpectTest, EXPECT_TRUE) { michael@0: EXPECT_TRUE(true) << "Intentional success"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.", michael@0: "Intentional failure #1."); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.", michael@0: "Intentional failure #2."); michael@0: EXPECT_TRUE(2 > 1); // NOLINT michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1), michael@0: "Value of: 2 < 1\n" michael@0: " Actual: false\n" michael@0: "Expected: true"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), michael@0: "2 > 3"); michael@0: } michael@0: michael@0: // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult. michael@0: TEST(ExpectTest, ExpectTrueWithAssertionResult) { michael@0: EXPECT_TRUE(ResultIsEven(2)); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)), michael@0: "Value of: ResultIsEven(3)\n" michael@0: " Actual: false (3 is odd)\n" michael@0: "Expected: true"); michael@0: EXPECT_TRUE(ResultIsEvenNoExplanation(2)); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)), michael@0: "Value of: ResultIsEvenNoExplanation(3)\n" michael@0: " Actual: false (3 is odd)\n" michael@0: "Expected: true"); michael@0: } michael@0: michael@0: // Tests EXPECT_FALSE with a streamed message. michael@0: TEST(ExpectTest, EXPECT_FALSE) { michael@0: EXPECT_FALSE(2 < 1); // NOLINT michael@0: EXPECT_FALSE(false) << "Intentional success"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.", michael@0: "Intentional failure #1."); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.", michael@0: "Intentional failure #2."); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1), michael@0: "Value of: 2 > 1\n" michael@0: " Actual: true\n" michael@0: "Expected: false"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), michael@0: "2 < 3"); michael@0: } michael@0: michael@0: // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult. michael@0: TEST(ExpectTest, ExpectFalseWithAssertionResult) { michael@0: EXPECT_FALSE(ResultIsEven(3)); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)), michael@0: "Value of: ResultIsEven(2)\n" michael@0: " Actual: true (2 is even)\n" michael@0: "Expected: false"); michael@0: EXPECT_FALSE(ResultIsEvenNoExplanation(3)); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)), michael@0: "Value of: ResultIsEvenNoExplanation(2)\n" michael@0: " Actual: true\n" michael@0: "Expected: false"); michael@0: } michael@0: michael@0: #ifdef __BORLANDC__ michael@0: // Restores warnings after previous "#pragma option push" supressed them michael@0: # pragma option pop michael@0: #endif michael@0: michael@0: // Tests EXPECT_EQ. michael@0: TEST(ExpectTest, EXPECT_EQ) { michael@0: EXPECT_EQ(5, 2 + 3); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3), michael@0: "Value of: 2*3\n" michael@0: " Actual: 6\n" michael@0: "Expected: 5"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), michael@0: "2 - 3"); michael@0: } michael@0: michael@0: // Tests using EXPECT_EQ on double values. The purpose is to make michael@0: // sure that the specialization we did for integer and anonymous enums michael@0: // isn't used for double arguments. michael@0: TEST(ExpectTest, EXPECT_EQ_Double) { michael@0: // A success. michael@0: EXPECT_EQ(5.6, 5.6); michael@0: michael@0: // A failure. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), michael@0: "5.1"); michael@0: } michael@0: michael@0: #if GTEST_CAN_COMPARE_NULL michael@0: // Tests EXPECT_EQ(NULL, pointer). michael@0: TEST(ExpectTest, EXPECT_EQ_NULL) { michael@0: // A success. michael@0: const char* p = NULL; michael@0: // Some older GCC versions may issue a spurious warning in this or the next michael@0: // assertion statement. This warning should not be suppressed with michael@0: // static_cast since the test verifies the ability to use bare NULL as the michael@0: // expected parameter to the macro. michael@0: EXPECT_EQ(NULL, p); michael@0: michael@0: // A failure. michael@0: int n = 0; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n), michael@0: "Value of: &n\n"); michael@0: } michael@0: #endif // GTEST_CAN_COMPARE_NULL michael@0: michael@0: // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be michael@0: // treated as a null pointer by the compiler, we need to make sure michael@0: // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as michael@0: // EXPECT_EQ(static_cast(NULL), non_pointer). michael@0: TEST(ExpectTest, EXPECT_EQ_0) { michael@0: int n = 0; michael@0: michael@0: // A success. michael@0: EXPECT_EQ(0, n); michael@0: michael@0: // A failure. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), michael@0: "Expected: 0"); michael@0: } michael@0: michael@0: // Tests EXPECT_NE. michael@0: TEST(ExpectTest, EXPECT_NE) { michael@0: EXPECT_NE(6, 7); michael@0: michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'), michael@0: "Expected: ('a') != ('a'), " michael@0: "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), michael@0: "2"); michael@0: char* const p0 = NULL; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), michael@0: "p0"); michael@0: // Only way to get the Nokia compiler to compile the cast michael@0: // is to have a separate void* variable first. Putting michael@0: // the two casts on the same line doesn't work, neither does michael@0: // a direct C-style to char*. michael@0: void* pv1 = (void*)0x1234; // NOLINT michael@0: char* const p1 = reinterpret_cast(pv1); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), michael@0: "p1"); michael@0: } michael@0: michael@0: // Tests EXPECT_LE. michael@0: TEST(ExpectTest, EXPECT_LE) { michael@0: EXPECT_LE(2, 3); michael@0: EXPECT_LE(2, 2); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0), michael@0: "Expected: (2) <= (0), actual: 2 vs 0"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), michael@0: "(1.1) <= (0.9)"); michael@0: } michael@0: michael@0: // Tests EXPECT_LT. michael@0: TEST(ExpectTest, EXPECT_LT) { michael@0: EXPECT_LT(2, 3); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2), michael@0: "Expected: (2) < (2), actual: 2 vs 2"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), michael@0: "(2) < (1)"); michael@0: } michael@0: michael@0: // Tests EXPECT_GE. michael@0: TEST(ExpectTest, EXPECT_GE) { michael@0: EXPECT_GE(2, 1); michael@0: EXPECT_GE(2, 2); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3), michael@0: "Expected: (2) >= (3), actual: 2 vs 3"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), michael@0: "(0.9) >= (1.1)"); michael@0: } michael@0: michael@0: // Tests EXPECT_GT. michael@0: TEST(ExpectTest, EXPECT_GT) { michael@0: EXPECT_GT(2, 1); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2), michael@0: "Expected: (2) > (2), actual: 2 vs 2"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), michael@0: "(2) > (3)"); michael@0: } michael@0: michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: michael@0: // Tests EXPECT_THROW. michael@0: TEST(ExpectTest, EXPECT_THROW) { michael@0: EXPECT_THROW(ThrowAnInteger(), int); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool), michael@0: "Expected: ThrowAnInteger() throws an exception of " michael@0: "type bool.\n Actual: it throws a different type."); michael@0: EXPECT_NONFATAL_FAILURE( michael@0: EXPECT_THROW(ThrowNothing(), bool), michael@0: "Expected: ThrowNothing() throws an exception of type bool.\n" michael@0: " Actual: it throws nothing."); michael@0: } michael@0: michael@0: // Tests EXPECT_NO_THROW. michael@0: TEST(ExpectTest, EXPECT_NO_THROW) { michael@0: EXPECT_NO_THROW(ThrowNothing()); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()), michael@0: "Expected: ThrowAnInteger() doesn't throw an " michael@0: "exception.\n Actual: it throws."); michael@0: } michael@0: michael@0: // Tests EXPECT_ANY_THROW. michael@0: TEST(ExpectTest, EXPECT_ANY_THROW) { michael@0: EXPECT_ANY_THROW(ThrowAnInteger()); michael@0: EXPECT_NONFATAL_FAILURE( michael@0: EXPECT_ANY_THROW(ThrowNothing()), michael@0: "Expected: ThrowNothing() throws an exception.\n" michael@0: " Actual: it doesn't."); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_EXCEPTIONS michael@0: michael@0: // Make sure we deal with the precedence of <<. michael@0: TEST(ExpectTest, ExpectPrecedence) { michael@0: EXPECT_EQ(1 < 2, true); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false), michael@0: "Value of: true && false"); michael@0: } michael@0: michael@0: michael@0: // Tests the StreamableToString() function. michael@0: michael@0: // Tests using StreamableToString() on a scalar. michael@0: TEST(StreamableToStringTest, Scalar) { michael@0: EXPECT_STREQ("5", StreamableToString(5).c_str()); michael@0: } michael@0: michael@0: // Tests using StreamableToString() on a non-char pointer. michael@0: TEST(StreamableToStringTest, Pointer) { michael@0: int n = 0; michael@0: int* p = &n; michael@0: EXPECT_STRNE("(null)", StreamableToString(p).c_str()); michael@0: } michael@0: michael@0: // Tests using StreamableToString() on a NULL non-char pointer. michael@0: TEST(StreamableToStringTest, NullPointer) { michael@0: int* p = NULL; michael@0: EXPECT_STREQ("(null)", StreamableToString(p).c_str()); michael@0: } michael@0: michael@0: // Tests using StreamableToString() on a C string. michael@0: TEST(StreamableToStringTest, CString) { michael@0: EXPECT_STREQ("Foo", StreamableToString("Foo").c_str()); michael@0: } michael@0: michael@0: // Tests using StreamableToString() on a NULL C string. michael@0: TEST(StreamableToStringTest, NullCString) { michael@0: char* p = NULL; michael@0: EXPECT_STREQ("(null)", StreamableToString(p).c_str()); michael@0: } michael@0: michael@0: // Tests using streamable values as assertion messages. michael@0: michael@0: // Tests using std::string as an assertion message. michael@0: TEST(StreamableTest, string) { michael@0: static const std::string str( michael@0: "This failure message is a std::string, and is expected."); michael@0: EXPECT_FATAL_FAILURE(FAIL() << str, michael@0: str.c_str()); michael@0: } michael@0: michael@0: // Tests that we can output strings containing embedded NULs. michael@0: // Limited to Linux because we can only do this with std::string's. michael@0: TEST(StreamableTest, stringWithEmbeddedNUL) { michael@0: static const char char_array_with_nul[] = michael@0: "Here's a NUL\0 and some more string"; michael@0: static const std::string string_with_nul(char_array_with_nul, michael@0: sizeof(char_array_with_nul) michael@0: - 1); // drops the trailing NUL michael@0: EXPECT_FATAL_FAILURE(FAIL() << string_with_nul, michael@0: "Here's a NUL\\0 and some more string"); michael@0: } michael@0: michael@0: // Tests that we can output a NUL char. michael@0: TEST(StreamableTest, NULChar) { michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: FAIL() << "A NUL" << '\0' << " and some more string"; michael@0: }, "A NUL\\0 and some more string"); michael@0: } michael@0: michael@0: // Tests using int as an assertion message. michael@0: TEST(StreamableTest, int) { michael@0: EXPECT_FATAL_FAILURE(FAIL() << 900913, michael@0: "900913"); michael@0: } michael@0: michael@0: // Tests using NULL char pointer as an assertion message. michael@0: // michael@0: // In MSVC, streaming a NULL char * causes access violation. Google Test michael@0: // implemented a workaround (substituting "(null)" for NULL). This michael@0: // tests whether the workaround works. michael@0: TEST(StreamableTest, NullCharPtr) { michael@0: EXPECT_FATAL_FAILURE(FAIL() << static_cast(NULL), michael@0: "(null)"); michael@0: } michael@0: michael@0: // Tests that basic IO manipulators (endl, ends, and flush) can be michael@0: // streamed to testing::Message. michael@0: TEST(StreamableTest, BasicIoManip) { michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: FAIL() << "Line 1." << std::endl michael@0: << "A NUL char " << std::ends << std::flush << " in line 2."; michael@0: }, "Line 1.\nA NUL char \\0 in line 2."); michael@0: } michael@0: michael@0: // Tests the macros that haven't been covered so far. michael@0: michael@0: void AddFailureHelper(bool* aborted) { michael@0: *aborted = true; michael@0: ADD_FAILURE() << "Intentional failure."; michael@0: *aborted = false; michael@0: } michael@0: michael@0: // Tests ADD_FAILURE. michael@0: TEST(MacroTest, ADD_FAILURE) { michael@0: bool aborted = true; michael@0: EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), michael@0: "Intentional failure."); michael@0: EXPECT_FALSE(aborted); michael@0: } michael@0: michael@0: // Tests ADD_FAILURE_AT. michael@0: TEST(MacroTest, ADD_FAILURE_AT) { michael@0: // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and michael@0: // the failure message contains the user-streamed part. michael@0: EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!"); michael@0: michael@0: // Verifies that the user-streamed part is optional. michael@0: EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed"); michael@0: michael@0: // Unfortunately, we cannot verify that the failure message contains michael@0: // the right file path and line number the same way, as michael@0: // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and michael@0: // line number. Instead, we do that in gtest_output_test_.cc. michael@0: } michael@0: michael@0: // Tests FAIL. michael@0: TEST(MacroTest, FAIL) { michael@0: EXPECT_FATAL_FAILURE(FAIL(), michael@0: "Failed"); michael@0: EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.", michael@0: "Intentional failure."); michael@0: } michael@0: michael@0: // Tests SUCCEED michael@0: TEST(MacroTest, SUCCEED) { michael@0: SUCCEED(); michael@0: SUCCEED() << "Explicit success."; michael@0: } michael@0: michael@0: // Tests for EXPECT_EQ() and ASSERT_EQ(). michael@0: // michael@0: // These tests fail *intentionally*, s.t. the failure messages can be michael@0: // generated and tested. michael@0: // michael@0: // We have different tests for different argument types. michael@0: michael@0: // Tests using bool values in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, Bool) { michael@0: EXPECT_EQ(true, true); michael@0: EXPECT_FATAL_FAILURE({ michael@0: bool false_value = false; michael@0: ASSERT_EQ(false_value, true); michael@0: }, "Value of: true"); michael@0: } michael@0: michael@0: // Tests using int values in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, Int) { michael@0: ASSERT_EQ(32, 32); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), michael@0: "33"); michael@0: } michael@0: michael@0: // Tests using time_t values in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, Time_T) { michael@0: EXPECT_EQ(static_cast(0), michael@0: static_cast(0)); michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast(0), michael@0: static_cast(1234)), michael@0: "1234"); michael@0: } michael@0: michael@0: // Tests using char values in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, Char) { michael@0: ASSERT_EQ('z', 'z'); michael@0: const char ch = 'b'; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), michael@0: "ch"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), michael@0: "ch"); michael@0: } michael@0: michael@0: // Tests using wchar_t values in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, WideChar) { michael@0: EXPECT_EQ(L'b', L'b'); michael@0: michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'), michael@0: "Value of: L'x'\n" michael@0: " Actual: L'x' (120, 0x78)\n" michael@0: "Expected: L'\0'\n" michael@0: "Which is: L'\0' (0, 0x0)"); michael@0: michael@0: static wchar_t wchar; michael@0: wchar = L'b'; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), michael@0: "wchar"); michael@0: wchar = 0x8119; michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast(0x8120), wchar), michael@0: "Value of: wchar"); michael@0: } michael@0: michael@0: // Tests using ::std::string values in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, StdString) { michael@0: // Compares a const char* to an std::string that has identical michael@0: // content. michael@0: ASSERT_EQ("Test", ::std::string("Test")); michael@0: michael@0: // Compares two identical std::strings. michael@0: static const ::std::string str1("A * in the middle"); michael@0: static const ::std::string str2(str1); michael@0: EXPECT_EQ(str1, str2); michael@0: michael@0: // Compares a const char* to an std::string that has different michael@0: // content michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), michael@0: "::std::string(\"test\")"); michael@0: michael@0: // Compares an std::string to a char* that has different content. michael@0: char* const p1 = const_cast("foo"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), michael@0: "p1"); michael@0: michael@0: // Compares two std::strings that have different contents, one of michael@0: // which having a NUL character in the middle. This should fail. michael@0: static ::std::string str3(str1); michael@0: str3.at(2) = '\0'; michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3), michael@0: "Value of: str3\n" michael@0: " Actual: \"A \\0 in the middle\""); michael@0: } michael@0: michael@0: #if GTEST_HAS_STD_WSTRING michael@0: michael@0: // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, StdWideString) { michael@0: // Compares two identical std::wstrings. michael@0: const ::std::wstring wstr1(L"A * in the middle"); michael@0: const ::std::wstring wstr2(wstr1); michael@0: ASSERT_EQ(wstr1, wstr2); michael@0: michael@0: // Compares an std::wstring to a const wchar_t* that has identical michael@0: // content. michael@0: const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; michael@0: EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119); michael@0: michael@0: // Compares an std::wstring to a const wchar_t* that has different michael@0: // content. michael@0: const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120); michael@0: }, "kTestX8120"); michael@0: michael@0: // Compares two std::wstrings that have different contents, one of michael@0: // which having a NUL character in the middle. michael@0: ::std::wstring wstr3(wstr1); michael@0: wstr3.at(2) = L'\0'; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), michael@0: "wstr3"); michael@0: michael@0: // Compares a wchar_t* to an std::wstring that has different michael@0: // content. michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_EQ(const_cast(L"foo"), ::std::wstring(L"bar")); michael@0: }, ""); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_STD_WSTRING michael@0: michael@0: #if GTEST_HAS_GLOBAL_STRING michael@0: // Tests using ::string values in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, GlobalString) { michael@0: // Compares a const char* to a ::string that has identical content. michael@0: EXPECT_EQ("Test", ::string("Test")); michael@0: michael@0: // Compares two identical ::strings. michael@0: const ::string str1("A * in the middle"); michael@0: const ::string str2(str1); michael@0: ASSERT_EQ(str1, str2); michael@0: michael@0: // Compares a ::string to a const char* that has different content. michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"), michael@0: "test"); michael@0: michael@0: // Compares two ::strings that have different contents, one of which michael@0: // having a NUL character in the middle. michael@0: ::string str3(str1); michael@0: str3.at(2) = '\0'; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3), michael@0: "str3"); michael@0: michael@0: // Compares a ::string to a char* that has different content. michael@0: EXPECT_FATAL_FAILURE({ // NOLINT michael@0: ASSERT_EQ(::string("bar"), const_cast("foo")); michael@0: }, ""); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_GLOBAL_STRING michael@0: michael@0: #if GTEST_HAS_GLOBAL_WSTRING michael@0: michael@0: // Tests using ::wstring values in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, GlobalWideString) { michael@0: // Compares two identical ::wstrings. michael@0: static const ::wstring wstr1(L"A * in the middle"); michael@0: static const ::wstring wstr2(wstr1); michael@0: EXPECT_EQ(wstr1, wstr2); michael@0: michael@0: // Compares a const wchar_t* to a ::wstring that has identical content. michael@0: const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; michael@0: ASSERT_EQ(kTestX8119, ::wstring(kTestX8119)); michael@0: michael@0: // Compares a const wchar_t* to a ::wstring that has different michael@0: // content. michael@0: const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; michael@0: EXPECT_NONFATAL_FAILURE({ // NOLINT michael@0: EXPECT_EQ(kTestX8120, ::wstring(kTestX8119)); michael@0: }, "Test\\x8119"); michael@0: michael@0: // Compares a wchar_t* to a ::wstring that has different content. michael@0: wchar_t* const p1 = const_cast(L"foo"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")), michael@0: "bar"); michael@0: michael@0: // Compares two ::wstrings that have different contents, one of which michael@0: // having a NUL character in the middle. michael@0: static ::wstring wstr3; michael@0: wstr3 = wstr1; michael@0: wstr3.at(2) = L'\0'; michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3), michael@0: "wstr3"); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_GLOBAL_WSTRING michael@0: michael@0: // Tests using char pointers in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, CharPointer) { michael@0: char* const p0 = NULL; michael@0: // Only way to get the Nokia compiler to compile the cast michael@0: // is to have a separate void* variable first. Putting michael@0: // the two casts on the same line doesn't work, neither does michael@0: // a direct C-style to char*. michael@0: void* pv1 = (void*)0x1234; // NOLINT michael@0: void* pv2 = (void*)0xABC0; // NOLINT michael@0: char* const p1 = reinterpret_cast(pv1); michael@0: char* const p2 = reinterpret_cast(pv2); michael@0: ASSERT_EQ(p1, p1); michael@0: michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), michael@0: "Value of: p2"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), michael@0: "p2"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast(0x1234), michael@0: reinterpret_cast(0xABC0)), michael@0: "ABC0"); michael@0: } michael@0: michael@0: // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, WideCharPointer) { michael@0: wchar_t* const p0 = NULL; michael@0: // Only way to get the Nokia compiler to compile the cast michael@0: // is to have a separate void* variable first. Putting michael@0: // the two casts on the same line doesn't work, neither does michael@0: // a direct C-style to char*. michael@0: void* pv1 = (void*)0x1234; // NOLINT michael@0: void* pv2 = (void*)0xABC0; // NOLINT michael@0: wchar_t* const p1 = reinterpret_cast(pv1); michael@0: wchar_t* const p2 = reinterpret_cast(pv2); michael@0: EXPECT_EQ(p0, p0); michael@0: michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), michael@0: "Value of: p2"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), michael@0: "p2"); michael@0: void* pv3 = (void*)0x1234; // NOLINT michael@0: void* pv4 = (void*)0xABC0; // NOLINT michael@0: const wchar_t* p3 = reinterpret_cast(pv3); michael@0: const wchar_t* p4 = reinterpret_cast(pv4); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), michael@0: "p4"); michael@0: } michael@0: michael@0: // Tests using other types of pointers in {EXPECT|ASSERT}_EQ. michael@0: TEST(EqAssertionTest, OtherPointer) { michael@0: ASSERT_EQ(static_cast(NULL), michael@0: static_cast(NULL)); michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast(NULL), michael@0: reinterpret_cast(0x1234)), michael@0: "0x1234"); michael@0: } michael@0: michael@0: // A class that supports binary comparison operators but not streaming. michael@0: class UnprintableChar { michael@0: public: michael@0: explicit UnprintableChar(char ch) : char_(ch) {} michael@0: michael@0: bool operator==(const UnprintableChar& rhs) const { michael@0: return char_ == rhs.char_; michael@0: } michael@0: bool operator!=(const UnprintableChar& rhs) const { michael@0: return char_ != rhs.char_; michael@0: } michael@0: bool operator<(const UnprintableChar& rhs) const { michael@0: return char_ < rhs.char_; michael@0: } michael@0: bool operator<=(const UnprintableChar& rhs) const { michael@0: return char_ <= rhs.char_; michael@0: } michael@0: bool operator>(const UnprintableChar& rhs) const { michael@0: return char_ > rhs.char_; michael@0: } michael@0: bool operator>=(const UnprintableChar& rhs) const { michael@0: return char_ >= rhs.char_; michael@0: } michael@0: michael@0: private: michael@0: char char_; michael@0: }; michael@0: michael@0: // Tests that ASSERT_EQ() and friends don't require the arguments to michael@0: // be printable. michael@0: TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) { michael@0: const UnprintableChar x('x'), y('y'); michael@0: ASSERT_EQ(x, x); michael@0: EXPECT_NE(x, y); michael@0: ASSERT_LT(x, y); michael@0: EXPECT_LE(x, y); michael@0: ASSERT_GT(y, x); michael@0: EXPECT_GE(x, x); michael@0: michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>"); michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>"); michael@0: michael@0: // Code tested by EXPECT_FATAL_FAILURE cannot reference local michael@0: // variables, so we have to write UnprintableChar('x') instead of x. michael@0: #ifndef __BORLANDC__ michael@0: // ICE's in C++Builder. michael@0: EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')), michael@0: "1-byte object <78>"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), michael@0: "1-byte object <78>"); michael@0: #endif michael@0: EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), michael@0: "1-byte object <79>"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), michael@0: "1-byte object <78>"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), michael@0: "1-byte object <79>"); michael@0: } michael@0: michael@0: // Tests the FRIEND_TEST macro. michael@0: michael@0: // This class has a private member we want to test. We will test it michael@0: // both in a TEST and in a TEST_F. michael@0: class Foo { michael@0: public: michael@0: Foo() {} michael@0: michael@0: private: michael@0: int Bar() const { return 1; } michael@0: michael@0: // Declares the friend tests that can access the private member michael@0: // Bar(). michael@0: FRIEND_TEST(FRIEND_TEST_Test, TEST); michael@0: FRIEND_TEST(FRIEND_TEST_Test2, TEST_F); michael@0: }; michael@0: michael@0: // Tests that the FRIEND_TEST declaration allows a TEST to access a michael@0: // class's private members. This should compile. michael@0: TEST(FRIEND_TEST_Test, TEST) { michael@0: ASSERT_EQ(1, Foo().Bar()); michael@0: } michael@0: michael@0: // The fixture needed to test using FRIEND_TEST with TEST_F. michael@0: class FRIEND_TEST_Test2 : public Test { michael@0: protected: michael@0: Foo foo; michael@0: }; michael@0: michael@0: // Tests that the FRIEND_TEST declaration allows a TEST_F to access a michael@0: // class's private members. This should compile. michael@0: TEST_F(FRIEND_TEST_Test2, TEST_F) { michael@0: ASSERT_EQ(1, foo.Bar()); michael@0: } michael@0: michael@0: // Tests the life cycle of Test objects. michael@0: michael@0: // The test fixture for testing the life cycle of Test objects. michael@0: // michael@0: // This class counts the number of live test objects that uses this michael@0: // fixture. michael@0: class TestLifeCycleTest : public Test { michael@0: protected: michael@0: // Constructor. Increments the number of test objects that uses michael@0: // this fixture. michael@0: TestLifeCycleTest() { count_++; } michael@0: michael@0: // Destructor. Decrements the number of test objects that uses this michael@0: // fixture. michael@0: ~TestLifeCycleTest() { count_--; } michael@0: michael@0: // Returns the number of live test objects that uses this fixture. michael@0: int count() const { return count_; } michael@0: michael@0: private: michael@0: static int count_; michael@0: }; michael@0: michael@0: int TestLifeCycleTest::count_ = 0; michael@0: michael@0: // Tests the life cycle of test objects. michael@0: TEST_F(TestLifeCycleTest, Test1) { michael@0: // There should be only one test object in this test case that's michael@0: // currently alive. michael@0: ASSERT_EQ(1, count()); michael@0: } michael@0: michael@0: // Tests the life cycle of test objects. michael@0: TEST_F(TestLifeCycleTest, Test2) { michael@0: // After Test1 is done and Test2 is started, there should still be michael@0: // only one live test object, as the object for Test1 should've been michael@0: // deleted. michael@0: ASSERT_EQ(1, count()); michael@0: } michael@0: michael@0: } // namespace michael@0: michael@0: // Tests that the copy constructor works when it is NOT optimized away by michael@0: // the compiler. michael@0: TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) { michael@0: // Checks that the copy constructor doesn't try to dereference NULL pointers michael@0: // in the source object. michael@0: AssertionResult r1 = AssertionSuccess(); michael@0: AssertionResult r2 = r1; michael@0: // The following line is added to prevent the compiler from optimizing michael@0: // away the constructor call. michael@0: r1 << "abc"; michael@0: michael@0: AssertionResult r3 = r1; michael@0: EXPECT_EQ(static_cast(r3), static_cast(r1)); michael@0: EXPECT_STREQ("abc", r1.message()); michael@0: } michael@0: michael@0: // Tests that AssertionSuccess and AssertionFailure construct michael@0: // AssertionResult objects as expected. michael@0: TEST(AssertionResultTest, ConstructionWorks) { michael@0: AssertionResult r1 = AssertionSuccess(); michael@0: EXPECT_TRUE(r1); michael@0: EXPECT_STREQ("", r1.message()); michael@0: michael@0: AssertionResult r2 = AssertionSuccess() << "abc"; michael@0: EXPECT_TRUE(r2); michael@0: EXPECT_STREQ("abc", r2.message()); michael@0: michael@0: AssertionResult r3 = AssertionFailure(); michael@0: EXPECT_FALSE(r3); michael@0: EXPECT_STREQ("", r3.message()); michael@0: michael@0: AssertionResult r4 = AssertionFailure() << "def"; michael@0: EXPECT_FALSE(r4); michael@0: EXPECT_STREQ("def", r4.message()); michael@0: michael@0: AssertionResult r5 = AssertionFailure(Message() << "ghi"); michael@0: EXPECT_FALSE(r5); michael@0: EXPECT_STREQ("ghi", r5.message()); michael@0: } michael@0: michael@0: // Tests that the negation flips the predicate result but keeps the message. michael@0: TEST(AssertionResultTest, NegationWorks) { michael@0: AssertionResult r1 = AssertionSuccess() << "abc"; michael@0: EXPECT_FALSE(!r1); michael@0: EXPECT_STREQ("abc", (!r1).message()); michael@0: michael@0: AssertionResult r2 = AssertionFailure() << "def"; michael@0: EXPECT_TRUE(!r2); michael@0: EXPECT_STREQ("def", (!r2).message()); michael@0: } michael@0: michael@0: TEST(AssertionResultTest, StreamingWorks) { michael@0: AssertionResult r = AssertionSuccess(); michael@0: r << "abc" << 'd' << 0 << true; michael@0: EXPECT_STREQ("abcd0true", r.message()); michael@0: } michael@0: michael@0: TEST(AssertionResultTest, CanStreamOstreamManipulators) { michael@0: AssertionResult r = AssertionSuccess(); michael@0: r << "Data" << std::endl << std::flush << std::ends << "Will be visible"; michael@0: EXPECT_STREQ("Data\n\\0Will be visible", r.message()); michael@0: } michael@0: michael@0: // Tests streaming a user type whose definition and operator << are michael@0: // both in the global namespace. michael@0: class Base { michael@0: public: michael@0: explicit Base(int an_x) : x_(an_x) {} michael@0: int x() const { return x_; } michael@0: private: michael@0: int x_; michael@0: }; michael@0: std::ostream& operator<<(std::ostream& os, michael@0: const Base& val) { michael@0: return os << val.x(); michael@0: } michael@0: std::ostream& operator<<(std::ostream& os, michael@0: const Base* pointer) { michael@0: return os << "(" << pointer->x() << ")"; michael@0: } michael@0: michael@0: TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) { michael@0: Message msg; michael@0: Base a(1); michael@0: michael@0: msg << a << &a; // Uses ::operator<<. michael@0: EXPECT_STREQ("1(1)", msg.GetString().c_str()); michael@0: } michael@0: michael@0: // Tests streaming a user type whose definition and operator<< are michael@0: // both in an unnamed namespace. michael@0: namespace { michael@0: class MyTypeInUnnamedNameSpace : public Base { michael@0: public: michael@0: explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {} michael@0: }; michael@0: std::ostream& operator<<(std::ostream& os, michael@0: const MyTypeInUnnamedNameSpace& val) { michael@0: return os << val.x(); michael@0: } michael@0: std::ostream& operator<<(std::ostream& os, michael@0: const MyTypeInUnnamedNameSpace* pointer) { michael@0: return os << "(" << pointer->x() << ")"; michael@0: } michael@0: } // namespace michael@0: michael@0: TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) { michael@0: Message msg; michael@0: MyTypeInUnnamedNameSpace a(1); michael@0: michael@0: msg << a << &a; // Uses ::operator<<. michael@0: EXPECT_STREQ("1(1)", msg.GetString().c_str()); michael@0: } michael@0: michael@0: // Tests streaming a user type whose definition and operator<< are michael@0: // both in a user namespace. michael@0: namespace namespace1 { michael@0: class MyTypeInNameSpace1 : public Base { michael@0: public: michael@0: explicit MyTypeInNameSpace1(int an_x): Base(an_x) {} michael@0: }; michael@0: std::ostream& operator<<(std::ostream& os, michael@0: const MyTypeInNameSpace1& val) { michael@0: return os << val.x(); michael@0: } michael@0: std::ostream& operator<<(std::ostream& os, michael@0: const MyTypeInNameSpace1* pointer) { michael@0: return os << "(" << pointer->x() << ")"; michael@0: } michael@0: } // namespace namespace1 michael@0: michael@0: TEST(MessageTest, CanStreamUserTypeInUserNameSpace) { michael@0: Message msg; michael@0: namespace1::MyTypeInNameSpace1 a(1); michael@0: michael@0: msg << a << &a; // Uses namespace1::operator<<. michael@0: EXPECT_STREQ("1(1)", msg.GetString().c_str()); michael@0: } michael@0: michael@0: // Tests streaming a user type whose definition is in a user namespace michael@0: // but whose operator<< is in the global namespace. michael@0: namespace namespace2 { michael@0: class MyTypeInNameSpace2 : public ::Base { michael@0: public: michael@0: explicit MyTypeInNameSpace2(int an_x): Base(an_x) {} michael@0: }; michael@0: } // namespace namespace2 michael@0: std::ostream& operator<<(std::ostream& os, michael@0: const namespace2::MyTypeInNameSpace2& val) { michael@0: return os << val.x(); michael@0: } michael@0: std::ostream& operator<<(std::ostream& os, michael@0: const namespace2::MyTypeInNameSpace2* pointer) { michael@0: return os << "(" << pointer->x() << ")"; michael@0: } michael@0: michael@0: TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) { michael@0: Message msg; michael@0: namespace2::MyTypeInNameSpace2 a(1); michael@0: michael@0: msg << a << &a; // Uses ::operator<<. michael@0: EXPECT_STREQ("1(1)", msg.GetString().c_str()); michael@0: } michael@0: michael@0: // Tests streaming NULL pointers to testing::Message. michael@0: TEST(MessageTest, NullPointers) { michael@0: Message msg; michael@0: char* const p1 = NULL; michael@0: unsigned char* const p2 = NULL; michael@0: int* p3 = NULL; michael@0: double* p4 = NULL; michael@0: bool* p5 = NULL; michael@0: Message* p6 = NULL; michael@0: michael@0: msg << p1 << p2 << p3 << p4 << p5 << p6; michael@0: ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", michael@0: msg.GetString().c_str()); michael@0: } michael@0: michael@0: // Tests streaming wide strings to testing::Message. michael@0: TEST(MessageTest, WideStrings) { michael@0: // Streams a NULL of type const wchar_t*. michael@0: const wchar_t* const_wstr = NULL; michael@0: EXPECT_STREQ("(null)", michael@0: (Message() << const_wstr).GetString().c_str()); michael@0: michael@0: // Streams a NULL of type wchar_t*. michael@0: wchar_t* wstr = NULL; michael@0: EXPECT_STREQ("(null)", michael@0: (Message() << wstr).GetString().c_str()); michael@0: michael@0: // Streams a non-NULL of type const wchar_t*. michael@0: const_wstr = L"abc\x8119"; michael@0: EXPECT_STREQ("abc\xe8\x84\x99", michael@0: (Message() << const_wstr).GetString().c_str()); michael@0: michael@0: // Streams a non-NULL of type wchar_t*. michael@0: wstr = const_cast(const_wstr); michael@0: EXPECT_STREQ("abc\xe8\x84\x99", michael@0: (Message() << wstr).GetString().c_str()); michael@0: } michael@0: michael@0: michael@0: // This line tests that we can define tests in the testing namespace. michael@0: namespace testing { michael@0: michael@0: // Tests the TestInfo class. michael@0: michael@0: class TestInfoTest : public Test { michael@0: protected: michael@0: static const TestInfo* GetTestInfo(const char* test_name) { michael@0: const TestCase* const test_case = GetUnitTestImpl()-> michael@0: GetTestCase("TestInfoTest", "", NULL, NULL); michael@0: michael@0: for (int i = 0; i < test_case->total_test_count(); ++i) { michael@0: const TestInfo* const test_info = test_case->GetTestInfo(i); michael@0: if (strcmp(test_name, test_info->name()) == 0) michael@0: return test_info; michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: static const TestResult* GetTestResult( michael@0: const TestInfo* test_info) { michael@0: return test_info->result(); michael@0: } michael@0: }; michael@0: michael@0: // Tests TestInfo::test_case_name() and TestInfo::name(). michael@0: TEST_F(TestInfoTest, Names) { michael@0: const TestInfo* const test_info = GetTestInfo("Names"); michael@0: michael@0: ASSERT_STREQ("TestInfoTest", test_info->test_case_name()); michael@0: ASSERT_STREQ("Names", test_info->name()); michael@0: } michael@0: michael@0: // Tests TestInfo::result(). michael@0: TEST_F(TestInfoTest, result) { michael@0: const TestInfo* const test_info = GetTestInfo("result"); michael@0: michael@0: // Initially, there is no TestPartResult for this test. michael@0: ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); michael@0: michael@0: // After the previous assertion, there is still none. michael@0: ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); michael@0: } michael@0: michael@0: // Tests setting up and tearing down a test case. michael@0: michael@0: class SetUpTestCaseTest : public Test { michael@0: protected: michael@0: // This will be called once before the first test in this test case michael@0: // is run. michael@0: static void SetUpTestCase() { michael@0: printf("Setting up the test case . . .\n"); michael@0: michael@0: // Initializes some shared resource. In this simple example, we michael@0: // just create a C string. More complex stuff can be done if michael@0: // desired. michael@0: shared_resource_ = "123"; michael@0: michael@0: // Increments the number of test cases that have been set up. michael@0: counter_++; michael@0: michael@0: // SetUpTestCase() should be called only once. michael@0: EXPECT_EQ(1, counter_); michael@0: } michael@0: michael@0: // This will be called once after the last test in this test case is michael@0: // run. michael@0: static void TearDownTestCase() { michael@0: printf("Tearing down the test case . . .\n"); michael@0: michael@0: // Decrements the number of test cases that have been set up. michael@0: counter_--; michael@0: michael@0: // TearDownTestCase() should be called only once. michael@0: EXPECT_EQ(0, counter_); michael@0: michael@0: // Cleans up the shared resource. michael@0: shared_resource_ = NULL; michael@0: } michael@0: michael@0: // This will be called before each test in this test case. michael@0: virtual void SetUp() { michael@0: // SetUpTestCase() should be called only once, so counter_ should michael@0: // always be 1. michael@0: EXPECT_EQ(1, counter_); michael@0: } michael@0: michael@0: // Number of test cases that have been set up. michael@0: static int counter_; michael@0: michael@0: // Some resource to be shared by all tests in this test case. michael@0: static const char* shared_resource_; michael@0: }; michael@0: michael@0: int SetUpTestCaseTest::counter_ = 0; michael@0: const char* SetUpTestCaseTest::shared_resource_ = NULL; michael@0: michael@0: // A test that uses the shared resource. michael@0: TEST_F(SetUpTestCaseTest, Test1) { michael@0: EXPECT_STRNE(NULL, shared_resource_); michael@0: } michael@0: michael@0: // Another test that uses the shared resource. michael@0: TEST_F(SetUpTestCaseTest, Test2) { michael@0: EXPECT_STREQ("123", shared_resource_); michael@0: } michael@0: michael@0: // The InitGoogleTestTest test case tests testing::InitGoogleTest(). michael@0: michael@0: // The Flags struct stores a copy of all Google Test flags. michael@0: struct Flags { michael@0: // Constructs a Flags struct where each flag has its default value. michael@0: Flags() : also_run_disabled_tests(false), michael@0: break_on_failure(false), michael@0: catch_exceptions(false), michael@0: death_test_use_fork(false), michael@0: filter(""), michael@0: list_tests(false), michael@0: output(""), michael@0: print_time(true), michael@0: random_seed(0), michael@0: repeat(1), michael@0: shuffle(false), michael@0: stack_trace_depth(kMaxStackTraceDepth), michael@0: stream_result_to(""), michael@0: throw_on_failure(false) {} michael@0: michael@0: // Factory methods. michael@0: michael@0: // Creates a Flags struct where the gtest_also_run_disabled_tests flag has michael@0: // the given value. michael@0: static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) { michael@0: Flags flags; michael@0: flags.also_run_disabled_tests = also_run_disabled_tests; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_break_on_failure flag has michael@0: // the given value. michael@0: static Flags BreakOnFailure(bool break_on_failure) { michael@0: Flags flags; michael@0: flags.break_on_failure = break_on_failure; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_catch_exceptions flag has michael@0: // the given value. michael@0: static Flags CatchExceptions(bool catch_exceptions) { michael@0: Flags flags; michael@0: flags.catch_exceptions = catch_exceptions; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_death_test_use_fork flag has michael@0: // the given value. michael@0: static Flags DeathTestUseFork(bool death_test_use_fork) { michael@0: Flags flags; michael@0: flags.death_test_use_fork = death_test_use_fork; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_filter flag has the given michael@0: // value. michael@0: static Flags Filter(const char* filter) { michael@0: Flags flags; michael@0: flags.filter = filter; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_list_tests flag has the michael@0: // given value. michael@0: static Flags ListTests(bool list_tests) { michael@0: Flags flags; michael@0: flags.list_tests = list_tests; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_output flag has the given michael@0: // value. michael@0: static Flags Output(const char* output) { michael@0: Flags flags; michael@0: flags.output = output; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_print_time flag has the given michael@0: // value. michael@0: static Flags PrintTime(bool print_time) { michael@0: Flags flags; michael@0: flags.print_time = print_time; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_random_seed flag has michael@0: // the given value. michael@0: static Flags RandomSeed(Int32 random_seed) { michael@0: Flags flags; michael@0: flags.random_seed = random_seed; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_repeat flag has the given michael@0: // value. michael@0: static Flags Repeat(Int32 repeat) { michael@0: Flags flags; michael@0: flags.repeat = repeat; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_shuffle flag has michael@0: // the given value. michael@0: static Flags Shuffle(bool shuffle) { michael@0: Flags flags; michael@0: flags.shuffle = shuffle; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has michael@0: // the given value. michael@0: static Flags StackTraceDepth(Int32 stack_trace_depth) { michael@0: Flags flags; michael@0: flags.stack_trace_depth = stack_trace_depth; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has michael@0: // the given value. michael@0: static Flags StreamResultTo(const char* stream_result_to) { michael@0: Flags flags; michael@0: flags.stream_result_to = stream_result_to; michael@0: return flags; michael@0: } michael@0: michael@0: // Creates a Flags struct where the gtest_throw_on_failure flag has michael@0: // the given value. michael@0: static Flags ThrowOnFailure(bool throw_on_failure) { michael@0: Flags flags; michael@0: flags.throw_on_failure = throw_on_failure; michael@0: return flags; michael@0: } michael@0: michael@0: // These fields store the flag values. michael@0: bool also_run_disabled_tests; michael@0: bool break_on_failure; michael@0: bool catch_exceptions; michael@0: bool death_test_use_fork; michael@0: const char* filter; michael@0: bool list_tests; michael@0: const char* output; michael@0: bool print_time; michael@0: Int32 random_seed; michael@0: Int32 repeat; michael@0: bool shuffle; michael@0: Int32 stack_trace_depth; michael@0: const char* stream_result_to; michael@0: bool throw_on_failure; michael@0: }; michael@0: michael@0: // Fixture for testing InitGoogleTest(). michael@0: class InitGoogleTestTest : public Test { michael@0: protected: michael@0: // Clears the flags before each test. michael@0: virtual void SetUp() { michael@0: GTEST_FLAG(also_run_disabled_tests) = false; michael@0: GTEST_FLAG(break_on_failure) = false; michael@0: GTEST_FLAG(catch_exceptions) = false; michael@0: GTEST_FLAG(death_test_use_fork) = false; michael@0: GTEST_FLAG(filter) = ""; michael@0: GTEST_FLAG(list_tests) = false; michael@0: GTEST_FLAG(output) = ""; michael@0: GTEST_FLAG(print_time) = true; michael@0: GTEST_FLAG(random_seed) = 0; michael@0: GTEST_FLAG(repeat) = 1; michael@0: GTEST_FLAG(shuffle) = false; michael@0: GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; michael@0: GTEST_FLAG(stream_result_to) = ""; michael@0: GTEST_FLAG(throw_on_failure) = false; michael@0: } michael@0: michael@0: // Asserts that two narrow or wide string arrays are equal. michael@0: template michael@0: static void AssertStringArrayEq(size_t size1, CharType** array1, michael@0: size_t size2, CharType** array2) { michael@0: ASSERT_EQ(size1, size2) << " Array sizes different."; michael@0: michael@0: for (size_t i = 0; i != size1; i++) { michael@0: ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i; michael@0: } michael@0: } michael@0: michael@0: // Verifies that the flag values match the expected values. michael@0: static void CheckFlags(const Flags& expected) { michael@0: EXPECT_EQ(expected.also_run_disabled_tests, michael@0: GTEST_FLAG(also_run_disabled_tests)); michael@0: EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure)); michael@0: EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions)); michael@0: EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork)); michael@0: EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str()); michael@0: EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests)); michael@0: EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str()); michael@0: EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time)); michael@0: EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed)); michael@0: EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat)); michael@0: EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle)); michael@0: EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth)); michael@0: EXPECT_STREQ(expected.stream_result_to, michael@0: GTEST_FLAG(stream_result_to).c_str()); michael@0: EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure)); michael@0: } michael@0: michael@0: // Parses a command line (specified by argc1 and argv1), then michael@0: // verifies that the flag values are expected and that the michael@0: // recognized flags are removed from the command line. michael@0: template michael@0: static void TestParsingFlags(int argc1, const CharType** argv1, michael@0: int argc2, const CharType** argv2, michael@0: const Flags& expected, bool should_print_help) { michael@0: const bool saved_help_flag = ::testing::internal::g_help_flag; michael@0: ::testing::internal::g_help_flag = false; michael@0: michael@0: #if GTEST_HAS_STREAM_REDIRECTION michael@0: CaptureStdout(); michael@0: #endif michael@0: michael@0: // Parses the command line. michael@0: internal::ParseGoogleTestFlagsOnly(&argc1, const_cast(argv1)); michael@0: michael@0: #if GTEST_HAS_STREAM_REDIRECTION michael@0: const String captured_stdout = GetCapturedStdout(); michael@0: #endif michael@0: michael@0: // Verifies the flag values. michael@0: CheckFlags(expected); michael@0: michael@0: // Verifies that the recognized flags are removed from the command michael@0: // line. michael@0: AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2); michael@0: michael@0: // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the michael@0: // help message for the flags it recognizes. michael@0: EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag); michael@0: michael@0: #if GTEST_HAS_STREAM_REDIRECTION michael@0: const char* const expected_help_fragment = michael@0: "This program contains tests written using"; michael@0: if (should_print_help) { michael@0: EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout); michael@0: } else { michael@0: EXPECT_PRED_FORMAT2(IsNotSubstring, michael@0: expected_help_fragment, captured_stdout); michael@0: } michael@0: #endif // GTEST_HAS_STREAM_REDIRECTION michael@0: michael@0: ::testing::internal::g_help_flag = saved_help_flag; michael@0: } michael@0: michael@0: // This macro wraps TestParsingFlags s.t. the user doesn't need michael@0: // to specify the array sizes. michael@0: michael@0: #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ michael@0: TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \ michael@0: sizeof(argv2)/sizeof(*argv2) - 1, argv2, \ michael@0: expected, should_print_help) michael@0: }; michael@0: michael@0: // Tests parsing an empty command line. michael@0: TEST_F(InitGoogleTestTest, Empty) { michael@0: const char* argv[] = { michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); michael@0: } michael@0: michael@0: // Tests parsing a command line that has no flag. michael@0: TEST_F(InitGoogleTestTest, NoFlag) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); michael@0: } michael@0: michael@0: // Tests parsing a bad --gtest_filter flag. michael@0: TEST_F(InitGoogleTestTest, FilterBad) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_filter", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: "--gtest_filter", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true); michael@0: } michael@0: michael@0: // Tests parsing an empty --gtest_filter flag. michael@0: TEST_F(InitGoogleTestTest, FilterEmpty) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_filter=", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false); michael@0: } michael@0: michael@0: // Tests parsing a non-empty --gtest_filter flag. michael@0: TEST_F(InitGoogleTestTest, FilterNonEmpty) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_filter=abc", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_break_on_failure. michael@0: TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_break_on_failure", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_break_on_failure=0. michael@0: TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_break_on_failure=0", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_break_on_failure=f. michael@0: TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_break_on_failure=f", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_break_on_failure=F. michael@0: TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_break_on_failure=F", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); michael@0: } michael@0: michael@0: // Tests parsing a --gtest_break_on_failure flag that has a "true" michael@0: // definition. michael@0: TEST_F(InitGoogleTestTest, BreakOnFailureTrue) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_break_on_failure=1", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_catch_exceptions. michael@0: TEST_F(InitGoogleTestTest, CatchExceptions) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_catch_exceptions", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_death_test_use_fork. michael@0: TEST_F(InitGoogleTestTest, DeathTestUseFork) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_death_test_use_fork", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false); michael@0: } michael@0: michael@0: // Tests having the same flag twice with different values. The michael@0: // expected behavior is that the one coming last takes precedence. michael@0: TEST_F(InitGoogleTestTest, DuplicatedFlags) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_filter=a", michael@0: "--gtest_filter=b", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false); michael@0: } michael@0: michael@0: // Tests having an unrecognized flag on the command line. michael@0: TEST_F(InitGoogleTestTest, UnrecognizedFlag) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_break_on_failure", michael@0: "bar", // Unrecognized by Google Test. michael@0: "--gtest_filter=b", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: "bar", michael@0: NULL michael@0: }; michael@0: michael@0: Flags flags; michael@0: flags.break_on_failure = true; michael@0: flags.filter = "b"; michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false); michael@0: } michael@0: michael@0: // Tests having a --gtest_list_tests flag michael@0: TEST_F(InitGoogleTestTest, ListTestsFlag) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_list_tests", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); michael@0: } michael@0: michael@0: // Tests having a --gtest_list_tests flag with a "true" value michael@0: TEST_F(InitGoogleTestTest, ListTestsTrue) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_list_tests=1", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); michael@0: } michael@0: michael@0: // Tests having a --gtest_list_tests flag with a "false" value michael@0: TEST_F(InitGoogleTestTest, ListTestsFalse) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_list_tests=0", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_list_tests=f. michael@0: TEST_F(InitGoogleTestTest, ListTestsFalse_f) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_list_tests=f", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_list_tests=F. michael@0: TEST_F(InitGoogleTestTest, ListTestsFalse_F) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_list_tests=F", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_output (invalid). michael@0: TEST_F(InitGoogleTestTest, OutputEmpty) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_output", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: "--gtest_output", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true); michael@0: } michael@0: michael@0: // Tests parsing --gtest_output=xml michael@0: TEST_F(InitGoogleTestTest, OutputXml) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_output=xml", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_output=xml:file michael@0: TEST_F(InitGoogleTestTest, OutputXmlFile) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_output=xml:file", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_output=xml:directory/path/ michael@0: TEST_F(InitGoogleTestTest, OutputXmlDirectory) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_output=xml:directory/path/", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, michael@0: Flags::Output("xml:directory/path/"), false); michael@0: } michael@0: michael@0: // Tests having a --gtest_print_time flag michael@0: TEST_F(InitGoogleTestTest, PrintTimeFlag) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_print_time", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); michael@0: } michael@0: michael@0: // Tests having a --gtest_print_time flag with a "true" value michael@0: TEST_F(InitGoogleTestTest, PrintTimeTrue) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_print_time=1", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); michael@0: } michael@0: michael@0: // Tests having a --gtest_print_time flag with a "false" value michael@0: TEST_F(InitGoogleTestTest, PrintTimeFalse) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_print_time=0", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_print_time=f. michael@0: TEST_F(InitGoogleTestTest, PrintTimeFalse_f) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_print_time=f", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_print_time=F. michael@0: TEST_F(InitGoogleTestTest, PrintTimeFalse_F) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_print_time=F", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_random_seed=number michael@0: TEST_F(InitGoogleTestTest, RandomSeed) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_random_seed=1000", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_repeat=number michael@0: TEST_F(InitGoogleTestTest, Repeat) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_repeat=1000", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false); michael@0: } michael@0: michael@0: // Tests having a --gtest_also_run_disabled_tests flag michael@0: TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_also_run_disabled_tests", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, michael@0: Flags::AlsoRunDisabledTests(true), false); michael@0: } michael@0: michael@0: // Tests having a --gtest_also_run_disabled_tests flag with a "true" value michael@0: TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_also_run_disabled_tests=1", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, michael@0: Flags::AlsoRunDisabledTests(true), false); michael@0: } michael@0: michael@0: // Tests having a --gtest_also_run_disabled_tests flag with a "false" value michael@0: TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_also_run_disabled_tests=0", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, michael@0: Flags::AlsoRunDisabledTests(false), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_shuffle. michael@0: TEST_F(InitGoogleTestTest, ShuffleWithoutValue) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_shuffle", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_shuffle=0. michael@0: TEST_F(InitGoogleTestTest, ShuffleFalse_0) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_shuffle=0", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false); michael@0: } michael@0: michael@0: // Tests parsing a --gtest_shuffle flag that has a "true" michael@0: // definition. michael@0: TEST_F(InitGoogleTestTest, ShuffleTrue) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_shuffle=1", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_stack_trace_depth=number. michael@0: TEST_F(InitGoogleTestTest, StackTraceDepth) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_stack_trace_depth=5", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false); michael@0: } michael@0: michael@0: TEST_F(InitGoogleTestTest, StreamResultTo) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_stream_result_to=localhost:1234", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_( michael@0: argv, argv2, Flags::StreamResultTo("localhost:1234"), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_throw_on_failure. michael@0: TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_throw_on_failure", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); michael@0: } michael@0: michael@0: // Tests parsing --gtest_throw_on_failure=0. michael@0: TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_throw_on_failure=0", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false); michael@0: } michael@0: michael@0: // Tests parsing a --gtest_throw_on_failure flag that has a "true" michael@0: // definition. michael@0: TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) { michael@0: const char* argv[] = { michael@0: "foo.exe", michael@0: "--gtest_throw_on_failure=1", michael@0: NULL michael@0: }; michael@0: michael@0: const char* argv2[] = { michael@0: "foo.exe", michael@0: NULL michael@0: }; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); michael@0: } michael@0: michael@0: #if GTEST_OS_WINDOWS michael@0: // Tests parsing wide strings. michael@0: TEST_F(InitGoogleTestTest, WideStrings) { michael@0: const wchar_t* argv[] = { michael@0: L"foo.exe", michael@0: L"--gtest_filter=Foo*", michael@0: L"--gtest_list_tests=1", michael@0: L"--gtest_break_on_failure", michael@0: L"--non_gtest_flag", michael@0: NULL michael@0: }; michael@0: michael@0: const wchar_t* argv2[] = { michael@0: L"foo.exe", michael@0: L"--non_gtest_flag", michael@0: NULL michael@0: }; michael@0: michael@0: Flags expected_flags; michael@0: expected_flags.break_on_failure = true; michael@0: expected_flags.filter = "Foo*"; michael@0: expected_flags.list_tests = true; michael@0: michael@0: GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); michael@0: } michael@0: #endif // GTEST_OS_WINDOWS michael@0: michael@0: // Tests current_test_info() in UnitTest. michael@0: class CurrentTestInfoTest : public Test { michael@0: protected: michael@0: // Tests that current_test_info() returns NULL before the first test in michael@0: // the test case is run. michael@0: static void SetUpTestCase() { michael@0: // There should be no tests running at this point. michael@0: const TestInfo* test_info = michael@0: UnitTest::GetInstance()->current_test_info(); michael@0: EXPECT_TRUE(test_info == NULL) michael@0: << "There should be no tests running at this point."; michael@0: } michael@0: michael@0: // Tests that current_test_info() returns NULL after the last test in michael@0: // the test case has run. michael@0: static void TearDownTestCase() { michael@0: const TestInfo* test_info = michael@0: UnitTest::GetInstance()->current_test_info(); michael@0: EXPECT_TRUE(test_info == NULL) michael@0: << "There should be no tests running at this point."; michael@0: } michael@0: }; michael@0: michael@0: // Tests that current_test_info() returns TestInfo for currently running michael@0: // test by checking the expected test name against the actual one. michael@0: TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) { michael@0: const TestInfo* test_info = michael@0: UnitTest::GetInstance()->current_test_info(); michael@0: ASSERT_TRUE(NULL != test_info) michael@0: << "There is a test running so we should have a valid TestInfo."; michael@0: EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) michael@0: << "Expected the name of the currently running test case."; michael@0: EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name()) michael@0: << "Expected the name of the currently running test."; michael@0: } michael@0: michael@0: // Tests that current_test_info() returns TestInfo for currently running michael@0: // test by checking the expected test name against the actual one. We michael@0: // use this test to see that the TestInfo object actually changed from michael@0: // the previous invocation. michael@0: TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) { michael@0: const TestInfo* test_info = michael@0: UnitTest::GetInstance()->current_test_info(); michael@0: ASSERT_TRUE(NULL != test_info) michael@0: << "There is a test running so we should have a valid TestInfo."; michael@0: EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) michael@0: << "Expected the name of the currently running test case."; michael@0: EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name()) michael@0: << "Expected the name of the currently running test."; michael@0: } michael@0: michael@0: } // namespace testing michael@0: michael@0: // These two lines test that we can define tests in a namespace that michael@0: // has the name "testing" and is nested in another namespace. michael@0: namespace my_namespace { michael@0: namespace testing { michael@0: michael@0: // Makes sure that TEST knows to use ::testing::Test instead of michael@0: // ::my_namespace::testing::Test. michael@0: class Test {}; michael@0: michael@0: // Makes sure that an assertion knows to use ::testing::Message instead of michael@0: // ::my_namespace::testing::Message. michael@0: class Message {}; michael@0: michael@0: // Makes sure that an assertion knows to use michael@0: // ::testing::AssertionResult instead of michael@0: // ::my_namespace::testing::AssertionResult. michael@0: class AssertionResult {}; michael@0: michael@0: // Tests that an assertion that should succeed works as expected. michael@0: TEST(NestedTestingNamespaceTest, Success) { michael@0: EXPECT_EQ(1, 1) << "This shouldn't fail."; michael@0: } michael@0: michael@0: // Tests that an assertion that should fail works as expected. michael@0: TEST(NestedTestingNamespaceTest, Failure) { michael@0: EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.", michael@0: "This failure is expected."); michael@0: } michael@0: michael@0: } // namespace testing michael@0: } // namespace my_namespace michael@0: michael@0: // Tests that one can call superclass SetUp and TearDown methods-- michael@0: // that is, that they are not private. michael@0: // No tests are based on this fixture; the test "passes" if it compiles michael@0: // successfully. michael@0: class ProtectedFixtureMethodsTest : public Test { michael@0: protected: michael@0: virtual void SetUp() { michael@0: Test::SetUp(); michael@0: } michael@0: virtual void TearDown() { michael@0: Test::TearDown(); michael@0: } michael@0: }; michael@0: michael@0: // StreamingAssertionsTest tests the streaming versions of a representative michael@0: // sample of assertions. michael@0: TEST(StreamingAssertionsTest, Unconditional) { michael@0: SUCCEED() << "expected success"; michael@0: EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(FAIL() << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: #ifdef __BORLANDC__ michael@0: // Silences warnings: "Condition is always true", "Unreachable code" michael@0: # pragma option push -w-ccc -w-rch michael@0: #endif michael@0: michael@0: TEST(StreamingAssertionsTest, Truth) { michael@0: EXPECT_TRUE(true) << "unexpected failure"; michael@0: ASSERT_TRUE(true) << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: TEST(StreamingAssertionsTest, Truth2) { michael@0: EXPECT_FALSE(false) << "unexpected failure"; michael@0: ASSERT_FALSE(false) << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: #ifdef __BORLANDC__ michael@0: // Restores warnings after previous "#pragma option push" supressed them michael@0: # pragma option pop michael@0: #endif michael@0: michael@0: TEST(StreamingAssertionsTest, IntegerEquals) { michael@0: EXPECT_EQ(1, 1) << "unexpected failure"; michael@0: ASSERT_EQ(1, 1) << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: TEST(StreamingAssertionsTest, IntegerLessThan) { michael@0: EXPECT_LT(1, 2) << "unexpected failure"; michael@0: ASSERT_LT(1, 2) << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: TEST(StreamingAssertionsTest, StringsEqual) { michael@0: EXPECT_STREQ("foo", "foo") << "unexpected failure"; michael@0: ASSERT_STREQ("foo", "foo") << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: TEST(StreamingAssertionsTest, StringsNotEqual) { michael@0: EXPECT_STRNE("foo", "bar") << "unexpected failure"; michael@0: ASSERT_STRNE("foo", "bar") << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) { michael@0: EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure"; michael@0: ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) { michael@0: EXPECT_STRCASENE("foo", "bar") << "unexpected failure"; michael@0: ASSERT_STRCASENE("foo", "bar") << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: TEST(StreamingAssertionsTest, FloatingPointEquals) { michael@0: EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; michael@0: ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure", michael@0: "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure", michael@0: "expected failure"); michael@0: } michael@0: michael@0: #if GTEST_HAS_EXCEPTIONS michael@0: michael@0: TEST(StreamingAssertionsTest, Throw) { michael@0: EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure"; michael@0: ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) << michael@0: "expected failure", "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) << michael@0: "expected failure", "expected failure"); michael@0: } michael@0: michael@0: TEST(StreamingAssertionsTest, NoThrow) { michael@0: EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure"; michael@0: ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) << michael@0: "expected failure", "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << michael@0: "expected failure", "expected failure"); michael@0: } michael@0: michael@0: TEST(StreamingAssertionsTest, AnyThrow) { michael@0: EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; michael@0: ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; michael@0: EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) << michael@0: "expected failure", "expected failure"); michael@0: EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << michael@0: "expected failure", "expected failure"); michael@0: } michael@0: michael@0: #endif // GTEST_HAS_EXCEPTIONS michael@0: michael@0: // Tests that Google Test correctly decides whether to use colors in the output. michael@0: michael@0: TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { michael@0: GTEST_FLAG(color) = "yes"; michael@0: michael@0: SetEnv("TERM", "xterm"); // TERM supports colors. michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. michael@0: michael@0: SetEnv("TERM", "dumb"); // TERM doesn't support colors. michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. michael@0: } michael@0: michael@0: TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { michael@0: SetEnv("TERM", "dumb"); // TERM doesn't support colors. michael@0: michael@0: GTEST_FLAG(color) = "True"; michael@0: EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. michael@0: michael@0: GTEST_FLAG(color) = "t"; michael@0: EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. michael@0: michael@0: GTEST_FLAG(color) = "1"; michael@0: EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. michael@0: } michael@0: michael@0: TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { michael@0: GTEST_FLAG(color) = "no"; michael@0: michael@0: SetEnv("TERM", "xterm"); // TERM supports colors. michael@0: EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. michael@0: michael@0: SetEnv("TERM", "dumb"); // TERM doesn't support colors. michael@0: EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. michael@0: } michael@0: michael@0: TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { michael@0: SetEnv("TERM", "xterm"); // TERM supports colors. michael@0: michael@0: GTEST_FLAG(color) = "F"; michael@0: EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: GTEST_FLAG(color) = "0"; michael@0: EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: GTEST_FLAG(color) = "unknown"; michael@0: EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: } michael@0: michael@0: TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { michael@0: GTEST_FLAG(color) = "auto"; michael@0: michael@0: SetEnv("TERM", "xterm"); // TERM supports colors. michael@0: EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: } michael@0: michael@0: TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { michael@0: GTEST_FLAG(color) = "auto"; michael@0: michael@0: #if GTEST_OS_WINDOWS michael@0: // On Windows, we ignore the TERM variable as it's usually not set. michael@0: michael@0: SetEnv("TERM", "dumb"); michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", ""); michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "xterm"); michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: #else michael@0: // On non-Windows platforms, we rely on TERM to determine if the michael@0: // terminal supports colors. michael@0: michael@0: SetEnv("TERM", "dumb"); // TERM doesn't support colors. michael@0: EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "emacs"); // TERM doesn't support colors. michael@0: EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "vt100"); // TERM doesn't support colors. michael@0: EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. michael@0: EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "xterm"); // TERM supports colors. michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "xterm-color"); // TERM supports colors. michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "xterm-256color"); // TERM supports colors. michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "screen"); // TERM supports colors. michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "linux"); // TERM supports colors. michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: michael@0: SetEnv("TERM", "cygwin"); // TERM supports colors. michael@0: EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. michael@0: #endif // GTEST_OS_WINDOWS michael@0: } michael@0: michael@0: // Verifies that StaticAssertTypeEq works in a namespace scope. michael@0: michael@0: static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq(); michael@0: static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ = michael@0: StaticAssertTypeEq(); michael@0: michael@0: // Verifies that StaticAssertTypeEq works in a class. michael@0: michael@0: template michael@0: class StaticAssertTypeEqTestHelper { michael@0: public: michael@0: StaticAssertTypeEqTestHelper() { StaticAssertTypeEq(); } michael@0: }; michael@0: michael@0: TEST(StaticAssertTypeEqTest, WorksInClass) { michael@0: StaticAssertTypeEqTestHelper(); michael@0: } michael@0: michael@0: // Verifies that StaticAssertTypeEq works inside a function. michael@0: michael@0: typedef int IntAlias; michael@0: michael@0: TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) { michael@0: StaticAssertTypeEq(); michael@0: StaticAssertTypeEq(); michael@0: } michael@0: michael@0: TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) { michael@0: testing::UnitTest* const unit_test = testing::UnitTest::GetInstance(); michael@0: michael@0: // We don't have a stack walker in Google Test yet. michael@0: EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str()); michael@0: EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str()); michael@0: } michael@0: michael@0: TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) { michael@0: EXPECT_FALSE(HasNonfatalFailure()); michael@0: } michael@0: michael@0: static void FailFatally() { FAIL(); } michael@0: michael@0: TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) { michael@0: FailFatally(); michael@0: const bool has_nonfatal_failure = HasNonfatalFailure(); michael@0: ClearCurrentTestPartResults(); michael@0: EXPECT_FALSE(has_nonfatal_failure); michael@0: } michael@0: michael@0: TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { michael@0: ADD_FAILURE(); michael@0: const bool has_nonfatal_failure = HasNonfatalFailure(); michael@0: ClearCurrentTestPartResults(); michael@0: EXPECT_TRUE(has_nonfatal_failure); michael@0: } michael@0: michael@0: TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { michael@0: FailFatally(); michael@0: ADD_FAILURE(); michael@0: const bool has_nonfatal_failure = HasNonfatalFailure(); michael@0: ClearCurrentTestPartResults(); michael@0: EXPECT_TRUE(has_nonfatal_failure); michael@0: } michael@0: michael@0: // A wrapper for calling HasNonfatalFailure outside of a test body. michael@0: static bool HasNonfatalFailureHelper() { michael@0: return testing::Test::HasNonfatalFailure(); michael@0: } michael@0: michael@0: TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) { michael@0: EXPECT_FALSE(HasNonfatalFailureHelper()); michael@0: } michael@0: michael@0: TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) { michael@0: ADD_FAILURE(); michael@0: const bool has_nonfatal_failure = HasNonfatalFailureHelper(); michael@0: ClearCurrentTestPartResults(); michael@0: EXPECT_TRUE(has_nonfatal_failure); michael@0: } michael@0: michael@0: TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) { michael@0: EXPECT_FALSE(HasFailure()); michael@0: } michael@0: michael@0: TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) { michael@0: FailFatally(); michael@0: const bool has_failure = HasFailure(); michael@0: ClearCurrentTestPartResults(); michael@0: EXPECT_TRUE(has_failure); michael@0: } michael@0: michael@0: TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { michael@0: ADD_FAILURE(); michael@0: const bool has_failure = HasFailure(); michael@0: ClearCurrentTestPartResults(); michael@0: EXPECT_TRUE(has_failure); michael@0: } michael@0: michael@0: TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { michael@0: FailFatally(); michael@0: ADD_FAILURE(); michael@0: const bool has_failure = HasFailure(); michael@0: ClearCurrentTestPartResults(); michael@0: EXPECT_TRUE(has_failure); michael@0: } michael@0: michael@0: // A wrapper for calling HasFailure outside of a test body. michael@0: static bool HasFailureHelper() { return testing::Test::HasFailure(); } michael@0: michael@0: TEST(HasFailureTest, WorksOutsideOfTestBody) { michael@0: EXPECT_FALSE(HasFailureHelper()); michael@0: } michael@0: michael@0: TEST(HasFailureTest, WorksOutsideOfTestBody2) { michael@0: ADD_FAILURE(); michael@0: const bool has_failure = HasFailureHelper(); michael@0: ClearCurrentTestPartResults(); michael@0: EXPECT_TRUE(has_failure); michael@0: } michael@0: michael@0: class TestListener : public EmptyTestEventListener { michael@0: public: michael@0: TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {} michael@0: TestListener(int* on_start_counter, bool* is_destroyed) michael@0: : on_start_counter_(on_start_counter), michael@0: is_destroyed_(is_destroyed) {} michael@0: michael@0: virtual ~TestListener() { michael@0: if (is_destroyed_) michael@0: *is_destroyed_ = true; michael@0: } michael@0: michael@0: protected: michael@0: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { michael@0: if (on_start_counter_ != NULL) michael@0: (*on_start_counter_)++; michael@0: } michael@0: michael@0: private: michael@0: int* on_start_counter_; michael@0: bool* is_destroyed_; michael@0: }; michael@0: michael@0: // Tests the constructor. michael@0: TEST(TestEventListenersTest, ConstructionWorks) { michael@0: TestEventListeners listeners; michael@0: michael@0: EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL); michael@0: EXPECT_TRUE(listeners.default_result_printer() == NULL); michael@0: EXPECT_TRUE(listeners.default_xml_generator() == NULL); michael@0: } michael@0: michael@0: // Tests that the TestEventListeners destructor deletes all the listeners it michael@0: // owns. michael@0: TEST(TestEventListenersTest, DestructionWorks) { michael@0: bool default_result_printer_is_destroyed = false; michael@0: bool default_xml_printer_is_destroyed = false; michael@0: bool extra_listener_is_destroyed = false; michael@0: TestListener* default_result_printer = new TestListener( michael@0: NULL, &default_result_printer_is_destroyed); michael@0: TestListener* default_xml_printer = new TestListener( michael@0: NULL, &default_xml_printer_is_destroyed); michael@0: TestListener* extra_listener = new TestListener( michael@0: NULL, &extra_listener_is_destroyed); michael@0: michael@0: { michael@0: TestEventListeners listeners; michael@0: TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, michael@0: default_result_printer); michael@0: TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, michael@0: default_xml_printer); michael@0: listeners.Append(extra_listener); michael@0: } michael@0: EXPECT_TRUE(default_result_printer_is_destroyed); michael@0: EXPECT_TRUE(default_xml_printer_is_destroyed); michael@0: EXPECT_TRUE(extra_listener_is_destroyed); michael@0: } michael@0: michael@0: // Tests that a listener Append'ed to a TestEventListeners list starts michael@0: // receiving events. michael@0: TEST(TestEventListenersTest, Append) { michael@0: int on_start_counter = 0; michael@0: bool is_destroyed = false; michael@0: TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); michael@0: { michael@0: TestEventListeners listeners; michael@0: listeners.Append(listener); michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: EXPECT_EQ(1, on_start_counter); michael@0: } michael@0: EXPECT_TRUE(is_destroyed); michael@0: } michael@0: michael@0: // Tests that listeners receive events in the order they were appended to michael@0: // the list, except for *End requests, which must be received in the reverse michael@0: // order. michael@0: class SequenceTestingListener : public EmptyTestEventListener { michael@0: public: michael@0: SequenceTestingListener(std::vector* vector, const char* id) michael@0: : vector_(vector), id_(id) {} michael@0: michael@0: protected: michael@0: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { michael@0: vector_->push_back(GetEventDescription("OnTestProgramStart")); michael@0: } michael@0: michael@0: virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) { michael@0: vector_->push_back(GetEventDescription("OnTestProgramEnd")); michael@0: } michael@0: michael@0: virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, michael@0: int /*iteration*/) { michael@0: vector_->push_back(GetEventDescription("OnTestIterationStart")); michael@0: } michael@0: michael@0: virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, michael@0: int /*iteration*/) { michael@0: vector_->push_back(GetEventDescription("OnTestIterationEnd")); michael@0: } michael@0: michael@0: private: michael@0: String GetEventDescription(const char* method) { michael@0: Message message; michael@0: message << id_ << "." << method; michael@0: return message.GetString(); michael@0: } michael@0: michael@0: std::vector* vector_; michael@0: const char* const id_; michael@0: michael@0: GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener); michael@0: }; michael@0: michael@0: TEST(EventListenerTest, AppendKeepsOrder) { michael@0: std::vector vec; michael@0: TestEventListeners listeners; michael@0: listeners.Append(new SequenceTestingListener(&vec, "1st")); michael@0: listeners.Append(new SequenceTestingListener(&vec, "2nd")); michael@0: listeners.Append(new SequenceTestingListener(&vec, "3rd")); michael@0: michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: ASSERT_EQ(3U, vec.size()); michael@0: EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str()); michael@0: EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str()); michael@0: EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str()); michael@0: michael@0: vec.clear(); michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd( michael@0: *UnitTest::GetInstance()); michael@0: ASSERT_EQ(3U, vec.size()); michael@0: EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str()); michael@0: EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str()); michael@0: EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str()); michael@0: michael@0: vec.clear(); michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart( michael@0: *UnitTest::GetInstance(), 0); michael@0: ASSERT_EQ(3U, vec.size()); michael@0: EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str()); michael@0: EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str()); michael@0: EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str()); michael@0: michael@0: vec.clear(); michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd( michael@0: *UnitTest::GetInstance(), 0); michael@0: ASSERT_EQ(3U, vec.size()); michael@0: EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str()); michael@0: EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str()); michael@0: EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str()); michael@0: } michael@0: michael@0: // Tests that a listener removed from a TestEventListeners list stops receiving michael@0: // events and is not deleted when the list is destroyed. michael@0: TEST(TestEventListenersTest, Release) { michael@0: int on_start_counter = 0; michael@0: bool is_destroyed = false; michael@0: // Although Append passes the ownership of this object to the list, michael@0: // the following calls release it, and we need to delete it before the michael@0: // test ends. michael@0: TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); michael@0: { michael@0: TestEventListeners listeners; michael@0: listeners.Append(listener); michael@0: EXPECT_EQ(listener, listeners.Release(listener)); michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: EXPECT_TRUE(listeners.Release(listener) == NULL); michael@0: } michael@0: EXPECT_EQ(0, on_start_counter); michael@0: EXPECT_FALSE(is_destroyed); michael@0: delete listener; michael@0: } michael@0: michael@0: // Tests that no events are forwarded when event forwarding is disabled. michael@0: TEST(EventListenerTest, SuppressEventForwarding) { michael@0: int on_start_counter = 0; michael@0: TestListener* listener = new TestListener(&on_start_counter, NULL); michael@0: michael@0: TestEventListeners listeners; michael@0: listeners.Append(listener); michael@0: ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); michael@0: TestEventListenersAccessor::SuppressEventForwarding(&listeners); michael@0: ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: EXPECT_EQ(0, on_start_counter); michael@0: } michael@0: michael@0: // Tests that events generated by Google Test are not forwarded in michael@0: // death test subprocesses. michael@0: TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) { michael@0: EXPECT_DEATH_IF_SUPPORTED({ michael@0: GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( michael@0: *GetUnitTestImpl()->listeners())) << "expected failure";}, michael@0: "expected failure"); michael@0: } michael@0: michael@0: // Tests that a listener installed via SetDefaultResultPrinter() starts michael@0: // receiving events and is returned via default_result_printer() and that michael@0: // the previous default_result_printer is removed from the list and deleted. michael@0: TEST(EventListenerTest, default_result_printer) { michael@0: int on_start_counter = 0; michael@0: bool is_destroyed = false; michael@0: TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); michael@0: michael@0: TestEventListeners listeners; michael@0: TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); michael@0: michael@0: EXPECT_EQ(listener, listeners.default_result_printer()); michael@0: michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: michael@0: EXPECT_EQ(1, on_start_counter); michael@0: michael@0: // Replacing default_result_printer with something else should remove it michael@0: // from the list and destroy it. michael@0: TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL); michael@0: michael@0: EXPECT_TRUE(listeners.default_result_printer() == NULL); michael@0: EXPECT_TRUE(is_destroyed); michael@0: michael@0: // After broadcasting an event the counter is still the same, indicating michael@0: // the listener is not in the list anymore. michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: EXPECT_EQ(1, on_start_counter); michael@0: } michael@0: michael@0: // Tests that the default_result_printer listener stops receiving events michael@0: // when removed via Release and that is not owned by the list anymore. michael@0: TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) { michael@0: int on_start_counter = 0; michael@0: bool is_destroyed = false; michael@0: // Although Append passes the ownership of this object to the list, michael@0: // the following calls release it, and we need to delete it before the michael@0: // test ends. michael@0: TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); michael@0: { michael@0: TestEventListeners listeners; michael@0: TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); michael@0: michael@0: EXPECT_EQ(listener, listeners.Release(listener)); michael@0: EXPECT_TRUE(listeners.default_result_printer() == NULL); michael@0: EXPECT_FALSE(is_destroyed); michael@0: michael@0: // Broadcasting events now should not affect default_result_printer. michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: EXPECT_EQ(0, on_start_counter); michael@0: } michael@0: // Destroying the list should not affect the listener now, too. michael@0: EXPECT_FALSE(is_destroyed); michael@0: delete listener; michael@0: } michael@0: michael@0: // Tests that a listener installed via SetDefaultXmlGenerator() starts michael@0: // receiving events and is returned via default_xml_generator() and that michael@0: // the previous default_xml_generator is removed from the list and deleted. michael@0: TEST(EventListenerTest, default_xml_generator) { michael@0: int on_start_counter = 0; michael@0: bool is_destroyed = false; michael@0: TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); michael@0: michael@0: TestEventListeners listeners; michael@0: TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); michael@0: michael@0: EXPECT_EQ(listener, listeners.default_xml_generator()); michael@0: michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: michael@0: EXPECT_EQ(1, on_start_counter); michael@0: michael@0: // Replacing default_xml_generator with something else should remove it michael@0: // from the list and destroy it. michael@0: TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL); michael@0: michael@0: EXPECT_TRUE(listeners.default_xml_generator() == NULL); michael@0: EXPECT_TRUE(is_destroyed); michael@0: michael@0: // After broadcasting an event the counter is still the same, indicating michael@0: // the listener is not in the list anymore. michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: EXPECT_EQ(1, on_start_counter); michael@0: } michael@0: michael@0: // Tests that the default_xml_generator listener stops receiving events michael@0: // when removed via Release and that is not owned by the list anymore. michael@0: TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) { michael@0: int on_start_counter = 0; michael@0: bool is_destroyed = false; michael@0: // Although Append passes the ownership of this object to the list, michael@0: // the following calls release it, and we need to delete it before the michael@0: // test ends. michael@0: TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); michael@0: { michael@0: TestEventListeners listeners; michael@0: TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); michael@0: michael@0: EXPECT_EQ(listener, listeners.Release(listener)); michael@0: EXPECT_TRUE(listeners.default_xml_generator() == NULL); michael@0: EXPECT_FALSE(is_destroyed); michael@0: michael@0: // Broadcasting events now should not affect default_xml_generator. michael@0: TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( michael@0: *UnitTest::GetInstance()); michael@0: EXPECT_EQ(0, on_start_counter); michael@0: } michael@0: // Destroying the list should not affect the listener now, too. michael@0: EXPECT_FALSE(is_destroyed); michael@0: delete listener; michael@0: } michael@0: michael@0: // Sanity tests to ensure that the alternative, verbose spellings of michael@0: // some of the macros work. We don't test them thoroughly as that michael@0: // would be quite involved. Since their implementations are michael@0: // straightforward, and they are rarely used, we'll just rely on the michael@0: // users to tell us when they are broken. michael@0: GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. michael@0: GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED. michael@0: michael@0: // GTEST_FAIL is the same as FAIL. michael@0: EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure", michael@0: "An expected failure"); michael@0: michael@0: // GTEST_ASSERT_XY is the same as ASSERT_XY. michael@0: michael@0: GTEST_ASSERT_EQ(0, 0); michael@0: EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure", michael@0: "An expected failure"); michael@0: EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure", michael@0: "An expected failure"); michael@0: michael@0: GTEST_ASSERT_NE(0, 1); michael@0: GTEST_ASSERT_NE(1, 0); michael@0: EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure", michael@0: "An expected failure"); michael@0: michael@0: GTEST_ASSERT_LE(0, 0); michael@0: GTEST_ASSERT_LE(0, 1); michael@0: EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure", michael@0: "An expected failure"); michael@0: michael@0: GTEST_ASSERT_LT(0, 1); michael@0: EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure", michael@0: "An expected failure"); michael@0: EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure", michael@0: "An expected failure"); michael@0: michael@0: GTEST_ASSERT_GE(0, 0); michael@0: GTEST_ASSERT_GE(1, 0); michael@0: EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure", michael@0: "An expected failure"); michael@0: michael@0: GTEST_ASSERT_GT(1, 0); michael@0: EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure", michael@0: "An expected failure"); michael@0: EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure", michael@0: "An expected failure"); michael@0: } michael@0: michael@0: // Tests for internal utilities necessary for implementation of the universal michael@0: // printing. michael@0: // TODO(vladl@google.com): Find a better home for them. michael@0: michael@0: class ConversionHelperBase {}; michael@0: class ConversionHelperDerived : public ConversionHelperBase {}; michael@0: michael@0: // Tests that IsAProtocolMessage::value is a compile-time constant. michael@0: TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) { michael@0: GTEST_COMPILE_ASSERT_(IsAProtocolMessage::value, michael@0: const_true); michael@0: GTEST_COMPILE_ASSERT_(!IsAProtocolMessage::value, const_false); michael@0: } michael@0: michael@0: // Tests that IsAProtocolMessage::value is true when T is michael@0: // proto2::Message or a sub-class of it. michael@0: TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) { michael@0: EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value); michael@0: EXPECT_TRUE(IsAProtocolMessage::value); michael@0: } michael@0: michael@0: // Tests that IsAProtocolMessage::value is false when T is neither michael@0: // ProtocolMessage nor a sub-class of it. michael@0: TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) { michael@0: EXPECT_FALSE(IsAProtocolMessage::value); michael@0: EXPECT_FALSE(IsAProtocolMessage::value); michael@0: } michael@0: michael@0: // Tests that CompileAssertTypesEqual compiles when the type arguments are michael@0: // equal. michael@0: TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) { michael@0: CompileAssertTypesEqual(); michael@0: CompileAssertTypesEqual(); michael@0: } michael@0: michael@0: // Tests that RemoveReference does not affect non-reference types. michael@0: TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) { michael@0: CompileAssertTypesEqual::type>(); michael@0: CompileAssertTypesEqual::type>(); michael@0: } michael@0: michael@0: // Tests that RemoveReference removes reference from reference types. michael@0: TEST(RemoveReferenceTest, RemovesReference) { michael@0: CompileAssertTypesEqual::type>(); michael@0: CompileAssertTypesEqual::type>(); michael@0: } michael@0: michael@0: // Tests GTEST_REMOVE_REFERENCE_. michael@0: michael@0: template michael@0: void TestGTestRemoveReference() { michael@0: CompileAssertTypesEqual(); michael@0: } michael@0: michael@0: TEST(RemoveReferenceTest, MacroVersion) { michael@0: TestGTestRemoveReference(); michael@0: TestGTestRemoveReference(); michael@0: } michael@0: michael@0: michael@0: // Tests that RemoveConst does not affect non-const types. michael@0: TEST(RemoveConstTest, DoesNotAffectNonConstType) { michael@0: CompileAssertTypesEqual::type>(); michael@0: CompileAssertTypesEqual::type>(); michael@0: } michael@0: michael@0: // Tests that RemoveConst removes const from const types. michael@0: TEST(RemoveConstTest, RemovesConst) { michael@0: CompileAssertTypesEqual::type>(); michael@0: CompileAssertTypesEqual::type>(); michael@0: CompileAssertTypesEqual::type>(); michael@0: } michael@0: michael@0: // Tests GTEST_REMOVE_CONST_. michael@0: michael@0: template michael@0: void TestGTestRemoveConst() { michael@0: CompileAssertTypesEqual(); michael@0: } michael@0: michael@0: TEST(RemoveConstTest, MacroVersion) { michael@0: TestGTestRemoveConst(); michael@0: TestGTestRemoveConst(); michael@0: TestGTestRemoveConst(); michael@0: } michael@0: michael@0: // Tests GTEST_REMOVE_REFERENCE_AND_CONST_. michael@0: michael@0: template michael@0: void TestGTestRemoveReferenceAndConst() { michael@0: CompileAssertTypesEqual(); michael@0: } michael@0: michael@0: TEST(RemoveReferenceToConstTest, Works) { michael@0: TestGTestRemoveReferenceAndConst(); michael@0: TestGTestRemoveReferenceAndConst(); michael@0: TestGTestRemoveReferenceAndConst(); michael@0: TestGTestRemoveReferenceAndConst(); michael@0: TestGTestRemoveReferenceAndConst(); michael@0: } michael@0: michael@0: // Tests that AddReference does not affect reference types. michael@0: TEST(AddReferenceTest, DoesNotAffectReferenceType) { michael@0: CompileAssertTypesEqual::type>(); michael@0: CompileAssertTypesEqual::type>(); michael@0: } michael@0: michael@0: // Tests that AddReference adds reference to non-reference types. michael@0: TEST(AddReferenceTest, AddsReference) { michael@0: CompileAssertTypesEqual::type>(); michael@0: CompileAssertTypesEqual::type>(); michael@0: } michael@0: michael@0: // Tests GTEST_ADD_REFERENCE_. michael@0: michael@0: template michael@0: void TestGTestAddReference() { michael@0: CompileAssertTypesEqual(); michael@0: } michael@0: michael@0: TEST(AddReferenceTest, MacroVersion) { michael@0: TestGTestAddReference(); michael@0: TestGTestAddReference(); michael@0: } michael@0: michael@0: // Tests GTEST_REFERENCE_TO_CONST_. michael@0: michael@0: template michael@0: void TestGTestReferenceToConst() { michael@0: CompileAssertTypesEqual(); michael@0: } michael@0: michael@0: TEST(GTestReferenceToConstTest, Works) { michael@0: TestGTestReferenceToConst(); michael@0: TestGTestReferenceToConst(); michael@0: TestGTestReferenceToConst(); michael@0: TestGTestReferenceToConst(); michael@0: } michael@0: michael@0: // Tests that ImplicitlyConvertible::value is a compile-time constant. michael@0: TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) { michael@0: GTEST_COMPILE_ASSERT_((ImplicitlyConvertible::value), const_true); michael@0: GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible::value), michael@0: const_false); michael@0: } michael@0: michael@0: // Tests that ImplicitlyConvertible::value is true when T1 can michael@0: // be implicitly converted to T2. michael@0: TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) { michael@0: EXPECT_TRUE((ImplicitlyConvertible::value)); michael@0: EXPECT_TRUE((ImplicitlyConvertible::value)); michael@0: EXPECT_TRUE((ImplicitlyConvertible::value)); michael@0: EXPECT_TRUE((ImplicitlyConvertible::value)); michael@0: EXPECT_TRUE((ImplicitlyConvertible::value)); michael@0: EXPECT_TRUE((ImplicitlyConvertible::value)); michael@0: } michael@0: michael@0: // Tests that ImplicitlyConvertible::value is false when T1 michael@0: // cannot be implicitly converted to T2. michael@0: TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) { michael@0: EXPECT_FALSE((ImplicitlyConvertible::value)); michael@0: EXPECT_FALSE((ImplicitlyConvertible::value)); michael@0: EXPECT_FALSE((ImplicitlyConvertible::value)); michael@0: EXPECT_FALSE((ImplicitlyConvertible::value)); michael@0: } michael@0: michael@0: // Tests IsContainerTest. michael@0: michael@0: class NonContainer {}; michael@0: michael@0: TEST(IsContainerTestTest, WorksForNonContainer) { michael@0: EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest(0))); michael@0: EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest(0))); michael@0: EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest(0))); michael@0: } michael@0: michael@0: TEST(IsContainerTestTest, WorksForContainer) { michael@0: EXPECT_EQ(sizeof(IsContainer), michael@0: sizeof(IsContainerTest >(0))); michael@0: EXPECT_EQ(sizeof(IsContainer), michael@0: sizeof(IsContainerTest >(0))); michael@0: } michael@0: michael@0: // Tests ArrayEq(). michael@0: michael@0: TEST(ArrayEqTest, WorksForDegeneratedArrays) { michael@0: EXPECT_TRUE(ArrayEq(5, 5L)); michael@0: EXPECT_FALSE(ArrayEq('a', 0)); michael@0: } michael@0: michael@0: TEST(ArrayEqTest, WorksForOneDimensionalArrays) { michael@0: // Note that a and b are distinct but compatible types. michael@0: const int a[] = { 0, 1 }; michael@0: long b[] = { 0, 1 }; michael@0: EXPECT_TRUE(ArrayEq(a, b)); michael@0: EXPECT_TRUE(ArrayEq(a, 2, b)); michael@0: michael@0: b[0] = 2; michael@0: EXPECT_FALSE(ArrayEq(a, b)); michael@0: EXPECT_FALSE(ArrayEq(a, 1, b)); michael@0: } michael@0: michael@0: TEST(ArrayEqTest, WorksForTwoDimensionalArrays) { michael@0: const char a[][3] = { "hi", "lo" }; michael@0: const char b[][3] = { "hi", "lo" }; michael@0: const char c[][3] = { "hi", "li" }; michael@0: michael@0: EXPECT_TRUE(ArrayEq(a, b)); michael@0: EXPECT_TRUE(ArrayEq(a, 2, b)); michael@0: michael@0: EXPECT_FALSE(ArrayEq(a, c)); michael@0: EXPECT_FALSE(ArrayEq(a, 2, c)); michael@0: } michael@0: michael@0: // Tests ArrayAwareFind(). michael@0: michael@0: TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) { michael@0: const char a[] = "hello"; michael@0: EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o')); michael@0: EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x')); michael@0: } michael@0: michael@0: TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) { michael@0: int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; michael@0: const int b[2] = { 2, 3 }; michael@0: EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b)); michael@0: michael@0: const int c[2] = { 6, 7 }; michael@0: EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c)); michael@0: } michael@0: michael@0: // Tests CopyArray(). michael@0: michael@0: TEST(CopyArrayTest, WorksForDegeneratedArrays) { michael@0: int n = 0; michael@0: CopyArray('a', &n); michael@0: EXPECT_EQ('a', n); michael@0: } michael@0: michael@0: TEST(CopyArrayTest, WorksForOneDimensionalArrays) { michael@0: const char a[3] = "hi"; michael@0: int b[3]; michael@0: #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. michael@0: CopyArray(a, &b); michael@0: EXPECT_TRUE(ArrayEq(a, b)); michael@0: #endif michael@0: michael@0: int c[3]; michael@0: CopyArray(a, 3, c); michael@0: EXPECT_TRUE(ArrayEq(a, c)); michael@0: } michael@0: michael@0: TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { michael@0: const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } }; michael@0: int b[2][3]; michael@0: #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. michael@0: CopyArray(a, &b); michael@0: EXPECT_TRUE(ArrayEq(a, b)); michael@0: #endif michael@0: michael@0: int c[2][3]; michael@0: CopyArray(a, 2, c); michael@0: EXPECT_TRUE(ArrayEq(a, c)); michael@0: } michael@0: michael@0: // Tests NativeArray. michael@0: michael@0: TEST(NativeArrayTest, ConstructorFromArrayWorks) { michael@0: const int a[3] = { 0, 1, 2 }; michael@0: NativeArray na(a, 3, kReference); michael@0: EXPECT_EQ(3U, na.size()); michael@0: EXPECT_EQ(a, na.begin()); michael@0: } michael@0: michael@0: TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) { michael@0: typedef int Array[2]; michael@0: Array* a = new Array[1]; michael@0: (*a)[0] = 0; michael@0: (*a)[1] = 1; michael@0: NativeArray na(*a, 2, kCopy); michael@0: EXPECT_NE(*a, na.begin()); michael@0: delete[] a; michael@0: EXPECT_EQ(0, na.begin()[0]); michael@0: EXPECT_EQ(1, na.begin()[1]); michael@0: michael@0: // We rely on the heap checker to verify that na deletes the copy of michael@0: // array. michael@0: } michael@0: michael@0: TEST(NativeArrayTest, TypeMembersAreCorrect) { michael@0: StaticAssertTypeEq::value_type>(); michael@0: StaticAssertTypeEq::value_type>(); michael@0: michael@0: StaticAssertTypeEq::const_iterator>(); michael@0: StaticAssertTypeEq::const_iterator>(); michael@0: } michael@0: michael@0: TEST(NativeArrayTest, MethodsWork) { michael@0: const int a[3] = { 0, 1, 2 }; michael@0: NativeArray na(a, 3, kCopy); michael@0: ASSERT_EQ(3U, na.size()); michael@0: EXPECT_EQ(3, na.end() - na.begin()); michael@0: michael@0: NativeArray::const_iterator it = na.begin(); michael@0: EXPECT_EQ(0, *it); michael@0: ++it; michael@0: EXPECT_EQ(1, *it); michael@0: it++; michael@0: EXPECT_EQ(2, *it); michael@0: ++it; michael@0: EXPECT_EQ(na.end(), it); michael@0: michael@0: EXPECT_TRUE(na == na); michael@0: michael@0: NativeArray na2(a, 3, kReference); michael@0: EXPECT_TRUE(na == na2); michael@0: michael@0: const int b1[3] = { 0, 1, 1 }; michael@0: const int b2[4] = { 0, 1, 2, 3 }; michael@0: EXPECT_FALSE(na == NativeArray(b1, 3, kReference)); michael@0: EXPECT_FALSE(na == NativeArray(b2, 4, kCopy)); michael@0: } michael@0: michael@0: TEST(NativeArrayTest, WorksForTwoDimensionalArray) { michael@0: const char a[2][3] = { "hi", "lo" }; michael@0: NativeArray na(a, 2, kReference); michael@0: ASSERT_EQ(2U, na.size()); michael@0: EXPECT_EQ(a, na.begin()); michael@0: } michael@0: michael@0: // Tests SkipPrefix(). michael@0: michael@0: TEST(SkipPrefixTest, SkipsWhenPrefixMatches) { michael@0: const char* const str = "hello"; michael@0: michael@0: const char* p = str; michael@0: EXPECT_TRUE(SkipPrefix("", &p)); michael@0: EXPECT_EQ(str, p); michael@0: michael@0: p = str; michael@0: EXPECT_TRUE(SkipPrefix("hell", &p)); michael@0: EXPECT_EQ(str + 4, p); michael@0: } michael@0: michael@0: TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) { michael@0: const char* const str = "world"; michael@0: michael@0: const char* p = str; michael@0: EXPECT_FALSE(SkipPrefix("W", &p)); michael@0: EXPECT_EQ(str, p); michael@0: michael@0: p = str; michael@0: EXPECT_FALSE(SkipPrefix("world!", &p)); michael@0: EXPECT_EQ(str, p); michael@0: }