"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "googletest/test/gtest_unittest.cc" between
googletest-release-1.11.0.tar.gz and googletest-release-1.12.0.tar.gz

About: GoogleTest is Google's (unit) testing and mocking framework for C++ tests.

gtest_unittest.cc  (googletest-release-1.11.0):gtest_unittest.cc  (googletest-release-1.12.0)
skipping to change at line 40 skipping to change at line 40
// //
// Tests for Google Test itself. This verifies that the basic constructs of // Tests for Google Test itself. This verifies that the basic constructs of
// Google Test work. // Google Test work.
#include "gtest/gtest.h" #include "gtest/gtest.h"
// Verifies that the command line flag variables can be accessed in // Verifies that the command line flag variables can be accessed in
// code once "gtest.h" has been #included. // code once "gtest.h" has been #included.
// Do not move it after other gtest #includes. // Do not move it after other gtest #includes.
TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) || bool dummy =
testing::GTEST_FLAG(break_on_failure) || GTEST_FLAG_GET(also_run_disabled_tests) ||
testing::GTEST_FLAG(catch_exceptions) || GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) ||
testing::GTEST_FLAG(color) != "unknown" || GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) ||
testing::GTEST_FLAG(fail_fast) || GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) ||
testing::GTEST_FLAG(filter) != "unknown" || GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) ||
testing::GTEST_FLAG(list_tests) || GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) ||
testing::GTEST_FLAG(output) != "unknown" || GTEST_FLAG_GET(repeat) > 0 ||
testing::GTEST_FLAG(brief) || testing::GTEST_FLAG(print_time) || GTEST_FLAG_GET(recreate_environments_when_repeating) ||
testing::GTEST_FLAG(random_seed) || GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) ||
testing::GTEST_FLAG(repeat) > 0 || GTEST_FLAG_GET(stack_trace_depth) > 0 ||
testing::GTEST_FLAG(show_internal_stack_frames) || GTEST_FLAG_GET(stream_result_to) != "unknown" ||
testing::GTEST_FLAG(shuffle) || GTEST_FLAG_GET(throw_on_failure);
testing::GTEST_FLAG(stack_trace_depth) > 0 ||
testing::GTEST_FLAG(stream_result_to) != "unknown" ||
testing::GTEST_FLAG(throw_on_failure);
EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused. EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
} }
#include <limits.h> // For INT_MAX. #include <limits.h> // For INT_MAX.
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <time.h> #include <time.h>
#include <cstdint> #include <cstdint>
#include <map> #include <map>
skipping to change at line 117 skipping to change at line 114
streamer_.OnTestProgramEnd(unit_test_); streamer_.OnTestProgramEnd(unit_test_);
EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output()); EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
} }
TEST_F(StreamingListenerTest, OnTestIterationEnd) { TEST_F(StreamingListenerTest, OnTestIterationEnd) {
*output() = ""; *output() = "";
streamer_.OnTestIterationEnd(unit_test_, 42); streamer_.OnTestIterationEnd(unit_test_, 42);
EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output()); EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
} }
TEST_F(StreamingListenerTest, OnTestCaseStart) { TEST_F(StreamingListenerTest, OnTestSuiteStart) {
*output() = ""; *output() = "";
streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", nullptr, nullptr)); streamer_.OnTestSuiteStart(TestSuite("FooTest", "Bar", nullptr, nullptr));
EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output()); EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
} }
TEST_F(StreamingListenerTest, OnTestCaseEnd) { TEST_F(StreamingListenerTest, OnTestSuiteEnd) {
*output() = ""; *output() = "";
streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", nullptr, nullptr)); streamer_.OnTestSuiteEnd(TestSuite("FooTest", "Bar", nullptr, nullptr));
EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output()); EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
} }
TEST_F(StreamingListenerTest, OnTestStart) { TEST_F(StreamingListenerTest, OnTestStart) {
*output() = ""; *output() = "";
streamer_.OnTestStart(test_info_obj_); streamer_.OnTestStart(test_info_obj_);
EXPECT_EQ("event=TestStart&name=Bar\n", *output()); EXPECT_EQ("event=TestStart&name=Bar\n", *output());
} }
TEST_F(StreamingListenerTest, OnTestEnd) { TEST_F(StreamingListenerTest, OnTestEnd) {
*output() = ""; *output() = "";
streamer_.OnTestEnd(test_info_obj_); streamer_.OnTestEnd(test_info_obj_);
EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output()); EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
} }
TEST_F(StreamingListenerTest, OnTestPartResult) { TEST_F(StreamingListenerTest, OnTestPartResult) {
*output() = ""; *output() = "";
streamer_.OnTestPartResult(TestPartResult( streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure,
TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%")); "foo.cc", 42, "failed=\n&%"));
// Meta characters in the failure message should be properly escaped. // Meta characters in the failure message should be properly escaped.
EXPECT_EQ( EXPECT_EQ(
"event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n", "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
*output()); *output());
} }
#endif // GTEST_CAN_STREAM_RESULTS_ #endif // GTEST_CAN_STREAM_RESULTS_
// Provides access to otherwise private parts of the TestEventListeners class // Provides access to otherwise private parts of the TestEventListeners class
skipping to change at line 202 skipping to change at line 199
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
using testing::AssertionFailure; using testing::AssertionFailure;
using testing::AssertionResult; using testing::AssertionResult;
using testing::AssertionSuccess; using testing::AssertionSuccess;
using testing::DoubleLE; using testing::DoubleLE;
using testing::EmptyTestEventListener; using testing::EmptyTestEventListener;
using testing::Environment; using testing::Environment;
using testing::FloatLE; using testing::FloatLE;
using testing::GTEST_FLAG(also_run_disabled_tests);
using testing::GTEST_FLAG(break_on_failure);
using testing::GTEST_FLAG(catch_exceptions);
using testing::GTEST_FLAG(color);
using testing::GTEST_FLAG(death_test_use_fork);
using testing::GTEST_FLAG(fail_fast);
using testing::GTEST_FLAG(filter);
using testing::GTEST_FLAG(list_tests);
using testing::GTEST_FLAG(output);
using testing::GTEST_FLAG(brief);
using testing::GTEST_FLAG(print_time);
using testing::GTEST_FLAG(random_seed);
using testing::GTEST_FLAG(repeat);
using testing::GTEST_FLAG(show_internal_stack_frames);
using testing::GTEST_FLAG(shuffle);
using testing::GTEST_FLAG(stack_trace_depth);
using testing::GTEST_FLAG(stream_result_to);
using testing::GTEST_FLAG(throw_on_failure);
using testing::IsNotSubstring; using testing::IsNotSubstring;
using testing::IsSubstring; using testing::IsSubstring;
using testing::kMaxStackTraceDepth; using testing::kMaxStackTraceDepth;
using testing::Message; using testing::Message;
using testing::ScopedFakeTestPartResultReporter; using testing::ScopedFakeTestPartResultReporter;
using testing::StaticAssertTypeEq; using testing::StaticAssertTypeEq;
using testing::Test; using testing::Test;
using testing::TestEventListeners; using testing::TestEventListeners;
using testing::TestInfo; using testing::TestInfo;
using testing::TestPartResult; using testing::TestPartResult;
skipping to change at line 268 skipping to change at line 247
using testing::internal::HasDebugStringAndShortDebugString; using testing::internal::HasDebugStringAndShortDebugString;
using testing::internal::Int32FromEnvOrDie; using testing::internal::Int32FromEnvOrDie;
using testing::internal::IsContainer; using testing::internal::IsContainer;
using testing::internal::IsContainerTest; using testing::internal::IsContainerTest;
using testing::internal::IsNotContainer; using testing::internal::IsNotContainer;
using testing::internal::kMaxRandomSeed; using testing::internal::kMaxRandomSeed;
using testing::internal::kTestTypeIdInGoogleTest; using testing::internal::kTestTypeIdInGoogleTest;
using testing::internal::NativeArray; using testing::internal::NativeArray;
using testing::internal::OsStackTraceGetter; using testing::internal::OsStackTraceGetter;
using testing::internal::OsStackTraceGetterInterface; using testing::internal::OsStackTraceGetterInterface;
using testing::internal::ParseInt32Flag; using testing::internal::ParseFlag;
using testing::internal::RelationToSourceCopy; using testing::internal::RelationToSourceCopy;
using testing::internal::RelationToSourceReference; using testing::internal::RelationToSourceReference;
using testing::internal::ShouldRunTestOnShard; using testing::internal::ShouldRunTestOnShard;
using testing::internal::ShouldShard; using testing::internal::ShouldShard;
using testing::internal::ShouldUseColor; using testing::internal::ShouldUseColor;
using testing::internal::Shuffle; using testing::internal::Shuffle;
using testing::internal::ShuffleRange; using testing::internal::ShuffleRange;
using testing::internal::SkipPrefix; using testing::internal::SkipPrefix;
using testing::internal::StreamableToString; using testing::internal::StreamableToString;
using testing::internal::String; using testing::internal::String;
skipping to change at line 296 skipping to change at line 275
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStdout; using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout; using testing::internal::GetCapturedStdout;
#endif #endif
#if GTEST_IS_THREADSAFE #if GTEST_IS_THREADSAFE
using testing::internal::ThreadWithParam; using testing::internal::ThreadWithParam;
#endif #endif
class TestingVector : public std::vector<int> { class TestingVector : public std::vector<int> {};
};
::std::ostream& operator<<(::std::ostream& os, ::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) {
const TestingVector& vector) {
os << "{ "; os << "{ ";
for (size_t i = 0; i < vector.size(); i++) { for (size_t i = 0; i < vector.size(); i++) {
os << vector[i] << " "; os << vector[i] << " ";
} }
os << "}"; os << "}";
return os; return os;
} }
// This line tests that we can define tests in an unnamed namespace. // This line tests that we can define tests in an unnamed namespace.
namespace { namespace {
skipping to change at line 428 skipping to change at line 405
TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) { TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3)); EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10)); EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200)); EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200)); EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000)); EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
} }
// Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
// for particular dates below was verified in Python using // for particular dates below was verified in Python using
// datetime.datetime.fromutctimestamp(<timetamp>/1000). // datetime.datetime.fromutctimestamp(<timestamp>/1000).
// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
// have to set up a particular timezone to obtain predictable results. // have to set up a particular timezone to obtain predictable results.
class FormatEpochTimeInMillisAsIso8601Test : public Test { class FormatEpochTimeInMillisAsIso8601Test : public Test {
public: public:
// On Cygwin, GCC doesn't allow unqualified integer literals to exceed // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
// 32 bits, even when 64-bit integer types are available. We have to // 32 bits, even when 64-bit integer types are available. We have to
// force the constants to have a 64-bit type here. // force the constants to have a 64-bit type here.
static const TimeInMillis kMillisPerSec = 1000; static const TimeInMillis kMillisPerSec = 1000;
private: private:
void SetUp() override { void SetUp() override {
saved_tz_ = nullptr; saved_tz_ = nullptr;
GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */) GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
if (getenv("TZ")) if (getenv("TZ")) saved_tz_ = strdup(getenv("TZ"));
saved_tz_ = strdup(getenv("TZ"));
GTEST_DISABLE_MSC_DEPRECATED_POP_() GTEST_DISABLE_MSC_DEPRECATED_POP_()
// Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
// cannot use the local time zone because the function's output depends // cannot use the local time zone because the function's output depends
// on the time zone. // on the time zone.
SetTimeZone("UTC+00"); SetTimeZone("UTC+00");
} }
void TearDown() override { void TearDown() override {
SetTimeZone(saved_tz_); SetTimeZone(saved_tz_);
skipping to change at line 474 skipping to change at line 450
#if _MSC_VER || GTEST_OS_WINDOWS_MINGW #if _MSC_VER || GTEST_OS_WINDOWS_MINGW
// ...Unless it's MSVC, whose standard library's _putenv doesn't // ...Unless it's MSVC, whose standard library's _putenv doesn't
// distinguish between an empty and a missing variable. // distinguish between an empty and a missing variable.
const std::string env_var = const std::string env_var =
std::string("TZ=") + (time_zone ? time_zone : ""); std::string("TZ=") + (time_zone ? time_zone : "");
_putenv(env_var.c_str()); _putenv(env_var.c_str());
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
tzset(); tzset();
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
#else #else
#if GTEST_OS_LINUX_ANDROID && __ANDROID_API__ < 21
// Work around KitKat bug in tzset by setting "UTC" before setting "UTC+00".
// See https://github.com/android/ndk/issues/1604.
setenv("TZ", "UTC", 1);
tzset();
#endif
if (time_zone) { if (time_zone) {
setenv(("TZ"), time_zone, 1); setenv(("TZ"), time_zone, 1);
} else { } else {
unsetenv("TZ"); unsetenv("TZ");
} }
tzset(); tzset();
#endif #endif
} }
const char* saved_tz_; const char* saved_tz_;
}; };
const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec; const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) { TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
EXPECT_EQ("2011-10-31T18:52:42.000", EXPECT_EQ("2011-10-31T18:52:42.000",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec)); FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
} }
TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) { TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
EXPECT_EQ( EXPECT_EQ("2011-10-31T18:52:42.234",
"2011-10-31T18:52:42.234", FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
} }
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) { TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
EXPECT_EQ("2011-09-03T05:07:02.000", EXPECT_EQ("2011-09-03T05:07:02.000",
FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec)); FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
} }
TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) { TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
EXPECT_EQ("2011-09-28T17:08:22.000", EXPECT_EQ("2011-09-28T17:08:22.000",
FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec)); FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
} }
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0)); EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
} }
# ifdef __BORLANDC__ #ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code" // Silences warnings: "Condition is always true", "Unreachable code"
# pragma option push -w-ccc -w-rch #pragma option push -w-ccc -w-rch
# endif #endif
// Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
// when the RHS is a pointer type. // when the RHS is a pointer type.
TEST(NullLiteralTest, LHSAllowsNullLiterals) { TEST(NullLiteralTest, LHSAllowsNullLiterals) {
EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
EXPECT_EQ(nullptr, static_cast<void*>(nullptr)); EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
ASSERT_EQ(nullptr, static_cast<void*>(nullptr)); ASSERT_EQ(nullptr, static_cast<void*>(nullptr));
skipping to change at line 590 skipping to change at line 571
// Test that gtests detection and handling of null pointer constants // Test that gtests detection and handling of null pointer constants
// doesn't trigger a warning when '0' isn't actually used as null. // doesn't trigger a warning when '0' isn't actually used as null.
EXPECT_EQ(0, 0); EXPECT_EQ(0, 0);
ASSERT_EQ(0, 0); ASSERT_EQ(0, 0);
} }
#ifdef __clang__ #ifdef __clang__
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif
# ifdef __BORLANDC__ #ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them. // Restores warnings after previous "#pragma option push" suppressed them.
# pragma option pop #pragma option pop
# endif #endif
// //
// Tests CodePointToUtf8(). // Tests CodePointToUtf8().
// Tests that the NUL character L'\0' is encoded correctly. // Tests that the NUL character L'\0' is encoded correctly.
TEST(CodePointToUtf8Test, CanEncodeNul) { TEST(CodePointToUtf8Test, CanEncodeNul) {
EXPECT_EQ("", CodePointToUtf8(L'\0')); EXPECT_EQ("", CodePointToUtf8(L'\0'));
} }
// Tests that ASCII characters are encoded correctly. // Tests that ASCII characters are encoded correctly.
skipping to change at line 621 skipping to change at line 602
// Tests that Unicode code-points that have 8 to 11 bits are encoded // Tests that Unicode code-points that have 8 to 11 bits are encoded
// as 110xxxxx 10xxxxxx. // as 110xxxxx 10xxxxxx.
TEST(CodePointToUtf8Test, CanEncode8To11Bits) { TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
// 000 1101 0011 => 110-00011 10-010011 // 000 1101 0011 => 110-00011 10-010011
EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3')); EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
// 101 0111 0110 => 110-10101 10-110110 // 101 0111 0110 => 110-10101 10-110110
// Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
// in wide strings and wide chars. In order to accommodate them, we have to // in wide strings and wide chars. In order to accommodate them, we have to
// introduce such character constants as integers. // introduce such character constants as integers.
EXPECT_EQ("\xD5\xB6", EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576)));
CodePointToUtf8(static_cast<wchar_t>(0x576)));
} }
// Tests that Unicode code-points that have 12 to 16 bits are encoded // Tests that Unicode code-points that have 12 to 16 bits are encoded
// as 1110xxxx 10xxxxxx 10xxxxxx. // as 1110xxxx 10xxxxxx 10xxxxxx.
TEST(CodePointToUtf8Test, CanEncode12To16Bits) { TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
// 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
EXPECT_EQ("\xE0\xA3\x93", EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
// 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
EXPECT_EQ("\xEC\x9D\x8D", EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
} }
#if !GTEST_WIDE_STRING_USES_UTF16_ #if !GTEST_WIDE_STRING_USES_UTF16_
// Tests in this group require a wchar_t to hold > 16 bits, and thus // Tests in this group require a wchar_t to hold > 16 bits, and thus
// are skipped on Windows, and Cygwin, where a wchar_t is // are skipped on Windows, and Cygwin, where a wchar_t is
// 16-bit wide. This code may not compile on those systems. // 16-bit wide. This code may not compile on those systems.
// Tests that Unicode code-points that have 17 to 21 bits are encoded // Tests that Unicode code-points that have 17 to 21 bits are encoded
// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
TEST(CodePointToUtf8Test, CanEncode17To21Bits) { TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
skipping to change at line 686 skipping to change at line 664
} }
// Tests that Unicode code-points that have 8 to 11 bits are encoded // Tests that Unicode code-points that have 8 to 11 bits are encoded
// as 110xxxxx 10xxxxxx. // as 110xxxxx 10xxxxxx.
TEST(WideStringToUtf8Test, CanEncode8To11Bits) { TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
// 000 1101 0011 => 110-00011 10-010011 // 000 1101 0011 => 110-00011 10-010011
EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str()); EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
// 101 0111 0110 => 110-10101 10-110110 // 101 0111 0110 => 110-10101 10-110110
const wchar_t s[] = { 0x576, '\0' }; const wchar_t s[] = {0x576, '\0'};
EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
} }
// Tests that Unicode code-points that have 12 to 16 bits are encoded // Tests that Unicode code-points that have 12 to 16 bits are encoded
// as 1110xxxx 10xxxxxx 10xxxxxx. // as 1110xxxx 10xxxxxx 10xxxxxx.
TEST(WideStringToUtf8Test, CanEncode12To16Bits) { TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
// 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
const wchar_t s1[] = { 0x8D3, '\0' }; const wchar_t s1[] = {0x8D3, '\0'};
EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
// 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
const wchar_t s2[] = { 0xC74D, '\0' }; const wchar_t s2[] = {0xC74D, '\0'};
EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
} }
// Tests that the conversion stops when the function encounters \0 character. // Tests that the conversion stops when the function encounters \0 character.
TEST(WideStringToUtf8Test, StopsOnNulCharacter) { TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str()); EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
} }
// Tests that the conversion stops when the function reaches the limit // Tests that the conversion stops when the function reaches the limit
skipping to change at line 735 skipping to change at line 713
// 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
} }
// Tests that encoding an invalid code-point generates the expected result. // Tests that encoding an invalid code-point generates the expected result.
TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
WideStringToUtf8(L"\xABCDFF", -1).c_str()); WideStringToUtf8(L"\xABCDFF", -1).c_str());
} }
#else // !GTEST_WIDE_STRING_USES_UTF16_ #else // !GTEST_WIDE_STRING_USES_UTF16_
// Tests that surrogate pairs are encoded correctly on the systems using // Tests that surrogate pairs are encoded correctly on the systems using
// UTF-16 encoding in the wide strings. // UTF-16 encoding in the wide strings.
TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
const wchar_t s[] = { 0xD801, 0xDC00, '\0' }; const wchar_t s[] = {0xD801, 0xDC00, '\0'};
EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
} }
// Tests that encoding an invalid UTF-16 surrogate pair // Tests that encoding an invalid UTF-16 surrogate pair
// generates the expected result. // generates the expected result.
TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
// Leading surrogate is at the end of the string. // Leading surrogate is at the end of the string.
const wchar_t s1[] = { 0xD800, '\0' }; const wchar_t s1[] = {0xD800, '\0'};
EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
// Leading surrogate is not followed by the trailing surrogate. // Leading surrogate is not followed by the trailing surrogate.
const wchar_t s2[] = { 0xD800, 'M', '\0' }; const wchar_t s2[] = {0xD800, 'M', '\0'};
EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
// Trailing surrogate appearas without a leading surrogate. // Trailing surrogate appearas without a leading surrogate.
const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' }; const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'};
EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
} }
#endif // !GTEST_WIDE_STRING_USES_UTF16_ #endif // !GTEST_WIDE_STRING_USES_UTF16_
// Tests that codepoint concatenation works correctly. // Tests that codepoint concatenation works correctly.
#if !GTEST_WIDE_STRING_USES_UTF16_ #if !GTEST_WIDE_STRING_USES_UTF16_
TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
EXPECT_STREQ( EXPECT_STREQ(
"\xF4\x88\x98\xB4" "\xF4\x88\x98\xB4"
"\xEC\x9D\x8D" "\xEC\x9D\x8D"
"\n" "\n"
"\xD5\xB6" "\xD5\xB6"
"\xE0\xA3\x93" "\xE0\xA3\x93"
"\xF4\x88\x98\xB4", "\xF4\x88\x98\xB4",
WideStringToUtf8(s, -1).c_str()); WideStringToUtf8(s, -1).c_str());
} }
#else #else
TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'}; const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'};
EXPECT_STREQ( EXPECT_STREQ(
"\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", "\xEC\x9D\x8D"
"\n"
"\xD5\xB6"
"\xE0\xA3\x93",
WideStringToUtf8(s, -1).c_str()); WideStringToUtf8(s, -1).c_str());
} }
#endif // !GTEST_WIDE_STRING_USES_UTF16_ #endif // !GTEST_WIDE_STRING_USES_UTF16_
// Tests the Random class. // Tests the Random class.
TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
testing::internal::Random random(42); testing::internal::Random random(42);
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(random.Generate(0),
random.Generate(0), "Cannot generate a number in the range \\[0, 0\\)");
"Cannot generate a number in the range \\[0, 0\\)");
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(
random.Generate(testing::internal::Random::kMaxRange + 1), random.Generate(testing::internal::Random::kMaxRange + 1),
"Generation of a number in \\[0, 2147483649\\) was requested, " "Generation of a number in \\[0, 2147483649\\) was requested, "
"but this can only generate numbers in \\[0, 2147483648\\)"); "but this can only generate numbers in \\[0, 2147483648\\)");
} }
TEST(RandomTest, GeneratesNumbersWithinRange) { TEST(RandomTest, GeneratesNumbersWithinRange) {
constexpr uint32_t kRange = 10000; constexpr uint32_t kRange = 10000;
testing::internal::Random random(12345); testing::internal::Random random(12345);
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
skipping to change at line 915 skipping to change at line 895
for (int i = 0; i < static_cast<int>(kVectorSize); i++) { for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
vector_.push_back(i); vector_.push_back(i);
} }
} }
static bool VectorIsCorrupt(const TestingVector& vector) { static bool VectorIsCorrupt(const TestingVector& vector) {
if (kVectorSize != vector.size()) { if (kVectorSize != vector.size()) {
return true; return true;
} }
bool found_in_vector[kVectorSize] = { false }; bool found_in_vector[kVectorSize] = {false};
for (size_t i = 0; i < vector.size(); i++) { for (size_t i = 0; i < vector.size(); i++) {
const int e = vector[i]; const int e = vector[i];
if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) { if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
return true; return true;
} }
found_in_vector[e] = true; found_in_vector[e] = true;
} }
// Vector size is correct, elements' range is correct, no // Vector size is correct, elements' range is correct, no
// duplicate elements. Therefore no corruption has occurred. // duplicate elements. Therefore no corruption has occurred.
skipping to change at line 942 skipping to change at line 922
static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) { static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
for (int i = begin; i < end; i++) { for (int i = begin; i < end; i++) {
if (i != vector[static_cast<size_t>(i)]) { if (i != vector[static_cast<size_t>(i)]) {
return true; return true;
} }
} }
return false; return false;
} }
static bool RangeIsUnshuffled( static bool RangeIsUnshuffled(const TestingVector& vector, int begin,
const TestingVector& vector, int begin, int end) { int end) {
return !RangeIsShuffled(vector, begin, end); return !RangeIsShuffled(vector, begin, end);
} }
static bool VectorIsShuffled(const TestingVector& vector) { static bool VectorIsShuffled(const TestingVector& vector) {
return RangeIsShuffled(vector, 0, static_cast<int>(vector.size())); return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
} }
static bool VectorIsUnshuffled(const TestingVector& vector) { static bool VectorIsUnshuffled(const TestingVector& vector) {
return !VectorIsShuffled(vector); return !VectorIsShuffled(vector);
} }
skipping to change at line 968 skipping to change at line 948
const size_t VectorShuffleTest::kVectorSize; const size_t VectorShuffleTest::kVectorSize;
TEST_F(VectorShuffleTest, HandlesEmptyRange) { TEST_F(VectorShuffleTest, HandlesEmptyRange) {
// Tests an empty range at the beginning... // Tests an empty range at the beginning...
ShuffleRange(&random_, 0, 0, &vector_); ShuffleRange(&random_, 0, 0, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...in the middle... // ...in the middle...
ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_); ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...at the end... // ...at the end...
ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_); ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...and past the end. // ...and past the end.
ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_); ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
skipping to change at line 990 skipping to change at line 970
ASSERT_PRED1(VectorIsUnshuffled, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_);
} }
TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) { TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
// Tests a size one range at the beginning... // Tests a size one range at the beginning...
ShuffleRange(&random_, 0, 1, &vector_); ShuffleRange(&random_, 0, 1, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...in the middle... // ...in the middle...
ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_); ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...and at the end. // ...and at the end.
ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_); ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_);
} }
// Because we use our own random number generator and a fixed seed, // Because we use our own random number generator and a fixed seed,
skipping to change at line 1015 skipping to change at line 995
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_; EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
// Tests the first and last elements in particular to ensure that // Tests the first and last elements in particular to ensure that
// there are no off-by-one problems in our shuffle algorithm. // there are no off-by-one problems in our shuffle algorithm.
EXPECT_NE(0, vector_[0]); EXPECT_NE(0, vector_[0]);
EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]); EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
} }
TEST_F(VectorShuffleTest, ShufflesStartOfVector) { TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
const int kRangeSize = kVectorSize/2; const int kRangeSize = kVectorSize / 2;
ShuffleRange(&random_, 0, kRangeSize, &vector_); ShuffleRange(&random_, 0, kRangeSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
static_cast<int>(kVectorSize)); static_cast<int>(kVectorSize));
} }
TEST_F(VectorShuffleTest, ShufflesEndOfVector) { TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
skipping to change at line 1037 skipping to change at line 1017
ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_); ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
static_cast<int>(kVectorSize)); static_cast<int>(kVectorSize));
} }
TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) { TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
const int kRangeSize = static_cast<int>(kVectorSize) / 3; const int kRangeSize = static_cast<int>(kVectorSize) / 3;
ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_); ShuffleRange(&random_, kRangeSize, 2 * kRangeSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize); EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2 * kRangeSize);
EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize, EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
static_cast<int>(kVectorSize)); static_cast<int>(kVectorSize));
} }
TEST_F(VectorShuffleTest, ShufflesRepeatably) { TEST_F(VectorShuffleTest, ShufflesRepeatably) {
TestingVector vector2; TestingVector vector2;
for (size_t i = 0; i < kVectorSize; i++) { for (size_t i = 0; i < kVectorSize; i++) {
vector2.push_back(static_cast<int>(i)); vector2.push_back(static_cast<int>(i));
} }
skipping to change at line 1106 skipping to change at line 1086
EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull)); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
} }
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Tests String::ShowWideCString(). // Tests String::ShowWideCString().
TEST(StringTest, ShowWideCString) { TEST(StringTest, ShowWideCString) {
EXPECT_STREQ("(null)", EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str());
String::ShowWideCString(NULL).c_str());
EXPECT_STREQ("", String::ShowWideCString(L"").c_str()); EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str()); EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
} }
# if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
TEST(StringTest, AnsiAndUtf16Null) { TEST(StringTest, AnsiAndUtf16Null) {
EXPECT_EQ(NULL, String::AnsiToUtf16(NULL)); EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL)); EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
} }
TEST(StringTest, AnsiAndUtf16ConvertBasic) { TEST(StringTest, AnsiAndUtf16ConvertBasic) {
const char* ansi = String::Utf16ToAnsi(L"str"); const char* ansi = String::Utf16ToAnsi(L"str");
EXPECT_STREQ("str", ansi); EXPECT_STREQ("str", ansi);
delete [] ansi; delete[] ansi;
const WCHAR* utf16 = String::AnsiToUtf16("str"); const WCHAR* utf16 = String::AnsiToUtf16("str");
EXPECT_EQ(0, wcsncmp(L"str", utf16, 3)); EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
delete [] utf16; delete[] utf16;
} }
TEST(StringTest, AnsiAndUtf16ConvertPathChars) { TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?"); const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
EXPECT_STREQ(".:\\ \"*?", ansi); EXPECT_STREQ(".:\\ \"*?", ansi);
delete [] ansi; delete[] ansi;
const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?"); const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3)); EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
delete [] utf16; delete[] utf16;
} }
# endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Tests TestProperty construction. // Tests TestProperty construction.
TEST(TestPropertyTest, StringValue) { TEST(TestPropertyTest, StringValue) {
TestProperty property("key", "1"); TestProperty property("key", "1");
EXPECT_STREQ("key", property.key()); EXPECT_STREQ("key", property.key());
EXPECT_STREQ("1", property.value()); EXPECT_STREQ("1", property.value());
} }
skipping to change at line 1157 skipping to change at line 1136
TEST(TestPropertyTest, ReplaceStringValue) { TEST(TestPropertyTest, ReplaceStringValue) {
TestProperty property("key", "1"); TestProperty property("key", "1");
EXPECT_STREQ("1", property.value()); EXPECT_STREQ("1", property.value());
property.SetValue("2"); property.SetValue("2");
EXPECT_STREQ("2", property.value()); EXPECT_STREQ("2", property.value());
} }
// AddFatalFailure() and AddNonfatalFailure() must be stand-alone // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
// functions (i.e. their definitions cannot be inlined at the call // functions (i.e. their definitions cannot be inlined at the call
// sites), or C++Builder won't compile the code. // sites), or C++Builder won't compile the code.
static void AddFatalFailure() { static void AddFatalFailure() { FAIL() << "Expected fatal failure."; }
FAIL() << "Expected fatal failure.";
}
static void AddNonfatalFailure() { static void AddNonfatalFailure() {
ADD_FAILURE() << "Expected non-fatal failure."; ADD_FAILURE() << "Expected non-fatal failure.";
} }
class ScopedFakeTestPartResultReporterTest : public Test { class ScopedFakeTestPartResultReporterTest : public Test {
public: // Must be public and not protected due to a bug in g++ 3.4.2. public: // Must be public and not protected due to a bug in g++ 3.4.2.
enum FailureMode { enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
FATAL_FAILURE,
NONFATAL_FAILURE
};
static void AddFailure(FailureMode failure) { static void AddFailure(FailureMode failure) {
if (failure == FATAL_FAILURE) { if (failure == FATAL_FAILURE) {
AddFatalFailure(); AddFatalFailure();
} else { } else {
AddNonfatalFailure(); AddNonfatalFailure();
} }
} }
}; };
// Tests that ScopedFakeTestPartResultReporter intercepts test // Tests that ScopedFakeTestPartResultReporter intercepts test
skipping to change at line 1210 skipping to change at line 1184
// Tests, that the deprecated constructor still works. // Tests, that the deprecated constructor still works.
ScopedFakeTestPartResultReporter reporter(&results); ScopedFakeTestPartResultReporter reporter(&results);
AddFailure(NONFATAL_FAILURE); AddFailure(NONFATAL_FAILURE);
} }
EXPECT_EQ(1, results.size()); EXPECT_EQ(1, results.size());
} }
#if GTEST_IS_THREADSAFE #if GTEST_IS_THREADSAFE
class ScopedFakeTestPartResultReporterWithThreadsTest class ScopedFakeTestPartResultReporterWithThreadsTest
: public ScopedFakeTestPartResultReporterTest { : public ScopedFakeTestPartResultReporterTest {
protected: protected:
static void AddFailureInOtherThread(FailureMode failure) { static void AddFailureInOtherThread(FailureMode failure) {
ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr); ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
thread.Join(); thread.Join();
} }
}; };
TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest, TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
InterceptsTestFailuresInAllThreads) { InterceptsTestFailuresInAllThreads) {
TestPartResultArray results; TestPartResultArray results;
skipping to change at line 1263 skipping to change at line 1237
TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) { TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
// We have another test below to verify that the macro catches fatal // We have another test below to verify that the macro catches fatal
// failures generated on another thread. // failures generated on another thread.
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(), EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
"Expected fatal failure."); "Expected fatal failure.");
} }
#ifdef __BORLANDC__ #ifdef __BORLANDC__
// Silences warnings: "Condition is always true" // Silences warnings: "Condition is always true"
# pragma option push -w-ccc #pragma option push -w-ccc
#endif #endif
// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
// function even when the statement in it contains ASSERT_*. // function even when the statement in it contains ASSERT_*.
int NonVoidFunction() { int NonVoidFunction() {
EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
return 0; return 0;
} }
skipping to change at line 1291 skipping to change at line 1265
void DoesNotAbortHelper(bool* aborted) { void DoesNotAbortHelper(bool* aborted) {
EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
*aborted = false; *aborted = false;
} }
#ifdef __BORLANDC__ #ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them. // Restores warnings after previous "#pragma option push" suppressed them.
# pragma option pop #pragma option pop
#endif #endif
TEST_F(ExpectFatalFailureTest, DoesNotAbort) { TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
bool aborted = true; bool aborted = true;
DoesNotAbortHelper(&aborted); DoesNotAbortHelper(&aborted);
EXPECT_FALSE(aborted); EXPECT_FALSE(aborted);
} }
// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
// statement that contains a macro which expands to code containing an // statement that contains a macro which expands to code containing an
// unprotected comma. // unprotected comma.
static int global_var = 0; static int global_var = 0;
#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++ #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
#ifndef __BORLANDC__ #ifndef __BORLANDC__
// ICE's in C++Builder. // ICE's in C++Builder.
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE(
GTEST_USE_UNPROTECTED_COMMA_; {
AddFatalFailure(); GTEST_USE_UNPROTECTED_COMMA_;
}, ""); AddFatalFailure();
},
"");
#endif #endif
EXPECT_FATAL_FAILURE_ON_ALL_THREADS({ EXPECT_FATAL_FAILURE_ON_ALL_THREADS(
GTEST_USE_UNPROTECTED_COMMA_; {
AddFatalFailure(); GTEST_USE_UNPROTECTED_COMMA_;
}, ""); AddFatalFailure();
},
"");
} }
// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}. // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest; typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure.");
"Expected non-fatal failure.");
} }
TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) { TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
::std::string("Expected non-fatal failure.")); ::std::string("Expected non-fatal failure."));
} }
TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
// We have another test below to verify that the macro catches // We have another test below to verify that the macro catches
// non-fatal failures generated on another thread. // non-fatal failures generated on another thread.
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(), EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
"Expected non-fatal failure."); "Expected non-fatal failure.");
} }
// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
// statement that contains a macro which expands to code containing an // statement that contains a macro which expands to code containing an
// unprotected comma. // unprotected comma.
TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
GTEST_USE_UNPROTECTED_COMMA_; {
AddNonfatalFailure(); GTEST_USE_UNPROTECTED_COMMA_;
}, ""); AddNonfatalFailure();
},
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({ "");
GTEST_USE_UNPROTECTED_COMMA_;
AddNonfatalFailure(); EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
}, ""); {
GTEST_USE_UNPROTECTED_COMMA_;
AddNonfatalFailure();
},
"");
} }
#if GTEST_IS_THREADSAFE #if GTEST_IS_THREADSAFE
typedef ScopedFakeTestPartResultReporterWithThreadsTest typedef ScopedFakeTestPartResultReporterWithThreadsTest
ExpectFailureWithThreadsTest; ExpectFailureWithThreadsTest;
TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) { TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE), EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
"Expected fatal failure."); "Expected fatal failure.");
skipping to change at line 1399 skipping to change at line 1380
} }
// Tests the TestResult class // Tests the TestResult class
// The test fixture for testing TestResult. // The test fixture for testing TestResult.
class TestResultTest : public Test { class TestResultTest : public Test {
protected: protected:
typedef std::vector<TestPartResult> TPRVector; typedef std::vector<TestPartResult> TPRVector;
// We make use of 2 TestPartResult objects, // We make use of 2 TestPartResult objects,
TestPartResult * pr1, * pr2; TestPartResult *pr1, *pr2;
// ... and 3 TestResult objects. // ... and 3 TestResult objects.
TestResult * r0, * r1, * r2; TestResult *r0, *r1, *r2;
void SetUp() override { void SetUp() override {
// pr1 is for success. // pr1 is for success.
pr1 = new TestPartResult(TestPartResult::kSuccess, pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10,
"foo/bar.cc",
10,
"Success!"); "Success!");
// pr2 is for fatal failure. // pr2 is for fatal failure.
pr2 = new TestPartResult(TestPartResult::kFatalFailure, pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc",
"foo/bar.cc",
-1, // This line number means "unknown" -1, // This line number means "unknown"
"Failure!"); "Failure!");
// Creates the TestResult objects. // Creates the TestResult objects.
r0 = new TestResult(); r0 = new TestResult();
r1 = new TestResult(); r1 = new TestResult();
r2 = new TestResult(); r2 = new TestResult();
// In order to test TestResult, we need to modify its internal // In order to test TestResult, we need to modify its internal
// state, in particular the TestPartResult vector it holds. // state, in particular the TestPartResult vector it holds.
// test_part_results() returns a const reference to this vector. // test_part_results() returns a const reference to this vector.
// We cast it to a non-const object s.t. it can be modified // We cast it to a non-const object s.t. it can be modified
TPRVector* results1 = const_cast<TPRVector*>( TPRVector* results1 =
&TestResultAccessor::test_part_results(*r1)); const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r1));
TPRVector* results2 = const_cast<TPRVector*>( TPRVector* results2 =
&TestResultAccessor::test_part_results(*r2)); const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r2));
// r0 is an empty TestResult. // r0 is an empty TestResult.
// r1 contains a single SUCCESS TestPartResult. // r1 contains a single SUCCESS TestPartResult.
results1->push_back(*pr1); results1->push_back(*pr1);
// r2 contains a SUCCESS, and a FAILURE. // r2 contains a SUCCESS, and a FAILURE.
results2->push_back(*pr1); results2->push_back(*pr1);
results2->push_back(*pr2); results2->push_back(*pr2);
} }
skipping to change at line 1600 skipping to change at line 1578
// Tests that GTestFlagSaver works on Windows and Mac. // Tests that GTestFlagSaver works on Windows and Mac.
class GTestFlagSaverTest : public Test { class GTestFlagSaverTest : public Test {
protected: protected:
// Saves the Google Test flags such that we can restore them later, and // Saves the Google Test flags such that we can restore them later, and
// then sets them to their default values. This will be called // then sets them to their default values. This will be called
// before the first test in this test case is run. // before the first test in this test case is run.
static void SetUpTestSuite() { static void SetUpTestSuite() {
saver_ = new GTestFlagSaver; saver_ = new GTestFlagSaver;
GTEST_FLAG(also_run_disabled_tests) = false; GTEST_FLAG_SET(also_run_disabled_tests, false);
GTEST_FLAG(break_on_failure) = false; GTEST_FLAG_SET(break_on_failure, false);
GTEST_FLAG(catch_exceptions) = false; GTEST_FLAG_SET(catch_exceptions, false);
GTEST_FLAG(death_test_use_fork) = false; GTEST_FLAG_SET(death_test_use_fork, false);
GTEST_FLAG(color) = "auto"; GTEST_FLAG_SET(color, "auto");
GTEST_FLAG(fail_fast) = false; GTEST_FLAG_SET(fail_fast, false);
GTEST_FLAG(filter) = ""; GTEST_FLAG_SET(filter, "");
GTEST_FLAG(list_tests) = false; GTEST_FLAG_SET(list_tests, false);
GTEST_FLAG(output) = ""; GTEST_FLAG_SET(output, "");
GTEST_FLAG(brief) = false; GTEST_FLAG_SET(brief, false);
GTEST_FLAG(print_time) = true; GTEST_FLAG_SET(print_time, true);
GTEST_FLAG(random_seed) = 0; GTEST_FLAG_SET(random_seed, 0);
GTEST_FLAG(repeat) = 1; GTEST_FLAG_SET(repeat, 1);
GTEST_FLAG(shuffle) = false; GTEST_FLAG_SET(recreate_environments_when_repeating, true);
GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; GTEST_FLAG_SET(shuffle, false);
GTEST_FLAG(stream_result_to) = ""; GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
GTEST_FLAG(throw_on_failure) = false; GTEST_FLAG_SET(stream_result_to, "");
GTEST_FLAG_SET(throw_on_failure, false);
} }
// Restores the Google Test flags that the tests have modified. This will // Restores the Google Test flags that the tests have modified. This will
// be called after the last test in this test case is run. // be called after the last test in this test case is run.
static void TearDownTestSuite() { static void TearDownTestSuite() {
delete saver_; delete saver_;
saver_ = nullptr; saver_ = nullptr;
} }
// Verifies that the Google Test flags have their default values, and then // Verifies that the Google Test flags have their default values, and then
// modifies each of them. // modifies each of them.
void VerifyAndModifyFlags() { void VerifyAndModifyFlags() {
EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests)); EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));
EXPECT_FALSE(GTEST_FLAG(break_on_failure)); EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));
EXPECT_FALSE(GTEST_FLAG(catch_exceptions)); EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));
EXPECT_STREQ("auto", GTEST_FLAG(color).c_str()); EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str());
EXPECT_FALSE(GTEST_FLAG(death_test_use_fork)); EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));
EXPECT_FALSE(GTEST_FLAG(fail_fast)); EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));
EXPECT_STREQ("", GTEST_FLAG(filter).c_str()); EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str());
EXPECT_FALSE(GTEST_FLAG(list_tests)); EXPECT_FALSE(GTEST_FLAG_GET(list_tests));
EXPECT_STREQ("", GTEST_FLAG(output).c_str()); EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str());
EXPECT_FALSE(GTEST_FLAG(brief)); EXPECT_FALSE(GTEST_FLAG_GET(brief));
EXPECT_TRUE(GTEST_FLAG(print_time)); EXPECT_TRUE(GTEST_FLAG_GET(print_time));
EXPECT_EQ(0, GTEST_FLAG(random_seed)); EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));
EXPECT_EQ(1, GTEST_FLAG(repeat)); EXPECT_EQ(1, GTEST_FLAG_GET(repeat));
EXPECT_FALSE(GTEST_FLAG(shuffle)); EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));
EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth)); EXPECT_FALSE(GTEST_FLAG_GET(shuffle));
EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str()); EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));
EXPECT_FALSE(GTEST_FLAG(throw_on_failure)); EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str());
EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));
GTEST_FLAG(also_run_disabled_tests) = true;
GTEST_FLAG(break_on_failure) = true; GTEST_FLAG_SET(also_run_disabled_tests, true);
GTEST_FLAG(catch_exceptions) = true; GTEST_FLAG_SET(break_on_failure, true);
GTEST_FLAG(color) = "no"; GTEST_FLAG_SET(catch_exceptions, true);
GTEST_FLAG(death_test_use_fork) = true; GTEST_FLAG_SET(color, "no");
GTEST_FLAG(fail_fast) = true; GTEST_FLAG_SET(death_test_use_fork, true);
GTEST_FLAG(filter) = "abc"; GTEST_FLAG_SET(fail_fast, true);
GTEST_FLAG(list_tests) = true; GTEST_FLAG_SET(filter, "abc");
GTEST_FLAG(output) = "xml:foo.xml"; GTEST_FLAG_SET(list_tests, true);
GTEST_FLAG(brief) = true; GTEST_FLAG_SET(output, "xml:foo.xml");
GTEST_FLAG(print_time) = false; GTEST_FLAG_SET(brief, true);
GTEST_FLAG(random_seed) = 1; GTEST_FLAG_SET(print_time, false);
GTEST_FLAG(repeat) = 100; GTEST_FLAG_SET(random_seed, 1);
GTEST_FLAG(shuffle) = true; GTEST_FLAG_SET(repeat, 100);
GTEST_FLAG(stack_trace_depth) = 1; GTEST_FLAG_SET(recreate_environments_when_repeating, false);
GTEST_FLAG(stream_result_to) = "localhost:1234"; GTEST_FLAG_SET(shuffle, true);
GTEST_FLAG(throw_on_failure) = true; GTEST_FLAG_SET(stack_trace_depth, 1);
GTEST_FLAG_SET(stream_result_to, "localhost:1234");
GTEST_FLAG_SET(throw_on_failure, true);
} }
private: private:
// For saving Google Test flags during this test case. // For saving Google Test flags during this test case.
static GTestFlagSaver* saver_; static GTestFlagSaver* saver_;
}; };
GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr; GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
// Google Test doesn't guarantee the order of tests. The following two // Google Test doesn't guarantee the order of tests. The following two
// tests are designed to work regardless of their order. // tests are designed to work regardless of their order.
// Modifies the Google Test flags in the test body. // Modifies the Google Test flags in the test body.
TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); }
VerifyAndModifyFlags();
}
// Verifies that the Google Test flags in the body of the previous test were // Verifies that the Google Test flags in the body of the previous test were
// restored to their original values. // restored to their original values.
TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); }
VerifyAndModifyFlags();
}
// Sets an environment variable with the given name to the given // Sets an environment variable with the given name to the given
// value. If the value argument is "", unsets the environment // value. If the value argument is "", unsets the environment
// variable. The caller must ensure that both arguments are not NULL. // variable. The caller must ensure that both arguments are not NULL.
static void SetEnv(const char* name, const char* value) { static void SetEnv(const char* name, const char* value) {
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
// Environment variables are not supported on Windows CE. // Environment variables are not supported on Windows CE.
return; return;
#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
// C++Builder's putenv only stores a pointer to its parameter; we have to // C++Builder's putenv only stores a pointer to its parameter; we have to
// ensure that the string remains valid as long as it might be needed. // ensure that the string remains valid as long as it might be needed.
// We use an std::map to do so. // We use an std::map to do so.
static std::map<std::string, std::string*> added_env; static std::map<std::string, std::string*> added_env;
// Because putenv stores a pointer to the string buffer, we can't delete the // Because putenv stores a pointer to the string buffer, we can't delete the
// previous string (if present) until after it's replaced. // previous string (if present) until after it's replaced.
std::string *prev_env = NULL; std::string* prev_env = NULL;
if (added_env.find(name) != added_env.end()) { if (added_env.find(name) != added_env.end()) {
prev_env = added_env[name]; prev_env = added_env[name];
} }
added_env[name] = new std::string( added_env[name] =
(Message() << name << "=" << value).GetString()); new std::string((Message() << name << "=" << value).GetString());
// The standard signature of putenv accepts a 'char*' argument. Other // The standard signature of putenv accepts a 'char*' argument. Other
// implementations, like C++Builder's, accept a 'const char*'. // implementations, like C++Builder's, accept a 'const char*'.
// We cast away the 'const' since that would work for both variants. // We cast away the 'const' since that would work for both variants.
putenv(const_cast<char*>(added_env[name]->c_str())); putenv(const_cast<char*>(added_env[name]->c_str()));
delete prev_env; delete prev_env;
#elif GTEST_OS_WINDOWS // If we are on Windows proper. #elif GTEST_OS_WINDOWS // If we are on Windows proper.
_putenv((Message() << name << "=" << value).GetString().c_str()); _putenv((Message() << name << "=" << value).GetString().c_str());
#else #else
if (*value == '\0') { if (*value == '\0') {
skipping to change at line 1739 skipping to change at line 1716
// Tests Int32FromGTestEnv(). // Tests Int32FromGTestEnv().
// Tests that Int32FromGTestEnv() returns the default value when the // Tests that Int32FromGTestEnv() returns the default value when the
// environment variable is not set. // environment variable is not set.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) { TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", ""); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
EXPECT_EQ(10, Int32FromGTestEnv("temp", 10)); EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
} }
# if !defined(GTEST_GET_INT32_FROM_ENV_) #if !defined(GTEST_GET_INT32_FROM_ENV_)
// Tests that Int32FromGTestEnv() returns the default value when the // Tests that Int32FromGTestEnv() returns the default value when the
// environment variable overflows as an Int32. // environment variable overflows as an Int32.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) { TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
printf("(expecting 2 warnings)\n"); printf("(expecting 2 warnings)\n");
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
EXPECT_EQ(20, Int32FromGTestEnv("temp", 20)); EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
skipping to change at line 1765 skipping to change at line 1742
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) { TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
printf("(expecting 2 warnings)\n"); printf("(expecting 2 warnings)\n");
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
EXPECT_EQ(40, Int32FromGTestEnv("temp", 40)); EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
EXPECT_EQ(50, Int32FromGTestEnv("temp", 50)); EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
} }
# endif // !defined(GTEST_GET_INT32_FROM_ENV_) #endif // !defined(GTEST_GET_INT32_FROM_ENV_)
// Tests that Int32FromGTestEnv() parses and returns the value of the // Tests that Int32FromGTestEnv() parses and returns the value of the
// environment variable when it represents a valid decimal integer in // environment variable when it represents a valid decimal integer in
// the range of an Int32. // the range of an Int32.
TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) { TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
EXPECT_EQ(123, Int32FromGTestEnv("temp", 0)); EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0)); EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
} }
#endif // !GTEST_OS_WINDOWS_MOBILE #endif // !GTEST_OS_WINDOWS_MOBILE
// Tests ParseInt32Flag(). // Tests ParseFlag().
// Tests that ParseInt32Flag() returns false and doesn't change the // Tests that ParseInt32Flag() returns false and doesn't change the
// output value when the flag has wrong format // output value when the flag has wrong format
TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
int32_t value = 123; int32_t value = 123;
EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value)); EXPECT_FALSE(ParseFlag("--a=100", "b", &value));
EXPECT_EQ(123, value); EXPECT_EQ(123, value);
EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value)); EXPECT_FALSE(ParseFlag("a=100", "a", &value));
EXPECT_EQ(123, value); EXPECT_EQ(123, value);
} }
// Tests that ParseInt32Flag() returns false and doesn't change the // Tests that ParseFlag() returns false and doesn't change the
// output value when the flag overflows as an Int32. // output value when the flag overflows as an Int32.
TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
printf("(expecting 2 warnings)\n"); printf("(expecting 2 warnings)\n");
int32_t value = 123; int32_t value = 123;
EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value)); EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value));
EXPECT_EQ(123, value); EXPECT_EQ(123, value);
EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value)); EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value));
EXPECT_EQ(123, value); EXPECT_EQ(123, value);
} }
// Tests that ParseInt32Flag() returns false and doesn't change the // Tests that ParseInt32Flag() returns false and doesn't change the
// output value when the flag does not represent a valid decimal // output value when the flag does not represent a valid decimal
// integer. // integer.
TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
printf("(expecting 2 warnings)\n"); printf("(expecting 2 warnings)\n");
int32_t value = 123; int32_t value = 123;
EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value)); EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value));
EXPECT_EQ(123, value); EXPECT_EQ(123, value);
EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value)); EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value));
EXPECT_EQ(123, value); EXPECT_EQ(123, value);
} }
// Tests that ParseInt32Flag() parses the value of the flag and // Tests that ParseInt32Flag() parses the value of the flag and
// returns true when the flag represents a valid decimal integer in // returns true when the flag represents a valid decimal integer in
// the range of an Int32. // the range of an Int32.
TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) { TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
int32_t value = 123; int32_t value = 123;
EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
EXPECT_EQ(456, value); EXPECT_EQ(456, value);
EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789", EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
"abc", &value));
EXPECT_EQ(-789, value); EXPECT_EQ(-789, value);
} }
// Tests that Int32FromEnvOrDie() parses the value of the var or // Tests that Int32FromEnvOrDie() parses the value of the var or
// returns the correct default. // returns the correct default.
// Environment variables are not supported on Windows CE. // Environment variables are not supported on Windows CE.
#if !GTEST_OS_WINDOWS_MOBILE #if !GTEST_OS_WINDOWS_MOBILE
TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
skipping to change at line 1850 skipping to change at line 1826
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
} }
#endif // !GTEST_OS_WINDOWS_MOBILE #endif // !GTEST_OS_WINDOWS_MOBILE
// Tests that Int32FromEnvOrDie() aborts with an error message // Tests that Int32FromEnvOrDie() aborts with an error message
// if the variable is not an int32_t. // if the variable is not an int32_t.
TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(
Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
".*");
} }
// Tests that Int32FromEnvOrDie() aborts with an error message // Tests that Int32FromEnvOrDie() aborts with an error message
// if the variable cannot be represented by an int32_t. // if the variable cannot be represented by an int32_t.
TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(
Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
".*");
} }
// Tests that ShouldRunTestOnShard() selects all tests // Tests that ShouldRunTestOnShard() selects all tests
// where there is 1 shard. // where there is 1 shard.
TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) { TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
skipping to change at line 1967 skipping to change at line 1941
// Check partitioning: each test should be on exactly 1 shard. // Check partitioning: each test should be on exactly 1 shard.
for (int test_id = 0; test_id < num_tests; test_id++) { for (int test_id = 0; test_id < num_tests; test_id++) {
int prev_selected_shard_index = -1; int prev_selected_shard_index = -1;
for (int shard_index = 0; shard_index < num_shards; shard_index++) { for (int shard_index = 0; shard_index < num_shards; shard_index++) {
if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) { if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
if (prev_selected_shard_index < 0) { if (prev_selected_shard_index < 0) {
prev_selected_shard_index = shard_index; prev_selected_shard_index = shard_index;
} else { } else {
ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and " ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
<< shard_index << " are both selected to run test " << test_id; << shard_index << " are both selected to run test "
<< test_id;
} }
} }
} }
} }
// Check balance: This is not required by the sharding protocol, but is a // Check balance: This is not required by the sharding protocol, but is a
// desirable property for performance. // desirable property for performance.
for (int shard_index = 0; shard_index < num_shards; shard_index++) { for (int shard_index = 0; shard_index < num_shards; shard_index++) {
int num_tests_on_shard = 0; int num_tests_on_shard = 0;
for (int test_id = 0; test_id < num_tests; test_id++) { for (int test_id = 0; test_id < num_tests; test_id++) {
num_tests_on_shard += num_tests_on_shard +=
ShouldRunTestOnShard(num_shards, shard_index, test_id); ShouldRunTestOnShard(num_shards, shard_index, test_id);
} }
EXPECT_GE(num_tests_on_shard, num_tests / num_shards); EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
} }
} }
// For the same reason we are not explicitly testing everything in the // For the same reason we are not explicitly testing everything in the
// Test class, there are no separate tests for the following classes // Test class, there are no separate tests for the following classes
// (except for some trivial cases): // (except for some trivial cases):
// //
// TestSuite, UnitTest, UnitTestResultPrinter. // TestSuite, UnitTest, UnitTestResultPrinter.
skipping to change at line 2011 skipping to change at line 1986
EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp()); EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis()); EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
} }
// When a property using a reserved key is supplied to this function, it // When a property using a reserved key is supplied to this function, it
// tests that a non-fatal failure is added, a fatal failure is not added, // tests that a non-fatal failure is added, a fatal failure is not added,
// and that the property is not recorded. // and that the property is not recorded.
void ExpectNonFatalFailureRecordingPropertyWithReservedKey( void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
const TestResult& test_result, const char* key) { const TestResult& test_result, const char* key) {
EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key"); EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key ASSERT_EQ(0, test_result.test_property_count())
<< "' recorded unexpectedly."; << "Property for key '" << key << "' recorded unexpectedly.";
} }
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
const char* key) { const char* key) {
const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(test_info != nullptr); ASSERT_TRUE(test_info != nullptr);
ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(), ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
key); key);
} }
skipping to change at line 2039 skipping to change at line 2014
test_suite->ad_hoc_test_result(), key); test_suite->ad_hoc_test_result(), key);
} }
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
const char* key) { const char* key) {
ExpectNonFatalFailureRecordingPropertyWithReservedKey( ExpectNonFatalFailureRecordingPropertyWithReservedKey(
UnitTest::GetInstance()->ad_hoc_test_result(), key); UnitTest::GetInstance()->ad_hoc_test_result(), key);
} }
// Tests that property recording functions in UnitTest outside of tests // Tests that property recording functions in UnitTest outside of tests
// functions correcly. Creating a separate instance of UnitTest ensures it // functions correctly. Creating a separate instance of UnitTest ensures it
// is in a state similar to the UnitTest's singleton's between tests. // is in a state similar to the UnitTest's singleton's between tests.
class UnitTestRecordPropertyTest : class UnitTestRecordPropertyTest
public testing::internal::UnitTestRecordPropertyTestHelper { : public testing::internal::UnitTestRecordPropertyTestHelper {
public: public:
static void SetUpTestSuite() { static void SetUpTestSuite() {
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"disabled"); "disabled");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"errors"); "errors");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"failures"); "failures");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"name"); "name");
skipping to change at line 2081 skipping to change at line 2056
}; };
// Tests TestResult has the expected property when added. // Tests TestResult has the expected property when added.
TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) { TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
UnitTestRecordProperty("key_1", "1"); UnitTestRecordProperty("key_1", "1");
ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count()); ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
EXPECT_STREQ("key_1", EXPECT_STREQ("key_1",
unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
EXPECT_STREQ("1", EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
} }
// Tests TestResult has multiple properties when added. // Tests TestResult has multiple properties when added.
TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) { TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
UnitTestRecordProperty("key_1", "1"); UnitTestRecordProperty("key_1", "1");
UnitTestRecordProperty("key_2", "2"); UnitTestRecordProperty("key_2", "2");
ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count()); ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
EXPECT_STREQ("key_1", EXPECT_STREQ("key_1",
skipping to change at line 2123 skipping to change at line 2097
unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
EXPECT_STREQ("key_2", EXPECT_STREQ("key_2",
unit_test_.ad_hoc_test_result().GetTestProperty(1).key()); unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
EXPECT_STREQ("22", EXPECT_STREQ("22",
unit_test_.ad_hoc_test_result().GetTestProperty(1).value()); unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
} }
TEST_F(UnitTestRecordPropertyTest, TEST_F(UnitTestRecordPropertyTest,
AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) { AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("name");
"name");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"value_param"); "value_param");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"type_param"); "type_param");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("status");
"status"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("time");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"time");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"classname"); "classname");
} }
TEST_F(UnitTestRecordPropertyTest, TEST_F(UnitTestRecordPropertyTest,
AddRecordWithReservedKeysGeneratesCorrectPropertyList) { AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
Test::RecordProperty("name", "1"), Test::RecordProperty("name", "1"),
"'classname', 'name', 'status', 'time', 'type_param', 'value_param'," "'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
" 'file', and 'line' are reserved"); " 'file', and 'line' are reserved");
skipping to change at line 2180 skipping to change at line 2151
// This group of tests is for predicate assertions (ASSERT_PRED*, etc) // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
// of various arities. They do not attempt to be exhaustive. Rather, // of various arities. They do not attempt to be exhaustive. Rather,
// view them as smoke tests that can be easily reviewed and verified. // view them as smoke tests that can be easily reviewed and verified.
// A more complete set of tests for predicate assertions can be found // A more complete set of tests for predicate assertions can be found
// in gtest_pred_impl_unittest.cc. // in gtest_pred_impl_unittest.cc.
// First, some predicates and predicate-formatters needed by the tests. // First, some predicates and predicate-formatters needed by the tests.
// Returns true if and only if the argument is an even number. // Returns true if and only if the argument is an even number.
bool IsEven(int n) { bool IsEven(int n) { return (n % 2) == 0; }
return (n % 2) == 0;
}
// A functor that returns true if and only if the argument is an even number. // A functor that returns true if and only if the argument is an even number.
struct IsEvenFunctor { struct IsEvenFunctor {
bool operator()(int n) { return IsEven(n); } bool operator()(int n) { return IsEven(n); }
}; };
// A predicate-formatter function that asserts the argument is an even // A predicate-formatter function that asserts the argument is an even
// number. // number.
AssertionResult AssertIsEven(const char* expr, int n) { AssertionResult AssertIsEven(const char* expr, int n) {
if (IsEven(n)) { if (IsEven(n)) {
skipping to change at line 2229 skipping to change at line 2198
// A predicate-formatter functor that asserts the argument is an even // A predicate-formatter functor that asserts the argument is an even
// number. // number.
struct AssertIsEvenFunctor { struct AssertIsEvenFunctor {
AssertionResult operator()(const char* expr, int n) { AssertionResult operator()(const char* expr, int n) {
return AssertIsEven(expr, n); return AssertIsEven(expr, n);
} }
}; };
// Returns true if and only if the sum of the arguments is an even number. // Returns true if and only if the sum of the arguments is an even number.
bool SumIsEven2(int n1, int n2) { bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); }
return IsEven(n1 + n2);
}
// A functor that returns true if and only if the sum of the arguments is an // A functor that returns true if and only if the sum of the arguments is an
// even number. // even number.
struct SumIsEven3Functor { struct SumIsEven3Functor {
bool operator()(int n1, int n2, int n3) { bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); }
return IsEven(n1 + n2 + n3);
}
}; };
// A predicate-formatter function that asserts the sum of the // A predicate-formatter function that asserts the sum of the
// arguments is an even number. // arguments is an even number.
AssertionResult AssertSumIsEven4( AssertionResult AssertSumIsEven4(const char* e1, const char* e2, const char* e3,
const char* e1, const char* e2, const char* e3, const char* e4, const char* e4, int n1, int n2, int n3,
int n1, int n2, int n3, int n4) { int n4) {
const int sum = n1 + n2 + n3 + n4; const int sum = n1 + n2 + n3 + n4;
if (IsEven(sum)) { if (IsEven(sum)) {
return AssertionSuccess(); return AssertionSuccess();
} }
Message msg; Message msg;
msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + "
<< " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum
<< ") evaluates to " << sum << ", which is not even."; << ", which is not even.";
return AssertionFailure(msg); return AssertionFailure(msg);
} }
// A predicate-formatter functor that asserts the sum of the arguments // A predicate-formatter functor that asserts the sum of the arguments
// is an even number. // is an even number.
struct AssertSumIsEven5Functor { struct AssertSumIsEven5Functor {
AssertionResult operator()( AssertionResult operator()(const char* e1, const char* e2, const char* e3,
const char* e1, const char* e2, const char* e3, const char* e4, const char* e4, const char* e5, int n1, int n2,
const char* e5, int n1, int n2, int n3, int n4, int n5) { int n3, int n4, int n5) {
const int sum = n1 + n2 + n3 + n4 + n5; const int sum = n1 + n2 + n3 + n4 + n5;
if (IsEven(sum)) { if (IsEven(sum)) {
return AssertionSuccess(); return AssertionSuccess();
} }
Message msg; Message msg;
msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
<< " (" << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + "
<< n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5 << n5 << ") evaluates to " << sum << ", which is not even.";
<< ") evaluates to " << sum << ", which is not even.";
return AssertionFailure(msg); return AssertionFailure(msg);
} }
}; };
// Tests unary predicate assertions. // Tests unary predicate assertions.
// Tests unary predicate assertions that don't use a custom formatter. // Tests unary predicate assertions that don't use a custom formatter.
TEST(Pred1Test, WithoutFormat) { TEST(Pred1Test, WithoutFormat) {
// Success cases. // Success cases.
EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!"; EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
ASSERT_PRED1(IsEven, 4); ASSERT_PRED1(IsEven, 4);
// Failure cases. // Failure cases.
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_PRED1(IsEven, 5) << "This failure is expected."; { // NOLINT
}, "This failure is expected."); EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), },
"evaluates to false"); "This failure is expected.");
EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false");
} }
// Tests unary predicate assertions that use a custom formatter. // Tests unary predicate assertions that use a custom formatter.
TEST(Pred1Test, WithFormat) { TEST(Pred1Test, WithFormat) {
// Success cases. // Success cases.
EXPECT_PRED_FORMAT1(AssertIsEven, 2); EXPECT_PRED_FORMAT1(AssertIsEven, 2);
ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4) ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
<< "This failure is UNEXPECTED!"; << "This failure is UNEXPECTED!";
// Failure cases. // Failure cases.
const int n = 5; const int n = 5;
EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n), EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
"n evaluates to 5, which is not even."); "n evaluates to 5, which is not even.");
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected."; { // NOLINT
}, "This failure is expected."); ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
},
"This failure is expected.");
} }
// Tests that unary predicate assertions evaluates their arguments // Tests that unary predicate assertions evaluates their arguments
// exactly once. // exactly once.
TEST(Pred1Test, SingleEvaluationOnFailure) { TEST(Pred1Test, SingleEvaluationOnFailure) {
// A success case. // A success case.
static int n = 0; static int n = 0;
EXPECT_PRED1(IsEven, n++); EXPECT_PRED1(IsEven, n++);
EXPECT_EQ(1, n) << "The argument is not evaluated exactly once."; EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
// A failure case. // A failure case.
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++) { // NOLINT
<< "This failure is expected."; ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
}, "This failure is expected."); << "This failure is expected.";
},
"This failure is expected.");
EXPECT_EQ(2, n) << "The argument is not evaluated exactly once."; EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
} }
// Tests predicate assertions whose arity is >= 2. // Tests predicate assertions whose arity is >= 2.
// Tests predicate assertions that don't use a custom formatter. // Tests predicate assertions that don't use a custom formatter.
TEST(PredTest, WithoutFormat) { TEST(PredTest, WithoutFormat) {
// Success cases. // Success cases.
ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!"; ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8); EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
// Failure cases. // Failure cases.
const int n1 = 1; const int n1 = 1;
const int n2 = 2; const int n2 = 2;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected."; { // NOLINT
}, "This failure is expected."); EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
EXPECT_FATAL_FAILURE({ // NOLINT },
ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4); "This failure is expected.");
}, "evaluates to false"); EXPECT_FATAL_FAILURE(
{ // NOLINT
ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
},
"evaluates to false");
} }
// Tests predicate assertions that use a custom formatter. // Tests predicate assertions that use a custom formatter.
TEST(PredTest, WithFormat) { TEST(PredTest, WithFormat) {
// Success cases. // Success cases.
ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) << ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10)
"This failure is UNEXPECTED!"; << "This failure is UNEXPECTED!";
EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10); EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
// Failure cases. // Failure cases.
const int n1 = 1; const int n1 = 1;
const int n2 = 2; const int n2 = 2;
const int n3 = 4; const int n3 = 4;
const int n4 = 6; const int n4 = 6;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4); { // NOLINT
}, "evaluates to 13, which is not even."); EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
EXPECT_FATAL_FAILURE({ // NOLINT },
ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8) "evaluates to 13, which is not even.");
<< "This failure is expected."; EXPECT_FATAL_FAILURE(
}, "This failure is expected."); { // NOLINT
ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
<< "This failure is expected.";
},
"This failure is expected.");
} }
// Tests that predicate assertions evaluates their arguments // Tests that predicate assertions evaluates their arguments
// exactly once. // exactly once.
TEST(PredTest, SingleEvaluationOnFailure) { TEST(PredTest, SingleEvaluationOnFailure) {
// A success case. // A success case.
int n1 = 0; int n1 = 0;
int n2 = 0; int n2 = 0;
EXPECT_PRED2(SumIsEven2, n1++, n2++); EXPECT_PRED2(SumIsEven2, n1++, n2++);
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
// Another success case. // Another success case.
n1 = n2 = 0; n1 = n2 = 0;
int n3 = 0; int n3 = 0;
int n4 = 0; int n4 = 0;
int n5 = 0; int n5 = 0;
ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++)
n1++, n2++, n3++, n4++, n5++) << "This failure is UNEXPECTED!";
<< "This failure is UNEXPECTED!";
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once."; EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
// A failure case. // A failure case.
n1 = n2 = n3 = 0; n1 = n2 = n3 = 0;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++) { // NOLINT
<< "This failure is expected."; EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
}, "This failure is expected."); << "This failure is expected.";
},
"This failure is expected.");
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
// Another failure case. // Another failure case.
n1 = n2 = n3 = n4 = 0; n1 = n2 = n3 = n4 = 0;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++); { // NOLINT
}, "evaluates to 1, which is not even."); EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
},
"evaluates to 1, which is not even.");
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
} }
// Test predicate assertions for sets // Test predicate assertions for sets
TEST(PredTest, ExpectPredEvalFailure) { TEST(PredTest, ExpectPredEvalFailure) {
std::set<int> set_a = {2, 1, 3, 4, 5}; std::set<int> set_a = {2, 1, 3, 4, 5};
std::set<int> set_b = {0, 4, 8}; std::set<int> set_b = {0, 4, 8};
const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; }; const auto compare_sets = [](std::set<int>, std::set<int>) { return false; };
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
EXPECT_PRED2(compare_sets, set_a, set_b), EXPECT_PRED2(compare_sets, set_a, set_b),
"compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates " "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
"to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }"); "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
} }
// Some helper functions for testing using overloaded/template // Some helper functions for testing using overloaded/template
// functions with ASSERT_PREDn and EXPECT_PREDn. // functions with ASSERT_PREDn and EXPECT_PREDn.
bool IsPositive(double x) { bool IsPositive(double x) { return x > 0; }
return x > 0;
}
template <typename T> template <typename T>
bool IsNegative(T x) { bool IsNegative(T x) {
return x < 0; return x < 0;
} }
template <typename T1, typename T2> template <typename T1, typename T2>
bool GreaterThan(T1 x1, T2 x2) { bool GreaterThan(T1 x1, T2 x2) {
return x1 > x2; return x1 > x2;
} }
// Tests that overloaded functions can be used in *_PRED* as long as // Tests that overloaded functions can be used in *_PRED* as long as
// their types are explicitly specified. // their types are explicitly specified.
TEST(PredicateAssertionTest, AcceptsOverloadedFunction) { TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
// C++Builder requires C-style casts rather than static_cast. // C++Builder requires C-style casts rather than static_cast.
EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
} }
// Tests that template functions can be used in *_PRED* as long as // Tests that template functions can be used in *_PRED* as long as
// their types are explicitly specified. // their types are explicitly specified.
TEST(PredicateAssertionTest, AcceptsTemplateFunction) { TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
EXPECT_PRED1(IsNegative<int>, -5); EXPECT_PRED1(IsNegative<int>, -5);
// Makes sure that we can handle templates with more than one // Makes sure that we can handle templates with more than one
// parameter. // parameter.
ASSERT_PRED2((GreaterThan<int, int>), 5, 0); ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
} }
// Some helper functions for testing using overloaded/template // Some helper functions for testing using overloaded/template
// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn. // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
AssertionResult IsPositiveFormat(const char* /* expr */, int n) { AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
return n > 0 ? AssertionSuccess() : return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
AssertionFailure(Message() << "Failure");
} }
AssertionResult IsPositiveFormat(const char* /* expr */, double x) { AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
return x > 0 ? AssertionSuccess() : return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
AssertionFailure(Message() << "Failure");
} }
template <typename T> template <typename T>
AssertionResult IsNegativeFormat(const char* /* expr */, T x) { AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
return x < 0 ? AssertionSuccess() : return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
AssertionFailure(Message() << "Failure");
} }
template <typename T1, typename T2> template <typename T1, typename T2>
AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */, AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
const T1& x1, const T2& x2) { const T1& x1, const T2& x2) {
return x1 == x2 ? AssertionSuccess() : return x1 == x2 ? AssertionSuccess()
AssertionFailure(Message() << "Failure"); : AssertionFailure(Message() << "Failure");
} }
// Tests that overloaded functions can be used in *_PRED_FORMAT* // Tests that overloaded functions can be used in *_PRED_FORMAT*
// without explicitly specifying their types. // without explicitly specifying their types.
TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) { TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
EXPECT_PRED_FORMAT1(IsPositiveFormat, 5); EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0); ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
} }
// Tests that template functions can be used in *_PRED_FORMAT* without // Tests that template functions can be used in *_PRED_FORMAT* without
// explicitly specifying their types. // explicitly specifying their types.
TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) { TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
EXPECT_PRED_FORMAT1(IsNegativeFormat, -5); EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3); ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
} }
// Tests string assertions. // Tests string assertions.
// Tests ASSERT_STREQ with non-NULL arguments. // Tests ASSERT_STREQ with non-NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ) { TEST(StringAssertionTest, ASSERT_STREQ) {
const char * const p1 = "good"; const char* const p1 = "good";
ASSERT_STREQ(p1, p1); ASSERT_STREQ(p1, p1);
// Let p2 have the same content as p1, but be at a different address. // Let p2 have the same content as p1, but be at a different address.
const char p2[] = "good"; const char p2[] = "good";
ASSERT_STREQ(p1, p2); ASSERT_STREQ(p1, p2);
EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), " \"bad\"\n \"good\"");
" \"bad\"\n \"good\"");
} }
// Tests ASSERT_STREQ with NULL arguments. // Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ_Null) { TEST(StringAssertionTest, ASSERT_STREQ_Null) {
ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr); ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null"); EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
} }
// Tests ASSERT_STREQ with NULL arguments. // Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ_Null2) { TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
skipping to change at line 2531 skipping to change at line 2505
// Tests ASSERT_STRNE. // Tests ASSERT_STRNE.
TEST(StringAssertionTest, ASSERT_STRNE) { TEST(StringAssertionTest, ASSERT_STRNE) {
ASSERT_STRNE("hi", "Hi"); ASSERT_STRNE("hi", "Hi");
ASSERT_STRNE("Hi", nullptr); ASSERT_STRNE("Hi", nullptr);
ASSERT_STRNE(nullptr, "Hi"); ASSERT_STRNE(nullptr, "Hi");
ASSERT_STRNE("", nullptr); ASSERT_STRNE("", nullptr);
ASSERT_STRNE(nullptr, ""); ASSERT_STRNE(nullptr, "");
ASSERT_STRNE("", "Hi"); ASSERT_STRNE("", "Hi");
ASSERT_STRNE("Hi", ""); ASSERT_STRNE("Hi", "");
EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\"");
"\"Hi\" vs \"Hi\"");
} }
// Tests ASSERT_STRCASEEQ. // Tests ASSERT_STRCASEEQ.
TEST(StringAssertionTest, ASSERT_STRCASEEQ) { TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
ASSERT_STRCASEEQ("hi", "Hi"); ASSERT_STRCASEEQ("hi", "Hi");
ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr); ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
ASSERT_STRCASEEQ("", ""); ASSERT_STRCASEEQ("", "");
EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "Ignoring case");
"Ignoring case");
} }
// Tests ASSERT_STRCASENE. // Tests ASSERT_STRCASENE.
TEST(StringAssertionTest, ASSERT_STRCASENE) { TEST(StringAssertionTest, ASSERT_STRCASENE) {
ASSERT_STRCASENE("hi1", "Hi2"); ASSERT_STRCASENE("hi1", "Hi2");
ASSERT_STRCASENE("Hi", nullptr); ASSERT_STRCASENE("Hi", nullptr);
ASSERT_STRCASENE(nullptr, "Hi"); ASSERT_STRCASENE(nullptr, "Hi");
ASSERT_STRCASENE("", nullptr); ASSERT_STRCASENE("", nullptr);
ASSERT_STRCASENE(nullptr, ""); ASSERT_STRCASENE(nullptr, "");
ASSERT_STRCASENE("", "Hi"); ASSERT_STRCASENE("", "Hi");
ASSERT_STRCASENE("Hi", ""); ASSERT_STRCASENE("Hi", "");
EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)");
"(ignoring case)");
} }
// Tests *_STREQ on wide strings. // Tests *_STREQ on wide strings.
TEST(StringAssertionTest, STREQ_Wide) { TEST(StringAssertionTest, STREQ_Wide) {
// NULL strings. // NULL strings.
ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr); ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
// Empty strings. // Empty strings.
ASSERT_STREQ(L"", L""); ASSERT_STREQ(L"", L"");
// Non-null vs NULL. // Non-null vs NULL.
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null"); EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
// Equal strings. // Equal strings.
EXPECT_STREQ(L"Hi", L"Hi"); EXPECT_STREQ(L"Hi", L"Hi");
// Unequal strings. // Unequal strings.
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc");
"Abc");
// Strings containing wide characters. // Strings containing wide characters.
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc");
"abc");
// The streaming variation. // The streaming variation.
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure"; { // NOLINT
}, "Expected failure"); EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
},
"Expected failure");
} }
// Tests *_STRNE on wide strings. // Tests *_STRNE on wide strings.
TEST(StringAssertionTest, STRNE_Wide) { TEST(StringAssertionTest, STRNE_Wide) {
// NULL strings. // NULL strings.
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
{ // NOLINT { // NOLINT
EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr); EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
}, },
""); "");
// Empty strings. // Empty strings.
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\"");
"L\"\"");
// Non-null vs NULL. // Non-null vs NULL.
ASSERT_STRNE(L"non-null", nullptr); ASSERT_STRNE(L"non-null", nullptr);
// Equal strings. // Equal strings.
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\"");
"L\"Hi\"");
// Unequal strings. // Unequal strings.
EXPECT_STRNE(L"abc", L"Abc"); EXPECT_STRNE(L"abc", L"Abc");
// Strings containing wide characters. // Strings containing wide characters.
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc");
"abc");
// The streaming variation. // The streaming variation.
ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen"; ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
} }
// Tests for ::testing::IsSubstring(). // Tests for ::testing::IsSubstring().
// Tests that IsSubstring() returns the correct result when the input // Tests that IsSubstring() returns the correct result when the input
// argument type is const char*. // argument type is const char*.
TEST(IsSubstringTest, ReturnsCorrectResultForCString) { TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
skipping to change at line 2645 skipping to change at line 2613
EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack")); EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
EXPECT_TRUE( EXPECT_TRUE(
IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr)); IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles")); EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
} }
// Tests that IsSubstring() generates the correct message when the input // Tests that IsSubstring() generates the correct message when the input
// argument type is const char*. // argument type is const char*.
TEST(IsSubstringTest, GeneratesCorrectMessageForCString) { TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
EXPECT_STREQ("Value of: needle_expr\n" EXPECT_STREQ(
" Actual: \"needle\"\n" "Value of: needle_expr\n"
"Expected: a substring of haystack_expr\n" " Actual: \"needle\"\n"
"Which is: \"haystack\"", "Expected: a substring of haystack_expr\n"
IsSubstring("needle_expr", "haystack_expr", "Which is: \"haystack\"",
"needle", "haystack").failure_message()); IsSubstring("needle_expr", "haystack_expr", "needle", "haystack")
.failure_message());
} }
// Tests that IsSubstring returns the correct result when the input // Tests that IsSubstring returns the correct result when the input
// argument type is ::std::string. // argument type is ::std::string.
TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) { TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob")); EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world"))); EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
} }
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
// Tests that IsSubstring returns the correct result when the input // Tests that IsSubstring returns the correct result when the input
// argument type is ::std::wstring. // argument type is ::std::wstring.
TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) { TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles")); EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack"))); EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
} }
// Tests that IsSubstring() generates the correct message when the input // Tests that IsSubstring() generates the correct message when the input
// argument type is ::std::wstring. // argument type is ::std::wstring.
TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) { TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
EXPECT_STREQ("Value of: needle_expr\n" EXPECT_STREQ(
" Actual: L\"needle\"\n" "Value of: needle_expr\n"
"Expected: a substring of haystack_expr\n" " Actual: L\"needle\"\n"
"Which is: L\"haystack\"", "Expected: a substring of haystack_expr\n"
IsSubstring( "Which is: L\"haystack\"",
"needle_expr", "haystack_expr", IsSubstring("needle_expr", "haystack_expr", ::std::wstring(L"needle"),
::std::wstring(L"needle"), L"haystack").failure_message()); L"haystack")
.failure_message());
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
// Tests for ::testing::IsNotSubstring(). // Tests for ::testing::IsNotSubstring().
// Tests that IsNotSubstring() returns the correct result when the input // Tests that IsNotSubstring() returns the correct result when the input
// argument type is const char*. // argument type is const char*.
TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) { TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack")); EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
skipping to change at line 2701 skipping to change at line 2671
// Tests that IsNotSubstring() returns the correct result when the input // Tests that IsNotSubstring() returns the correct result when the input
// argument type is const wchar_t*. // argument type is const wchar_t*.
TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) { TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack")); EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles")); EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
} }
// Tests that IsNotSubstring() generates the correct message when the input // Tests that IsNotSubstring() generates the correct message when the input
// argument type is const wchar_t*. // argument type is const wchar_t*.
TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) { TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
EXPECT_STREQ("Value of: needle_expr\n" EXPECT_STREQ(
" Actual: L\"needle\"\n" "Value of: needle_expr\n"
"Expected: not a substring of haystack_expr\n" " Actual: L\"needle\"\n"
"Which is: L\"two needles\"", "Expected: not a substring of haystack_expr\n"
IsNotSubstring( "Which is: L\"two needles\"",
"needle_expr", "haystack_expr", IsNotSubstring("needle_expr", "haystack_expr", L"needle", L"two needles")
L"needle", L"two needles").failure_message()); .failure_message());
} }
// Tests that IsNotSubstring returns the correct result when the input // Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::string. // argument type is ::std::string.
TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) { TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob")); EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world"))); EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
} }
// Tests that IsNotSubstring() generates the correct message when the input // Tests that IsNotSubstring() generates the correct message when the input
// argument type is ::std::string. // argument type is ::std::string.
TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) { TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
EXPECT_STREQ("Value of: needle_expr\n" EXPECT_STREQ(
" Actual: \"needle\"\n" "Value of: needle_expr\n"
"Expected: not a substring of haystack_expr\n" " Actual: \"needle\"\n"
"Which is: \"two needles\"", "Expected: not a substring of haystack_expr\n"
IsNotSubstring( "Which is: \"two needles\"",
"needle_expr", "haystack_expr", IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"),
::std::string("needle"), "two needles").failure_message()); "two needles")
.failure_message());
} }
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
// Tests that IsNotSubstring returns the correct result when the input // Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::wstring. // argument type is ::std::wstring.
TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) { TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
EXPECT_FALSE( EXPECT_FALSE(
IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles")); IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack"))); EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
skipping to change at line 2773 skipping to change at line 2744
typedef typename testing::internal::FloatingPoint<RawType> Floating; typedef typename testing::internal::FloatingPoint<RawType> Floating;
typedef typename Floating::Bits Bits; typedef typename Floating::Bits Bits;
void SetUp() override { void SetUp() override {
const uint32_t max_ulps = Floating::kMaxUlps; const uint32_t max_ulps = Floating::kMaxUlps;
// The bits that represent 0.0. // The bits that represent 0.0.
const Bits zero_bits = Floating(0).bits(); const Bits zero_bits = Floating(0).bits();
// Makes some numbers close to 0.0. // Makes some numbers close to 0.0.
values_.close_to_positive_zero = Floating::ReinterpretBits( values_.close_to_positive_zero =
zero_bits + max_ulps/2); Floating::ReinterpretBits(zero_bits + max_ulps / 2);
values_.close_to_negative_zero = -Floating::ReinterpretBits( values_.close_to_negative_zero =
zero_bits + max_ulps - max_ulps/2); -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2);
values_.further_from_negative_zero = -Floating::ReinterpretBits( values_.further_from_negative_zero =
zero_bits + max_ulps + 1 - max_ulps/2); -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2);
// The bits that represent 1.0. // The bits that represent 1.0.
const Bits one_bits = Floating(1).bits(); const Bits one_bits = Floating(1).bits();
// Makes some numbers close to 1.0. // Makes some numbers close to 1.0.
values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps); values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
values_.further_from_one = Floating::ReinterpretBits( values_.further_from_one =
one_bits + max_ulps + 1); Floating::ReinterpretBits(one_bits + max_ulps + 1);
// +infinity. // +infinity.
values_.infinity = Floating::Infinity(); values_.infinity = Floating::Infinity();
// The bits that represent +infinity. // The bits that represent +infinity.
const Bits infinity_bits = Floating(values_.infinity).bits(); const Bits infinity_bits = Floating(values_.infinity).bits();
// Makes some numbers close to infinity. // Makes some numbers close to infinity.
values_.close_to_infinity = Floating::ReinterpretBits( values_.close_to_infinity =
infinity_bits - max_ulps); Floating::ReinterpretBits(infinity_bits - max_ulps);
values_.further_from_infinity = Floating::ReinterpretBits( values_.further_from_infinity =
infinity_bits - max_ulps - 1); Floating::ReinterpretBits(infinity_bits - max_ulps - 1);
// Makes some NAN's. Sets the most significant bit of the fraction so that // Makes some NAN's. Sets the most significant bit of the fraction so that
// our NaN's are quiet; trying to process a signaling NaN would raise an // our NaN's are quiet; trying to process a signaling NaN would raise an
// exception if our environment enables floating point exceptions. // exception if our environment enables floating point exceptions.
values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask values_.nan1 = Floating::ReinterpretBits(
| (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1); Floating::kExponentBitMask |
values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
| (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200); values_.nan2 = Floating::ReinterpretBits(
Floating::kExponentBitMask |
(static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
} }
void TestSize() { void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); }
EXPECT_EQ(sizeof(RawType), sizeof(Bits));
}
static TestValues values_; static TestValues values_;
}; };
template <typename RawType> template <typename RawType>
typename FloatingPointTest<RawType>::TestValues typename FloatingPointTest<RawType>::TestValues
FloatingPointTest<RawType>::values_; FloatingPointTest<RawType>::values_;
// Instantiates FloatingPointTest for testing *_FLOAT_EQ. // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
typedef FloatingPointTest<float> FloatTest; typedef FloatingPointTest<float> FloatTest;
// Tests that the size of Float::Bits matches the size of float. // Tests that the size of Float::Bits matches the size of float.
TEST_F(FloatTest, Size) { TEST_F(FloatTest, Size) { TestSize(); }
TestSize();
}
// Tests comparing with +0 and -0. // Tests comparing with +0 and -0.
TEST_F(FloatTest, Zeros) { TEST_F(FloatTest, Zeros) {
EXPECT_FLOAT_EQ(0.0, -0.0); EXPECT_FLOAT_EQ(0.0, -0.0);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0");
"1.0"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
"1.5");
} }
// Tests comparing numbers close to 0. // Tests comparing numbers close to 0.
// //
// This ensures that *_FLOAT_EQ handles the sign correctly and no // This ensures that *_FLOAT_EQ handles the sign correctly and no
// overflow occurs when comparing numbers whose absolute value is very // overflow occurs when comparing numbers whose absolute value is very
// small. // small.
TEST_F(FloatTest, AlmostZeros) { TEST_F(FloatTest, AlmostZeros) {
// In C++Builder, names within local classes (such as used by // In C++Builder, names within local classes (such as used by
// EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
// scoping class. Use a static local alias as a workaround. // scoping class. Use a static local alias as a workaround.
// We use the assignment syntax since some compilers, like Sun Studio, // We use the assignment syntax since some compilers, like Sun Studio,
// don't allow initializing references using construction syntax // don't allow initializing references using construction syntax
// (parentheses). // (parentheses).
static const FloatTest::TestValues& v = this->values_; static const FloatTest::TestValues& v = this->values_;
EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero); EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero); EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero); EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
ASSERT_FLOAT_EQ(v.close_to_positive_zero, { // NOLINT
v.further_from_negative_zero); ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero);
}, "v.further_from_negative_zero"); },
"v.further_from_negative_zero");
} }
// Tests comparing numbers close to each other. // Tests comparing numbers close to each other.
TEST_F(FloatTest, SmallDiff) { TEST_F(FloatTest, SmallDiff) {
EXPECT_FLOAT_EQ(1.0, values_.close_to_one); EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one), EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
"values_.further_from_one"); "values_.further_from_one");
} }
// Tests comparing numbers far apart. // Tests comparing numbers far apart.
TEST_F(FloatTest, LargeDiff) { TEST_F(FloatTest, LargeDiff) {
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0");
"3.0");
} }
// Tests comparing with infinity. // Tests comparing with infinity.
// //
// This ensures that no overflow occurs when comparing numbers whose // This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large. // absolute value is very large.
TEST_F(FloatTest, Infinity) { TEST_F(FloatTest, Infinity) {
EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity); EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity); EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity), EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
skipping to change at line 2900 skipping to change at line 2867
// Tests that comparing with NAN always returns false. // Tests that comparing with NAN always returns false.
TEST_F(FloatTest, NaN) { TEST_F(FloatTest, NaN) {
// In C++Builder, names within local classes (such as used by // In C++Builder, names within local classes (such as used by
// EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
// scoping class. Use a static local alias as a workaround. // scoping class. Use a static local alias as a workaround.
// We use the assignment syntax since some compilers, like Sun Studio, // We use the assignment syntax since some compilers, like Sun Studio,
// don't allow initializing references using construction syntax // don't allow initializing references using construction syntax
// (parentheses). // (parentheses).
static const FloatTest::TestValues& v = this->values_; static const FloatTest::TestValues& v = this->values_;
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1");
"v.nan1"); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2");
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1");
"v.nan2");
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
"v.nan1");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity");
"v.infinity");
} }
// Tests that *_FLOAT_EQ are reflexive. // Tests that *_FLOAT_EQ are reflexive.
TEST_F(FloatTest, Reflexive) { TEST_F(FloatTest, Reflexive) {
EXPECT_FLOAT_EQ(0.0, 0.0); EXPECT_FLOAT_EQ(0.0, 0.0);
EXPECT_FLOAT_EQ(1.0, 1.0); EXPECT_FLOAT_EQ(1.0, 1.0);
ASSERT_FLOAT_EQ(values_.infinity, values_.infinity); ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
} }
// Tests that *_FLOAT_EQ are commutative. // Tests that *_FLOAT_EQ are commutative.
skipping to change at line 2962 skipping to change at line 2925
EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f); EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
} }
// Tests the cases where FloatLE() should fail. // Tests the cases where FloatLE() should fail.
TEST_F(FloatTest, FloatLEFails) { TEST_F(FloatTest, FloatLEFails) {
// When val1 is greater than val2 by a large margin, // When val1 is greater than val2 by a large margin,
EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f), EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
"(2.0f) <= (1.0f)"); "(2.0f) <= (1.0f)");
// or by a small yet non-negligible margin, // or by a small yet non-negligible margin,
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); { // NOLINT
}, "(values_.further_from_one) <= (1.0f)"); EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
},
EXPECT_NONFATAL_FAILURE({ // NOLINT "(values_.further_from_one) <= (1.0f)");
EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
}, "(values_.nan1) <= (values_.infinity)"); EXPECT_NONFATAL_FAILURE(
EXPECT_NONFATAL_FAILURE({ // NOLINT { // NOLINT
EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1); EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
}, "(-values_.infinity) <= (values_.nan1)"); },
EXPECT_FATAL_FAILURE({ // NOLINT "(values_.nan1) <= (values_.infinity)");
ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); EXPECT_NONFATAL_FAILURE(
}, "(values_.nan1) <= (values_.nan1)"); { // NOLINT
EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
},
"(-values_.infinity) <= (values_.nan1)");
EXPECT_FATAL_FAILURE(
{ // NOLINT
ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
},
"(values_.nan1) <= (values_.nan1)");
} }
// Instantiates FloatingPointTest for testing *_DOUBLE_EQ. // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
typedef FloatingPointTest<double> DoubleTest; typedef FloatingPointTest<double> DoubleTest;
// Tests that the size of Double::Bits matches the size of double. // Tests that the size of Double::Bits matches the size of double.
TEST_F(DoubleTest, Size) { TEST_F(DoubleTest, Size) { TestSize(); }
TestSize();
}
// Tests comparing with +0 and -0. // Tests comparing with +0 and -0.
TEST_F(DoubleTest, Zeros) { TEST_F(DoubleTest, Zeros) {
EXPECT_DOUBLE_EQ(0.0, -0.0); EXPECT_DOUBLE_EQ(0.0, -0.0);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0");
"1.0"); EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0");
EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
"1.0");
} }
// Tests comparing numbers close to 0. // Tests comparing numbers close to 0.
// //
// This ensures that *_DOUBLE_EQ handles the sign correctly and no // This ensures that *_DOUBLE_EQ handles the sign correctly and no
// overflow occurs when comparing numbers whose absolute value is very // overflow occurs when comparing numbers whose absolute value is very
// small. // small.
TEST_F(DoubleTest, AlmostZeros) { TEST_F(DoubleTest, AlmostZeros) {
// In C++Builder, names within local classes (such as used by // In C++Builder, names within local classes (such as used by
// EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
// scoping class. Use a static local alias as a workaround. // scoping class. Use a static local alias as a workaround.
// We use the assignment syntax since some compilers, like Sun Studio, // We use the assignment syntax since some compilers, like Sun Studio,
// don't allow initializing references using construction syntax // don't allow initializing references using construction syntax
// (parentheses). // (parentheses).
static const DoubleTest::TestValues& v = this->values_; static const DoubleTest::TestValues& v = this->values_;
EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero); EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero); EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero); EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
ASSERT_DOUBLE_EQ(v.close_to_positive_zero, { // NOLINT
v.further_from_negative_zero); ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
}, "v.further_from_negative_zero"); v.further_from_negative_zero);
},
"v.further_from_negative_zero");
} }
// Tests comparing numbers close to each other. // Tests comparing numbers close to each other.
TEST_F(DoubleTest, SmallDiff) { TEST_F(DoubleTest, SmallDiff) {
EXPECT_DOUBLE_EQ(1.0, values_.close_to_one); EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one), EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
"values_.further_from_one"); "values_.further_from_one");
} }
// Tests comparing numbers far apart. // Tests comparing numbers far apart.
TEST_F(DoubleTest, LargeDiff) { TEST_F(DoubleTest, LargeDiff) {
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0");
"3.0");
} }
// Tests comparing with infinity. // Tests comparing with infinity.
// //
// This ensures that no overflow occurs when comparing numbers whose // This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large. // absolute value is very large.
TEST_F(DoubleTest, Infinity) { TEST_F(DoubleTest, Infinity) {
EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity); EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity); EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity), EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
skipping to change at line 3052 skipping to change at line 3020
// are only 1 DLP apart. // are only 1 DLP apart.
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1), EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
"values_.nan1"); "values_.nan1");
} }
// Tests that comparing with NAN always returns false. // Tests that comparing with NAN always returns false.
TEST_F(DoubleTest, NaN) { TEST_F(DoubleTest, NaN) {
static const DoubleTest::TestValues& v = this->values_; static const DoubleTest::TestValues& v = this->values_;
// Nokia's STLport crashes if we try to output infinity or NaN. // Nokia's STLport crashes if we try to output infinity or NaN.
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1");
"v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity");
"v.infinity");
} }
// Tests that *_DOUBLE_EQ are reflexive. // Tests that *_DOUBLE_EQ are reflexive.
TEST_F(DoubleTest, Reflexive) { TEST_F(DoubleTest, Reflexive) {
EXPECT_DOUBLE_EQ(0.0, 0.0); EXPECT_DOUBLE_EQ(0.0, 0.0);
EXPECT_DOUBLE_EQ(1.0, 1.0); EXPECT_DOUBLE_EQ(1.0, 1.0);
ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity); ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
} }
// Tests that *_DOUBLE_EQ are commutative. // Tests that *_DOUBLE_EQ are commutative.
skipping to change at line 3118 skipping to change at line 3084
EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0); EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
} }
// Tests the cases where DoubleLE() should fail. // Tests the cases where DoubleLE() should fail.
TEST_F(DoubleTest, DoubleLEFails) { TEST_F(DoubleTest, DoubleLEFails) {
// When val1 is greater than val2 by a large margin, // When val1 is greater than val2 by a large margin,
EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0), EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
"(2.0) <= (1.0)"); "(2.0) <= (1.0)");
// or by a small yet non-negligible margin, // or by a small yet non-negligible margin,
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); { // NOLINT
}, "(values_.further_from_one) <= (1.0)"); EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
},
EXPECT_NONFATAL_FAILURE({ // NOLINT "(values_.further_from_one) <= (1.0)");
EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
}, "(values_.nan1) <= (values_.infinity)"); EXPECT_NONFATAL_FAILURE(
EXPECT_NONFATAL_FAILURE({ // NOLINT { // NOLINT
EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1); EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
}, " (-values_.infinity) <= (values_.nan1)"); },
EXPECT_FATAL_FAILURE({ // NOLINT "(values_.nan1) <= (values_.infinity)");
ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); EXPECT_NONFATAL_FAILURE(
}, "(values_.nan1) <= (values_.nan1)"); { // NOLINT
EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
},
" (-values_.infinity) <= (values_.nan1)");
EXPECT_FATAL_FAILURE(
{ // NOLINT
ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
},
"(values_.nan1) <= (values_.nan1)");
} }
// Verifies that a test or test case whose name starts with DISABLED_ is // Verifies that a test or test case whose name starts with DISABLED_ is
// not run. // not run.
// A test whose name starts with DISABLED_. // A test whose name starts with DISABLED_.
// Should not run. // Should not run.
TEST(DisabledTest, DISABLED_TestShouldNotRun) { TEST(DisabledTest, DISABLED_TestShouldNotRun) {
FAIL() << "Unexpected failure: Disabled test should not be run."; FAIL() << "Unexpected failure: Disabled test should not be run.";
} }
// A test whose name does not start with DISABLED_. // A test whose name does not start with DISABLED_.
// Should run. // Should run.
TEST(DisabledTest, NotDISABLED_TestShouldRun) { TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); }
EXPECT_EQ(1, 1);
}
// A test case whose name starts with DISABLED_. // A test case whose name starts with DISABLED_.
// Should not run. // Should not run.
TEST(DISABLED_TestSuite, TestShouldNotRun) { TEST(DISABLED_TestSuite, TestShouldNotRun) {
FAIL() << "Unexpected failure: Test in disabled test case should not be run."; FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
} }
// A test case and test whose names start with DISABLED_. // A test case and test whose names start with DISABLED_.
// Should not run. // Should not run.
TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) { TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
skipping to change at line 3186 skipping to change at line 3158
FAIL() << "Unexpected failure: Disabled test should not be run."; FAIL() << "Unexpected failure: Disabled test should not be run.";
} }
TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) { TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
FAIL() << "Unexpected failure: Disabled test should not be run."; FAIL() << "Unexpected failure: Disabled test should not be run.";
} }
// Tests that disabled typed tests aren't run. // Tests that disabled typed tests aren't run.
template <typename T> template <typename T>
class TypedTest : public Test { class TypedTest : public Test {};
};
typedef testing::Types<int, double> NumericTypes; typedef testing::Types<int, double> NumericTypes;
TYPED_TEST_SUITE(TypedTest, NumericTypes); TYPED_TEST_SUITE(TypedTest, NumericTypes);
TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
FAIL() << "Unexpected failure: Disabled typed test should not run."; FAIL() << "Unexpected failure: Disabled typed test should not run.";
} }
template <typename T> template <typename T>
class DISABLED_TypedTest : public Test { class DISABLED_TypedTest : public Test {};
};
TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes); TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
FAIL() << "Unexpected failure: Disabled typed test should not run."; FAIL() << "Unexpected failure: Disabled typed test should not run.";
} }
// Tests that disabled type-parameterized tests aren't run. // Tests that disabled type-parameterized tests aren't run.
template <typename T> template <typename T>
class TypedTestP : public Test { class TypedTestP : public Test {};
};
TYPED_TEST_SUITE_P(TypedTestP); TYPED_TEST_SUITE_P(TypedTestP);
TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) { TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
FAIL() << "Unexpected failure: " FAIL() << "Unexpected failure: "
<< "Disabled type-parameterized test should not run."; << "Disabled type-parameterized test should not run.";
} }
REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun); REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes); INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
template <typename T> template <typename T>
class DISABLED_TypedTestP : public Test { class DISABLED_TypedTestP : public Test {};
};
TYPED_TEST_SUITE_P(DISABLED_TypedTestP); TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) { TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
FAIL() << "Unexpected failure: " FAIL() << "Unexpected failure: "
<< "Disabled type-parameterized test should not run."; << "Disabled type-parameterized test should not run.";
} }
REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun); REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes); INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
// Tests that assertion macros evaluate their arguments exactly once. // Tests that assertion macros evaluate their arguments exactly once.
class SingleEvaluationTest : public Test { class SingleEvaluationTest : public Test {
public: // Must be public and not protected due to a bug in g++ 3.4.2. public: // Must be public and not protected due to a bug in g++ 3.4.2.
// This helper function is needed by the FailedASSERT_STREQ test // This helper function is needed by the FailedASSERT_STREQ test
// below. It's public to work around C++Builder's bug with scoping local // below. It's public to work around C++Builder's bug with scoping local
// classes. // classes.
static void CompareAndIncrementCharPtrs() { static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); }
ASSERT_STREQ(p1_++, p2_++);
}
// This helper function is needed by the FailedASSERT_NE test below. It's // This helper function is needed by the FailedASSERT_NE test below. It's
// public to work around C++Builder's bug with scoping local classes. // public to work around C++Builder's bug with scoping local classes.
static void CompareAndIncrementInts() { static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); }
ASSERT_NE(a_++, b_++);
}
protected: protected:
SingleEvaluationTest() { SingleEvaluationTest() {
p1_ = s1_; p1_ = s1_;
p2_ = s2_; p2_ = s2_;
a_ = 0; a_ = 0;
b_ = 0; b_ = 0;
} }
static const char* const s1_; static const char* const s1_;
skipping to change at line 3296 skipping to change at line 3260
} }
// Tests that string assertion arguments are evaluated exactly once. // Tests that string assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ASSERT_STR) { TEST_F(SingleEvaluationTest, ASSERT_STR) {
// successful EXPECT_STRNE // successful EXPECT_STRNE
EXPECT_STRNE(p1_++, p2_++); EXPECT_STRNE(p1_++, p2_++);
EXPECT_EQ(s1_ + 1, p1_); EXPECT_EQ(s1_ + 1, p1_);
EXPECT_EQ(s2_ + 1, p2_); EXPECT_EQ(s2_ + 1, p2_);
// failed EXPECT_STRCASEEQ // failed EXPECT_STRCASEEQ
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "Ignoring case");
"Ignoring case");
EXPECT_EQ(s1_ + 2, p1_); EXPECT_EQ(s1_ + 2, p1_);
EXPECT_EQ(s2_ + 2, p2_); EXPECT_EQ(s2_ + 2, p2_);
} }
// Tests that when ASSERT_NE fails, it evaluates its arguments exactly // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
// once. // once.
TEST_F(SingleEvaluationTest, FailedASSERT_NE) { TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(), EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
"(a_++) != (b_++)"); "(a_++) != (b_++)");
EXPECT_EQ(1, a_); EXPECT_EQ(1, a_);
skipping to change at line 3357 skipping to change at line 3320
#else #else
#define ERROR_DESC "std::runtime_error" #define ERROR_DESC "std::runtime_error"
#endif #endif
#else // GTEST_HAS_RTTI #else // GTEST_HAS_RTTI
#define ERROR_DESC "an std::exception-derived error" #define ERROR_DESC "an std::exception-derived error"
#endif // GTEST_HAS_RTTI #endif // GTEST_HAS_RTTI
void ThrowAnInteger() { void ThrowAnInteger() { throw 1; }
throw 1; void ThrowRuntimeError(const char* what) { throw std::runtime_error(what); }
}
void ThrowRuntimeError(const char* what) {
throw std::runtime_error(what);
}
// Tests that assertion arguments are evaluated exactly once. // Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ExceptionTests) { TEST_F(SingleEvaluationTest, ExceptionTests) {
// successful EXPECT_THROW // successful EXPECT_THROW
EXPECT_THROW({ // NOLINT EXPECT_THROW(
a_++; { // NOLINT
ThrowAnInteger(); a_++;
}, int); ThrowAnInteger();
},
int);
EXPECT_EQ(1, a_); EXPECT_EQ(1, a_);
// failed EXPECT_THROW, throws different // failed EXPECT_THROW, throws different
EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
a_++; { // NOLINT
ThrowAnInteger(); a_++;
}, bool), "throws a different type"); ThrowAnInteger();
},
bool),
"throws a different type");
EXPECT_EQ(2, a_); EXPECT_EQ(2, a_);
// failed EXPECT_THROW, throws runtime error // failed EXPECT_THROW, throws runtime error
EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
a_++; { // NOLINT
ThrowRuntimeError("A description"); a_++;
}, bool), "throws " ERROR_DESC " with description \"A description\""); ThrowRuntimeError("A description");
},
bool),
"throws " ERROR_DESC
" with description \"A description\"");
EXPECT_EQ(3, a_); EXPECT_EQ(3, a_);
// failed EXPECT_THROW, throws nothing // failed EXPECT_THROW, throws nothing
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing"); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
EXPECT_EQ(4, a_); EXPECT_EQ(4, a_);
// successful EXPECT_NO_THROW // successful EXPECT_NO_THROW
EXPECT_NO_THROW(a_++); EXPECT_NO_THROW(a_++);
EXPECT_EQ(5, a_); EXPECT_EQ(5, a_);
// failed EXPECT_NO_THROW // failed EXPECT_NO_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
a_++; a_++;
ThrowAnInteger(); ThrowAnInteger();
}), "it throws"); }),
"it throws");
EXPECT_EQ(6, a_); EXPECT_EQ(6, a_);
// successful EXPECT_ANY_THROW // successful EXPECT_ANY_THROW
EXPECT_ANY_THROW({ // NOLINT EXPECT_ANY_THROW({ // NOLINT
a_++; a_++;
ThrowAnInteger(); ThrowAnInteger();
}); });
EXPECT_EQ(7, a_); EXPECT_EQ(7, a_);
// failed EXPECT_ANY_THROW // failed EXPECT_ANY_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't"); EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
EXPECT_EQ(8, a_); EXPECT_EQ(8, a_);
} }
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE. // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
class NoFatalFailureTest : public Test { class NoFatalFailureTest : public Test {
protected: protected:
void Succeeds() {} void Succeeds() {}
void FailsNonFatal() { void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; }
ADD_FAILURE() << "some non-fatal failure"; void Fails() { FAIL() << "some fatal failure"; }
}
void Fails() {
FAIL() << "some fatal failure";
}
void DoAssertNoFatalFailureOnFails() { void DoAssertNoFatalFailureOnFails() {
ASSERT_NO_FATAL_FAILURE(Fails()); ASSERT_NO_FATAL_FAILURE(Fails());
ADD_FAILURE() << "should not reach here."; ADD_FAILURE() << "should not reach here.";
} }
void DoExpectNoFatalFailureOnFails() { void DoExpectNoFatalFailureOnFails() {
EXPECT_NO_FATAL_FAILURE(Fails()); EXPECT_NO_FATAL_FAILURE(Fails());
ADD_FAILURE() << "other failure"; ADD_FAILURE() << "other failure";
} }
}; };
TEST_F(NoFatalFailureTest, NoFailure) { TEST_F(NoFatalFailureTest, NoFailure) {
EXPECT_NO_FATAL_FAILURE(Succeeds()); EXPECT_NO_FATAL_FAILURE(Succeeds());
ASSERT_NO_FATAL_FAILURE(Succeeds()); ASSERT_NO_FATAL_FAILURE(Succeeds());
} }
TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) { TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
EXPECT_NO_FATAL_FAILURE(FailsNonFatal()), "some non-fatal failure");
"some non-fatal failure"); EXPECT_NONFATAL_FAILURE(ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
EXPECT_NONFATAL_FAILURE( "some non-fatal failure");
ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
"some non-fatal failure");
} }
TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) { TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
TestPartResultArray gtest_failures; TestPartResultArray gtest_failures;
{ {
ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures); ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
DoAssertNoFatalFailureOnFails(); DoAssertNoFatalFailureOnFails();
} }
ASSERT_EQ(2, gtest_failures.size()); ASSERT_EQ(2, gtest_failures.size());
EXPECT_EQ(TestPartResult::kFatalFailure, EXPECT_EQ(TestPartResult::kFatalFailure,
skipping to change at line 3572 skipping to change at line 3535
"@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"}, "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
{__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++", {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
"@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n" "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
"@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"}, "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
{}}; {}};
for (const Case* c = kCases; c->left; ++c) { for (const Case* c = kCases; c->left; ++c) {
EXPECT_TRUE(c->expected_edits == EXPECT_TRUE(c->expected_edits ==
EditsToString(CalculateOptimalEdits(CharsToIndices(c->left), EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
CharsToIndices(c->right)))) CharsToIndices(c->right))))
<< "Left <" << c->left << "> Right <" << c->right << "> Edits <" << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
<< EditsToString(CalculateOptimalEdits( << EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
CharsToIndices(c->left), CharsToIndices(c->right))) << ">"; CharsToIndices(c->right)))
<< ">";
EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left), EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
CharsToLines(c->right))) CharsToLines(c->right)))
<< "Left <" << c->left << "> Right <" << c->right << "> Diff <" << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
<< CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right)) << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
<< ">"; << ">";
} }
} }
// Tests EqFailure(), used for implementing *EQ* assertions. // Tests EqFailure(), used for implementing *EQ* assertions.
TEST(AssertionTest, EqFailure) { TEST(AssertionTest, EqFailure) {
const std::string foo_val("5"), bar_val("6"); const std::string foo_val("5"), bar_val("6");
const std::string msg1( const std::string msg1(
EqFailure("foo", "bar", foo_val, bar_val, false) EqFailure("foo", "bar", foo_val, bar_val, false).failure_message());
.failure_message());
EXPECT_STREQ( EXPECT_STREQ(
"Expected equality of these values:\n" "Expected equality of these values:\n"
" foo\n" " foo\n"
" Which is: 5\n" " Which is: 5\n"
" bar\n" " bar\n"
" Which is: 6", " Which is: 6",
msg1.c_str()); msg1.c_str());
const std::string msg2( const std::string msg2(
EqFailure("foo", "6", foo_val, bar_val, false) EqFailure("foo", "6", foo_val, bar_val, false).failure_message());
.failure_message());
EXPECT_STREQ( EXPECT_STREQ(
"Expected equality of these values:\n" "Expected equality of these values:\n"
" foo\n" " foo\n"
" Which is: 5\n" " Which is: 5\n"
" 6", " 6",
msg2.c_str()); msg2.c_str());
const std::string msg3( const std::string msg3(
EqFailure("5", "bar", foo_val, bar_val, false) EqFailure("5", "bar", foo_val, bar_val, false).failure_message());
.failure_message());
EXPECT_STREQ( EXPECT_STREQ(
"Expected equality of these values:\n" "Expected equality of these values:\n"
" 5\n" " 5\n"
" bar\n" " bar\n"
" Which is: 6", " Which is: 6",
msg3.c_str()); msg3.c_str());
const std::string msg4( const std::string msg4(
EqFailure("5", "6", foo_val, bar_val, false).failure_message()); EqFailure("5", "6", foo_val, bar_val, false).failure_message());
EXPECT_STREQ( EXPECT_STREQ(
"Expected equality of these values:\n" "Expected equality of these values:\n"
" 5\n" " 5\n"
" 6", " 6",
msg4.c_str()); msg4.c_str());
const std::string msg5( const std::string msg5(
EqFailure("foo", "bar", EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true)
std::string("\"x\""), std::string("\"y\""), .failure_message());
true).failure_message());
EXPECT_STREQ( EXPECT_STREQ(
"Expected equality of these values:\n" "Expected equality of these values:\n"
" foo\n" " foo\n"
" Which is: \"x\"\n" " Which is: \"x\"\n"
" bar\n" " bar\n"
" Which is: \"y\"\n" " Which is: \"y\"\n"
"Ignoring case", "Ignoring case",
msg5.c_str()); msg5.c_str());
} }
skipping to change at line 3662 skipping to change at line 3622
"With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n" "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
"@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n", "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
msg1.c_str()); msg1.c_str());
} }
// Tests AppendUserMessage(), used for implementing the *EQ* macros. // Tests AppendUserMessage(), used for implementing the *EQ* macros.
TEST(AssertionTest, AppendUserMessage) { TEST(AssertionTest, AppendUserMessage) {
const std::string foo("foo"); const std::string foo("foo");
Message msg; Message msg;
EXPECT_STREQ("foo", EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str());
AppendUserMessage(foo, msg).c_str());
msg << "bar"; msg << "bar";
EXPECT_STREQ("foo\nbar", EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str());
AppendUserMessage(foo, msg).c_str());
} }
#ifdef __BORLANDC__ #ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code" // Silences warnings: "Condition is always true", "Unreachable code"
# pragma option push -w-ccc -w-rch #pragma option push -w-ccc -w-rch
#endif #endif
// Tests ASSERT_TRUE. // Tests ASSERT_TRUE.
TEST(AssertionTest, ASSERT_TRUE) { TEST(AssertionTest, ASSERT_TRUE) {
ASSERT_TRUE(2 > 1); // NOLINT ASSERT_TRUE(2 > 1); // NOLINT
EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1");
"2 < 1");
} }
// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult. // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
TEST(AssertionTest, AssertTrueWithAssertionResult) { TEST(AssertionTest, AssertTrueWithAssertionResult) {
ASSERT_TRUE(ResultIsEven(2)); ASSERT_TRUE(ResultIsEven(2));
#ifndef __BORLANDC__ #ifndef __BORLANDC__
// ICE's in C++Builder. // ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)), EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
"Value of: ResultIsEven(3)\n" "Value of: ResultIsEven(3)\n"
" Actual: false (3 is odd)\n" " Actual: false (3 is odd)\n"
skipping to change at line 3727 skipping to change at line 3684
#endif #endif
ASSERT_FALSE(ResultIsEvenNoExplanation(3)); ASSERT_FALSE(ResultIsEvenNoExplanation(3));
EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)), EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
"Value of: ResultIsEvenNoExplanation(2)\n" "Value of: ResultIsEvenNoExplanation(2)\n"
" Actual: true\n" " Actual: true\n"
"Expected: false"); "Expected: false");
} }
#ifdef __BORLANDC__ #ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them // Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop #pragma option pop
#endif #endif
// Tests using ASSERT_EQ on double values. The purpose is to make // Tests using ASSERT_EQ on double values. The purpose is to make
// sure that the specialization we did for integer and anonymous enums // sure that the specialization we did for integer and anonymous enums
// isn't used for double arguments. // isn't used for double arguments.
TEST(ExpectTest, ASSERT_EQ_Double) { TEST(ExpectTest, ASSERT_EQ_Double) {
// A success. // A success.
ASSERT_EQ(5.6, 5.6); ASSERT_EQ(5.6, 5.6);
// A failure. // A failure.
EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1");
"5.1");
} }
// Tests ASSERT_EQ. // Tests ASSERT_EQ.
TEST(AssertionTest, ASSERT_EQ) { TEST(AssertionTest, ASSERT_EQ) {
ASSERT_EQ(5, 2 + 3); ASSERT_EQ(5, 2 + 3);
// clang-format off
EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
"Expected equality of these values:\n" "Expected equality of these values:\n"
" 5\n" " 5\n"
" 2*3\n" " 2*3\n"
" Which is: 6"); " Which is: 6");
// clang-format on
} }
// Tests ASSERT_EQ(NULL, pointer). // Tests ASSERT_EQ(NULL, pointer).
TEST(AssertionTest, ASSERT_EQ_NULL) { TEST(AssertionTest, ASSERT_EQ_NULL) {
// A success. // A success.
const char* p = nullptr; const char* p = nullptr;
ASSERT_EQ(nullptr, p); ASSERT_EQ(nullptr, p);
// A failure. // A failure.
static int n = 0; static int n = 0;
skipping to change at line 3774 skipping to change at line 3732
// treated as a null pointer by the compiler, we need to make sure // treated as a null pointer by the compiler, we need to make sure
// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
// ASSERT_EQ(static_cast<void*>(NULL), non_pointer). // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest, ASSERT_EQ_0) { TEST(ExpectTest, ASSERT_EQ_0) {
int n = 0; int n = 0;
// A success. // A success.
ASSERT_EQ(0, n); ASSERT_EQ(0, n);
// A failure. // A failure.
EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), " 0\n 5.6");
" 0\n 5.6");
} }
// Tests ASSERT_NE. // Tests ASSERT_NE.
TEST(AssertionTest, ASSERT_NE) { TEST(AssertionTest, ASSERT_NE) {
ASSERT_NE(6, 7); ASSERT_NE(6, 7);
EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'), EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
"Expected: ('a') != ('a'), " "Expected: ('a') != ('a'), "
"actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
} }
// Tests ASSERT_LE. // Tests ASSERT_LE.
TEST(AssertionTest, ASSERT_LE) { TEST(AssertionTest, ASSERT_LE) {
ASSERT_LE(2, 3); ASSERT_LE(2, 3);
ASSERT_LE(2, 2); ASSERT_LE(2, 2);
EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0");
"Expected: (2) <= (0), actual: 2 vs 0");
} }
// Tests ASSERT_LT. // Tests ASSERT_LT.
TEST(AssertionTest, ASSERT_LT) { TEST(AssertionTest, ASSERT_LT) {
ASSERT_LT(2, 3); ASSERT_LT(2, 3);
EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2");
"Expected: (2) < (2), actual: 2 vs 2");
} }
// Tests ASSERT_GE. // Tests ASSERT_GE.
TEST(AssertionTest, ASSERT_GE) { TEST(AssertionTest, ASSERT_GE) {
ASSERT_GE(2, 1); ASSERT_GE(2, 1);
ASSERT_GE(2, 2); ASSERT_GE(2, 2);
EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3");
"Expected: (2) >= (3), actual: 2 vs 3");
} }
// Tests ASSERT_GT. // Tests ASSERT_GT.
TEST(AssertionTest, ASSERT_GT) { TEST(AssertionTest, ASSERT_GT) {
ASSERT_GT(2, 1); ASSERT_GT(2, 1);
EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2");
"Expected: (2) > (2), actual: 2 vs 2");
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
void ThrowNothing() {} void ThrowNothing() {}
// Tests ASSERT_THROW. // Tests ASSERT_THROW.
TEST(AssertionTest, ASSERT_THROW) { TEST(AssertionTest, ASSERT_THROW) {
ASSERT_THROW(ThrowAnInteger(), int); ASSERT_THROW(ThrowAnInteger(), int);
# ifndef __BORLANDC__ #ifndef __BORLANDC__
// ICE's in C++Builder 2007 and 2009. // ICE's in C++Builder 2007 and 2009.
EXPECT_FATAL_FAILURE( EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowAnInteger(), bool), ASSERT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of type bool.\n" "Expected: ThrowAnInteger() throws an exception of type bool.\n"
" Actual: it throws a different type."); " Actual: it throws a different type.");
EXPECT_FATAL_FAILURE( EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error), ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
"Expected: ThrowRuntimeError(\"A description\") " "Expected: ThrowRuntimeError(\"A description\") "
"throws an exception of type std::logic_error.\n " "throws an exception of type std::logic_error.\n "
"Actual: it throws " ERROR_DESC " " "Actual: it throws " ERROR_DESC
" "
"with description \"A description\"."); "with description \"A description\".");
# endif #endif
EXPECT_FATAL_FAILURE( EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowNothing(), bool), ASSERT_THROW(ThrowNothing(), bool),
"Expected: ThrowNothing() throws an exception of type bool.\n" "Expected: ThrowNothing() throws an exception of type bool.\n"
" Actual: it throws nothing."); " Actual: it throws nothing.");
} }
// Tests ASSERT_NO_THROW. // Tests ASSERT_NO_THROW.
TEST(AssertionTest, ASSERT_NO_THROW) { TEST(AssertionTest, ASSERT_NO_THROW) {
ASSERT_NO_THROW(ThrowNothing()); ASSERT_NO_THROW(ThrowNothing());
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()), EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
"Expected: ThrowAnInteger() doesn't throw an exception." "Expected: ThrowAnInteger() doesn't throw an exception."
"\n Actual: it throws."); "\n Actual: it throws.");
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")), EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") " "Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n " "doesn't throw an exception.\n "
"Actual: it throws " ERROR_DESC " " "Actual: it throws " ERROR_DESC
" "
"with description \"A description\"."); "with description \"A description\".");
} }
// Tests ASSERT_ANY_THROW. // Tests ASSERT_ANY_THROW.
TEST(AssertionTest, ASSERT_ANY_THROW) { TEST(AssertionTest, ASSERT_ANY_THROW) {
ASSERT_ANY_THROW(ThrowAnInteger()); ASSERT_ANY_THROW(ThrowAnInteger());
EXPECT_FATAL_FAILURE( EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()),
ASSERT_ANY_THROW(ThrowNothing()), "Expected: ThrowNothing() throws an exception.\n"
"Expected: ThrowNothing() throws an exception.\n" " Actual: it doesn't.");
" Actual: it doesn't.");
} }
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
// Makes sure we deal with the precedence of <<. This test should // Makes sure we deal with the precedence of <<. This test should
// compile. // compile.
TEST(AssertionTest, AssertPrecedence) { TEST(AssertionTest, AssertPrecedence) {
ASSERT_EQ(1 < 2, true); ASSERT_EQ(1 < 2, true);
bool false_value = false; bool false_value = false;
ASSERT_EQ(true && false_value, false); ASSERT_EQ(true && false_value, false);
} }
// A subroutine used by the following test. // A subroutine used by the following test.
void TestEq1(int x) { void TestEq1(int x) { ASSERT_EQ(1, x); }
ASSERT_EQ(1, x);
}
// Tests calling a test subroutine that's not part of a fixture. // Tests calling a test subroutine that's not part of a fixture.
TEST(AssertionTest, NonFixtureSubroutine) { TEST(AssertionTest, NonFixtureSubroutine) {
EXPECT_FATAL_FAILURE(TestEq1(2), EXPECT_FATAL_FAILURE(TestEq1(2), " x\n Which is: 2");
" x\n Which is: 2");
} }
// An uncopyable class. // An uncopyable class.
class Uncopyable { class Uncopyable {
public: public:
explicit Uncopyable(int a_value) : value_(a_value) {} explicit Uncopyable(int a_value) : value_(a_value) {}
int value() const { return value_; } int value() const { return value_; }
bool operator==(const Uncopyable& rhs) const { bool operator==(const Uncopyable& rhs) const {
return value() == rhs.value(); return value() == rhs.value();
} }
private: private:
// This constructor deliberately has no implementation, as we don't // This constructor deliberately has no implementation, as we don't
// want this class to be copyable. // want this class to be copyable.
Uncopyable(const Uncopyable&); // NOLINT Uncopyable(const Uncopyable&); // NOLINT
int value_; int value_;
}; };
::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) { ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
return os << value.value(); return os << value.value();
} }
bool IsPositiveUncopyable(const Uncopyable& x) { bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; }
return x.value() > 0;
}
// A subroutine used by the following test. // A subroutine used by the following test.
void TestAssertNonPositive() { void TestAssertNonPositive() {
Uncopyable y(-1); Uncopyable y(-1);
ASSERT_PRED1(IsPositiveUncopyable, y); ASSERT_PRED1(IsPositiveUncopyable, y);
} }
// A subroutine used by the following test. // A subroutine used by the following test.
void TestAssertEqualsUncopyable() { void TestAssertEqualsUncopyable() {
Uncopyable x(5); Uncopyable x(5);
Uncopyable y(-1); Uncopyable y(-1);
ASSERT_EQ(x, y); ASSERT_EQ(x, y);
} }
// Tests that uncopyable objects can be used in assertions. // Tests that uncopyable objects can be used in assertions.
TEST(AssertionTest, AssertWorksWithUncopyableObject) { TEST(AssertionTest, AssertWorksWithUncopyableObject) {
Uncopyable x(5); Uncopyable x(5);
ASSERT_PRED1(IsPositiveUncopyable, x); ASSERT_PRED1(IsPositiveUncopyable, x);
ASSERT_EQ(x, x); ASSERT_EQ(x, x);
EXPECT_FATAL_FAILURE(TestAssertNonPositive(), EXPECT_FATAL_FAILURE(
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); TestAssertNonPositive(),
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(), EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
"Expected equality of these values:\n" "Expected equality of these values:\n"
" x\n Which is: 5\n y\n Which is: -1"); " x\n Which is: 5\n y\n Which is: -1");
} }
// Tests that uncopyable objects can be used in expects. // Tests that uncopyable objects can be used in expects.
TEST(AssertionTest, ExpectWorksWithUncopyableObject) { TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
Uncopyable x(5); Uncopyable x(5);
EXPECT_PRED1(IsPositiveUncopyable, x); EXPECT_PRED1(IsPositiveUncopyable, x);
Uncopyable y(-1); Uncopyable y(-1);
EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y), EXPECT_NONFATAL_FAILURE(
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_PRED1(IsPositiveUncopyable, y),
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
EXPECT_EQ(x, x); EXPECT_EQ(x, x);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
"Expected equality of these values:\n" "Expected equality of these values:\n"
" x\n Which is: 5\n y\n Which is: -1"); " x\n Which is: 5\n y\n Which is: -1");
} }
enum NamedEnum { enum NamedEnum { kE1 = 0, kE2 = 1 };
kE1 = 0,
kE2 = 1
};
TEST(AssertionTest, NamedEnum) { TEST(AssertionTest, NamedEnum) {
EXPECT_EQ(kE1, kE1); EXPECT_EQ(kE1, kE1);
EXPECT_LT(kE1, kE2); EXPECT_LT(kE1, kE2);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
} }
// Sun Studio and HP aCC2reject this code. // Sun Studio and HP aCC2reject this code.
#if !defined(__SUNPRO_CC) && !defined(__HP_aCC) #if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
// Tests using assertions with anonymous enums. // Tests using assertions with anonymous enums.
enum { enum {
kCaseA = -1, kCaseA = -1,
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
// We want to test the case where the size of the anonymous enum is // We want to test the case where the size of the anonymous enum is
// larger than sizeof(int), to make sure our implementation of the // larger than sizeof(int), to make sure our implementation of the
// assertions doesn't truncate the enums. However, MSVC // assertions doesn't truncate the enums. However, MSVC
// (incorrectly) doesn't allow an enum value to exceed the range of // (incorrectly) doesn't allow an enum value to exceed the range of
// an int, so this has to be conditionally compiled. // an int, so this has to be conditionally compiled.
// //
// On Linux, kCaseB and kCaseA have the same value when truncated to // On Linux, kCaseB and kCaseA have the same value when truncated to
// int size. We want to test whether this will confuse the // int size. We want to test whether this will confuse the
// assertions. // assertions.
kCaseB = testing::internal::kMaxBiggestInt, kCaseB = testing::internal::kMaxBiggestInt,
# else #else
kCaseB = INT_MAX, kCaseB = INT_MAX,
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
kCaseC = 42 kCaseC = 42
}; };
TEST(AssertionTest, AnonymousEnum) { TEST(AssertionTest, AnonymousEnum) {
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB)); EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
EXPECT_EQ(kCaseA, kCaseA); EXPECT_EQ(kCaseA, kCaseA);
EXPECT_NE(kCaseA, kCaseB); EXPECT_NE(kCaseA, kCaseB);
EXPECT_LT(kCaseA, kCaseB); EXPECT_LT(kCaseA, kCaseB);
EXPECT_LE(kCaseA, kCaseB); EXPECT_LE(kCaseA, kCaseB);
EXPECT_GT(kCaseB, kCaseA); EXPECT_GT(kCaseB, kCaseA);
EXPECT_GE(kCaseA, kCaseA); EXPECT_GE(kCaseA, kCaseA);
EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)");
"(kCaseA) >= (kCaseB)"); EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42");
EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
"-1 vs 42");
ASSERT_EQ(kCaseA, kCaseA); ASSERT_EQ(kCaseA, kCaseA);
ASSERT_NE(kCaseA, kCaseB); ASSERT_NE(kCaseA, kCaseB);
ASSERT_LT(kCaseA, kCaseB); ASSERT_LT(kCaseA, kCaseB);
ASSERT_LE(kCaseA, kCaseB); ASSERT_LE(kCaseA, kCaseB);
ASSERT_GT(kCaseB, kCaseA); ASSERT_GT(kCaseB, kCaseA);
ASSERT_GE(kCaseA, kCaseA); ASSERT_GE(kCaseA, kCaseA);
# ifndef __BORLANDC__ #ifndef __BORLANDC__
// ICE's in C++Builder. // ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), " kCaseB\n Which is: ");
" kCaseB\n Which is: "); EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: 42");
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), #endif
"\n Which is: 42");
# endif
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: -1");
"\n Which is: -1");
} }
#endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC) #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
static HRESULT UnexpectedHRESULTFailure() { static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; }
return E_UNEXPECTED;
}
static HRESULT OkHRESULTSuccess() { static HRESULT OkHRESULTSuccess() { return S_OK; }
return S_OK;
}
static HRESULT FalseHRESULTSuccess() { static HRESULT FalseHRESULTSuccess() { return S_FALSE; }
return S_FALSE;
}
// HRESULT assertion tests test both zero and non-zero // HRESULT assertion tests test both zero and non-zero
// success codes as well as failure message for each. // success codes as well as failure message for each.
// //
// Windows CE doesn't support message texts. // Windows CE doesn't support message texts.
TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) { TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
EXPECT_HRESULT_SUCCEEDED(S_OK); EXPECT_HRESULT_SUCCEEDED(S_OK);
EXPECT_HRESULT_SUCCEEDED(S_FALSE); EXPECT_HRESULT_SUCCEEDED(S_FALSE);
EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
"Expected: (UnexpectedHRESULTFailure()) succeeds.\n" "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
" Actual: 0x8000FFFF"); " Actual: 0x8000FFFF");
} }
TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) { TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
ASSERT_HRESULT_SUCCEEDED(S_OK); ASSERT_HRESULT_SUCCEEDED(S_OK);
ASSERT_HRESULT_SUCCEEDED(S_FALSE); ASSERT_HRESULT_SUCCEEDED(S_FALSE);
EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
"Expected: (UnexpectedHRESULTFailure()) succeeds.\n" "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
" Actual: 0x8000FFFF"); " Actual: 0x8000FFFF");
} }
TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) { TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
EXPECT_HRESULT_FAILED(E_UNEXPECTED); EXPECT_HRESULT_FAILED(E_UNEXPECTED);
EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()), EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
"Expected: (OkHRESULTSuccess()) fails.\n" "Expected: (OkHRESULTSuccess()) fails.\n"
" Actual: 0x0"); " Actual: 0x0");
EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()), EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
"Expected: (FalseHRESULTSuccess()) fails.\n" "Expected: (FalseHRESULTSuccess()) fails.\n"
" Actual: 0x1"); " Actual: 0x1");
} }
TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) { TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
ASSERT_HRESULT_FAILED(E_UNEXPECTED); ASSERT_HRESULT_FAILED(E_UNEXPECTED);
# ifndef __BORLANDC__ #ifndef __BORLANDC__
// ICE's in C++Builder 2007 and 2009. // ICE's in C++Builder 2007 and 2009.
EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()), EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
"Expected: (OkHRESULTSuccess()) fails.\n" "Expected: (OkHRESULTSuccess()) fails.\n"
" Actual: 0x0"); " Actual: 0x0");
# endif #endif
EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()), EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
"Expected: (FalseHRESULTSuccess()) fails.\n" "Expected: (FalseHRESULTSuccess()) fails.\n"
" Actual: 0x1"); " Actual: 0x1");
} }
// Tests that streaming to the HRESULT macros works. // Tests that streaming to the HRESULT macros works.
TEST(HRESULTAssertionTest, Streaming) { TEST(HRESULTAssertionTest, Streaming) {
EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED)
EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", << "expected failure",
"expected failure"); "expected failure");
# ifndef __BORLANDC__ #ifndef __BORLANDC__
// ICE's in C++Builder 2007 and 2009. // ICE's in C++Builder 2007 and 2009.
EXPECT_FATAL_FAILURE( EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED)
ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", << "expected failure",
"expected failure"); "expected failure");
# endif #endif
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
EXPECT_HRESULT_FAILED(S_OK) << "expected failure", "expected failure");
"expected failure");
EXPECT_FATAL_FAILURE( EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
ASSERT_HRESULT_FAILED(S_OK) << "expected failure", "expected failure");
"expected failure");
} }
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// The following code intentionally tests a suboptimal syntax. // The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__ #ifdef __GNUC__
#pragma GCC diagnostic push #pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-else" #pragma GCC diagnostic ignored "-Wdangling-else"
#pragma GCC diagnostic ignored "-Wempty-body" #pragma GCC diagnostic ignored "-Wempty-body"
#pragma GCC diagnostic ignored "-Wpragmas" #pragma GCC diagnostic ignored "-Wpragmas"
skipping to change at line 4142 skipping to change at line 4078
TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) { TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse()) if (AlwaysFalse())
ASSERT_TRUE(false) << "This should never be executed; " ASSERT_TRUE(false) << "This should never be executed; "
"It's a compilation test only."; "It's a compilation test only.";
if (AlwaysTrue()) if (AlwaysTrue())
EXPECT_FALSE(false); EXPECT_FALSE(false);
else else
; // NOLINT ; // NOLINT
if (AlwaysFalse()) if (AlwaysFalse()) ASSERT_LT(1, 3);
ASSERT_LT(1, 3);
if (AlwaysFalse()) if (AlwaysFalse())
; // NOLINT ; // NOLINT
else else
EXPECT_GT(3, 2) << ""; EXPECT_GT(3, 2) << "";
} }
#ifdef __GNUC__ #ifdef __GNUC__
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif
skipping to change at line 4181 skipping to change at line 4116
} }
// The following code intentionally tests a suboptimal syntax. // The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__ #ifdef __GNUC__
#pragma GCC diagnostic push #pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-else" #pragma GCC diagnostic ignored "-Wdangling-else"
#pragma GCC diagnostic ignored "-Wempty-body" #pragma GCC diagnostic ignored "-Wempty-body"
#pragma GCC diagnostic ignored "-Wpragmas" #pragma GCC diagnostic ignored "-Wpragmas"
#endif #endif
TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse()) if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool);
EXPECT_THROW(ThrowNothing(), bool);
if (AlwaysTrue()) if (AlwaysTrue())
EXPECT_THROW(ThrowAnInteger(), int); EXPECT_THROW(ThrowAnInteger(), int);
else else
; // NOLINT ; // NOLINT
if (AlwaysFalse()) if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger());
EXPECT_NO_THROW(ThrowAnInteger());
if (AlwaysTrue()) if (AlwaysTrue())
EXPECT_NO_THROW(ThrowNothing()); EXPECT_NO_THROW(ThrowNothing());
else else
; // NOLINT ; // NOLINT
if (AlwaysFalse()) if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing());
EXPECT_ANY_THROW(ThrowNothing());
if (AlwaysTrue()) if (AlwaysTrue())
EXPECT_ANY_THROW(ThrowAnInteger()); EXPECT_ANY_THROW(ThrowAnInteger());
else else
; // NOLINT ; // NOLINT
} }
#ifdef __GNUC__ #ifdef __GNUC__
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif
skipping to change at line 4254 skipping to change at line 4186
// Tests that the assertion macros work well with switch statements. // Tests that the assertion macros work well with switch statements.
TEST(AssertionSyntaxTest, WorksWithSwitch) { TEST(AssertionSyntaxTest, WorksWithSwitch) {
switch (0) { switch (0) {
case 1: case 1:
break; break;
default: default:
ASSERT_TRUE(true); ASSERT_TRUE(true);
} }
switch (0) switch (0)
case 0: case 0:
EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case"; EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
// Binary assertions are implemented using a different code path // Binary assertions are implemented using a different code path
// than the Boolean assertions. Hence we test them separately. // than the Boolean assertions. Hence we test them separately.
switch (0) { switch (0) {
case 1: case 1:
default: default:
ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler"; ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
} }
switch (0) switch (0)
case 0: case 0:
EXPECT_NE(1, 2); EXPECT_NE(1, 2);
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
void ThrowAString() { void ThrowAString() { throw "std::string"; }
throw "std::string";
}
// Test that the exception assertion macros compile and work with const // Test that the exception assertion macros compile and work with const
// type qualifier. // type qualifier.
TEST(AssertionSyntaxTest, WorksWithConst) { TEST(AssertionSyntaxTest, WorksWithConst) {
ASSERT_THROW(ThrowAString(), const char*); ASSERT_THROW(ThrowAString(), const char*);
EXPECT_THROW(ThrowAString(), const char*); EXPECT_THROW(ThrowAString(), const char*);
} }
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
} // namespace } // namespace
namespace testing { namespace testing {
// Tests that Google Test tracks SUCCEED*. // Tests that Google Test tracks SUCCEED*.
TEST(SuccessfulAssertionTest, SUCCEED) { TEST(SuccessfulAssertionTest, SUCCEED) {
skipping to change at line 4379 skipping to change at line 4309
TEST(AssertionWithMessageTest, ASSERT_FLOATING) { TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
ASSERT_FLOAT_EQ(1, 1) << "This should succeed."; ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
ASSERT_DOUBLE_EQ(1, 1) << "This should succeed."; ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
"Expect failure."); "Expect failure.");
} }
// Tests using ASSERT_FALSE with a streamed message. // Tests using ASSERT_FALSE with a streamed message.
TEST(AssertionWithMessageTest, ASSERT_FALSE) { TEST(AssertionWithMessageTest, ASSERT_FALSE) {
ASSERT_FALSE(false) << "This shouldn't fail."; ASSERT_FALSE(false) << "This shouldn't fail.";
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1 { // NOLINT
<< " evaluates to " << true; ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
}, "Expected failure"); << " evaluates to " << true;
},
"Expected failure");
} }
// Tests using FAIL with a streamed message. // Tests using FAIL with a streamed message.
TEST(AssertionWithMessageTest, FAIL) { TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); }
EXPECT_FATAL_FAILURE(FAIL() << 0,
"0");
}
// Tests using SUCCEED with a streamed message. // Tests using SUCCEED with a streamed message.
TEST(AssertionWithMessageTest, SUCCEED) { TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; }
SUCCEED() << "Success == " << 1;
}
// Tests using ASSERT_TRUE with a streamed message. // Tests using ASSERT_TRUE with a streamed message.
TEST(AssertionWithMessageTest, ASSERT_TRUE) { TEST(AssertionWithMessageTest, ASSERT_TRUE) {
ASSERT_TRUE(true) << "This should succeed."; ASSERT_TRUE(true) << "This should succeed.";
ASSERT_TRUE(true) << true; ASSERT_TRUE(true) << true;
EXPECT_FATAL_FAILURE( EXPECT_FATAL_FAILURE(
{ // NOLINT { // NOLINT
ASSERT_TRUE(false) << static_cast<const char*>(nullptr) ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
<< static_cast<char*>(nullptr); << static_cast<char*>(nullptr);
}, },
"(null)(null)"); "(null)(null)");
} }
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Tests using wide strings in assertion messages. // Tests using wide strings in assertion messages.
TEST(AssertionWithMessageTest, WideStringMessage) { TEST(AssertionWithMessageTest, WideStringMessage) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_TRUE(false) << L"This failure is expected.\x8119"; { // NOLINT
}, "This failure is expected."); EXPECT_TRUE(false) << L"This failure is expected.\x8119";
EXPECT_FATAL_FAILURE({ // NOLINT },
ASSERT_EQ(1, 2) << "This failure is " "This failure is expected.");
<< L"expected too.\x8120"; EXPECT_FATAL_FAILURE(
}, "This failure is expected too."); { // NOLINT
ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120";
},
"This failure is expected too.");
} }
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Tests EXPECT_TRUE. // Tests EXPECT_TRUE.
TEST(ExpectTest, EXPECT_TRUE) { TEST(ExpectTest, EXPECT_TRUE) {
EXPECT_TRUE(true) << "Intentional success"; EXPECT_TRUE(true) << "Intentional success";
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.", EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
"Intentional failure #1."); "Intentional failure #1.");
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.", EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
"Intentional failure #2."); "Intentional failure #2.");
EXPECT_TRUE(2 > 1); // NOLINT EXPECT_TRUE(2 > 1); // NOLINT
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1), EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
"Value of: 2 < 1\n" "Value of: 2 < 1\n"
" Actual: false\n" " Actual: false\n"
"Expected: true"); "Expected: true");
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3");
"2 > 3");
} }
// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult. // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest, ExpectTrueWithAssertionResult) { TEST(ExpectTest, ExpectTrueWithAssertionResult) {
EXPECT_TRUE(ResultIsEven(2)); EXPECT_TRUE(ResultIsEven(2));
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)), EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
"Value of: ResultIsEven(3)\n" "Value of: ResultIsEven(3)\n"
" Actual: false (3 is odd)\n" " Actual: false (3 is odd)\n"
"Expected: true"); "Expected: true");
EXPECT_TRUE(ResultIsEvenNoExplanation(2)); EXPECT_TRUE(ResultIsEvenNoExplanation(2));
skipping to change at line 4463 skipping to change at line 4392
EXPECT_FALSE(2 < 1); // NOLINT EXPECT_FALSE(2 < 1); // NOLINT
EXPECT_FALSE(false) << "Intentional success"; EXPECT_FALSE(false) << "Intentional success";
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.", EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
"Intentional failure #1."); "Intentional failure #1.");
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.", EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
"Intentional failure #2."); "Intentional failure #2.");
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1), EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
"Value of: 2 > 1\n" "Value of: 2 > 1\n"
" Actual: true\n" " Actual: true\n"
"Expected: false"); "Expected: false");
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3");
"2 < 3");
} }
// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult. // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest, ExpectFalseWithAssertionResult) { TEST(ExpectTest, ExpectFalseWithAssertionResult) {
EXPECT_FALSE(ResultIsEven(3)); EXPECT_FALSE(ResultIsEven(3));
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)), EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
"Value of: ResultIsEven(2)\n" "Value of: ResultIsEven(2)\n"
" Actual: true (2 is even)\n" " Actual: true (2 is even)\n"
"Expected: false"); "Expected: false");
EXPECT_FALSE(ResultIsEvenNoExplanation(3)); EXPECT_FALSE(ResultIsEvenNoExplanation(3));
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)), EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
"Value of: ResultIsEvenNoExplanation(2)\n" "Value of: ResultIsEvenNoExplanation(2)\n"
" Actual: true\n" " Actual: true\n"
"Expected: false"); "Expected: false");
} }
#ifdef __BORLANDC__ #ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them // Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop #pragma option pop
#endif #endif
// Tests EXPECT_EQ. // Tests EXPECT_EQ.
TEST(ExpectTest, EXPECT_EQ) { TEST(ExpectTest, EXPECT_EQ) {
EXPECT_EQ(5, 2 + 3); EXPECT_EQ(5, 2 + 3);
// clang-format off
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
"Expected equality of these values:\n" "Expected equality of these values:\n"
" 5\n" " 5\n"
" 2*3\n" " 2*3\n"
" Which is: 6"); " Which is: 6");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3");
"2 - 3"); // clang-format on
} }
// Tests using EXPECT_EQ on double values. The purpose is to make // Tests using EXPECT_EQ on double values. The purpose is to make
// sure that the specialization we did for integer and anonymous enums // sure that the specialization we did for integer and anonymous enums
// isn't used for double arguments. // isn't used for double arguments.
TEST(ExpectTest, EXPECT_EQ_Double) { TEST(ExpectTest, EXPECT_EQ_Double) {
// A success. // A success.
EXPECT_EQ(5.6, 5.6); EXPECT_EQ(5.6, 5.6);
// A failure. // A failure.
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1");
"5.1");
} }
// Tests EXPECT_EQ(NULL, pointer). // Tests EXPECT_EQ(NULL, pointer).
TEST(ExpectTest, EXPECT_EQ_NULL) { TEST(ExpectTest, EXPECT_EQ_NULL) {
// A success. // A success.
const char* p = nullptr; const char* p = nullptr;
EXPECT_EQ(nullptr, p); EXPECT_EQ(nullptr, p);
// A failure. // A failure.
int n = 0; int n = 0;
skipping to change at line 4532 skipping to change at line 4460
// treated as a null pointer by the compiler, we need to make sure // treated as a null pointer by the compiler, we need to make sure
// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
// EXPECT_EQ(static_cast<void*>(NULL), non_pointer). // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest, EXPECT_EQ_0) { TEST(ExpectTest, EXPECT_EQ_0) {
int n = 0; int n = 0;
// A success. // A success.
EXPECT_EQ(0, n); EXPECT_EQ(0, n);
// A failure. // A failure.
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), " 0\n 5.6");
" 0\n 5.6");
} }
// Tests EXPECT_NE. // Tests EXPECT_NE.
TEST(ExpectTest, EXPECT_NE) { TEST(ExpectTest, EXPECT_NE) {
EXPECT_NE(6, 7); EXPECT_NE(6, 7);
EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'), EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
"Expected: ('a') != ('a'), " "Expected: ('a') != ('a'), "
"actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2");
"2");
char* const p0 = nullptr; char* const p0 = nullptr;
EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0");
"p0");
// Only way to get the Nokia compiler to compile the cast // Only way to get the Nokia compiler to compile the cast
// is to have a separate void* variable first. Putting // is to have a separate void* variable first. Putting
// the two casts on the same line doesn't work, neither does // the two casts on the same line doesn't work, neither does
// a direct C-style to char*. // a direct C-style to char*.
void* pv1 = (void*)0x1234; // NOLINT void* pv1 = (void*)0x1234; // NOLINT
char* const p1 = reinterpret_cast<char*>(pv1); char* const p1 = reinterpret_cast<char*>(pv1);
EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1");
"p1");
} }
// Tests EXPECT_LE. // Tests EXPECT_LE.
TEST(ExpectTest, EXPECT_LE) { TEST(ExpectTest, EXPECT_LE) {
EXPECT_LE(2, 3); EXPECT_LE(2, 3);
EXPECT_LE(2, 2); EXPECT_LE(2, 2);
EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0), EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
"Expected: (2) <= (0), actual: 2 vs 0"); "Expected: (2) <= (0), actual: 2 vs 0");
EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)");
"(1.1) <= (0.9)");
} }
// Tests EXPECT_LT. // Tests EXPECT_LT.
TEST(ExpectTest, EXPECT_LT) { TEST(ExpectTest, EXPECT_LT) {
EXPECT_LT(2, 3); EXPECT_LT(2, 3);
EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2), EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
"Expected: (2) < (2), actual: 2 vs 2"); "Expected: (2) < (2), actual: 2 vs 2");
EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)");
"(2) < (1)");
} }
// Tests EXPECT_GE. // Tests EXPECT_GE.
TEST(ExpectTest, EXPECT_GE) { TEST(ExpectTest, EXPECT_GE) {
EXPECT_GE(2, 1); EXPECT_GE(2, 1);
EXPECT_GE(2, 2); EXPECT_GE(2, 2);
EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3), EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
"Expected: (2) >= (3), actual: 2 vs 3"); "Expected: (2) >= (3), actual: 2 vs 3");
EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)");
"(0.9) >= (1.1)");
} }
// Tests EXPECT_GT. // Tests EXPECT_GT.
TEST(ExpectTest, EXPECT_GT) { TEST(ExpectTest, EXPECT_GT) {
EXPECT_GT(2, 1); EXPECT_GT(2, 1);
EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2), EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
"Expected: (2) > (2), actual: 2 vs 2"); "Expected: (2) > (2), actual: 2 vs 2");
EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)");
"(2) > (3)");
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
// Tests EXPECT_THROW. // Tests EXPECT_THROW.
TEST(ExpectTest, EXPECT_THROW) { TEST(ExpectTest, EXPECT_THROW) {
EXPECT_THROW(ThrowAnInteger(), int); EXPECT_THROW(ThrowAnInteger(), int);
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool), EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of " "Expected: ThrowAnInteger() throws an exception of "
"type bool.\n Actual: it throws a different type."); "type bool.\n Actual: it throws a different type.");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"), EXPECT_NONFATAL_FAILURE(
std::logic_error), EXPECT_THROW(ThrowRuntimeError("A description"), std::logic_error),
"Expected: ThrowRuntimeError(\"A description\") " "Expected: ThrowRuntimeError(\"A description\") "
"throws an exception of type std::logic_error.\n " "throws an exception of type std::logic_error.\n "
"Actual: it throws " ERROR_DESC " " "Actual: it throws " ERROR_DESC
"with description \"A description\"."); " "
"with description \"A description\".");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
EXPECT_THROW(ThrowNothing(), bool), EXPECT_THROW(ThrowNothing(), bool),
"Expected: ThrowNothing() throws an exception of type bool.\n" "Expected: ThrowNothing() throws an exception of type bool.\n"
" Actual: it throws nothing."); " Actual: it throws nothing.");
} }
// Tests EXPECT_NO_THROW. // Tests EXPECT_NO_THROW.
TEST(ExpectTest, EXPECT_NO_THROW) { TEST(ExpectTest, EXPECT_NO_THROW) {
EXPECT_NO_THROW(ThrowNothing()); EXPECT_NO_THROW(ThrowNothing());
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()), EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
"Expected: ThrowAnInteger() doesn't throw an " "Expected: ThrowAnInteger() doesn't throw an "
"exception.\n Actual: it throws."); "exception.\n Actual: it throws.");
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")), EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") " "Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n " "doesn't throw an exception.\n "
"Actual: it throws " ERROR_DESC " " "Actual: it throws " ERROR_DESC
" "
"with description \"A description\"."); "with description \"A description\".");
} }
// Tests EXPECT_ANY_THROW. // Tests EXPECT_ANY_THROW.
TEST(ExpectTest, EXPECT_ANY_THROW) { TEST(ExpectTest, EXPECT_ANY_THROW) {
EXPECT_ANY_THROW(ThrowAnInteger()); EXPECT_ANY_THROW(ThrowAnInteger());
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()),
EXPECT_ANY_THROW(ThrowNothing()), "Expected: ThrowNothing() throws an exception.\n"
"Expected: ThrowNothing() throws an exception.\n" " Actual: it doesn't.");
" Actual: it doesn't.");
} }
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
// Make sure we deal with the precedence of <<. // Make sure we deal with the precedence of <<.
TEST(ExpectTest, ExpectPrecedence) { TEST(ExpectTest, ExpectPrecedence) {
EXPECT_EQ(1 < 2, true); EXPECT_EQ(1 < 2, true);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
" true && false\n Which is: false"); " true && false\n Which is: false");
} }
skipping to change at line 4684 skipping to change at line 4605
char* p = nullptr; char* p = nullptr;
EXPECT_STREQ("(null)", StreamableToString(p).c_str()); EXPECT_STREQ("(null)", StreamableToString(p).c_str());
} }
// Tests using streamable values as assertion messages. // Tests using streamable values as assertion messages.
// Tests using std::string as an assertion message. // Tests using std::string as an assertion message.
TEST(StreamableTest, string) { TEST(StreamableTest, string) {
static const std::string str( static const std::string str(
"This failure message is a std::string, and is expected."); "This failure message is a std::string, and is expected.");
EXPECT_FATAL_FAILURE(FAIL() << str, EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str());
str.c_str());
} }
// Tests that we can output strings containing embedded NULs. // Tests that we can output strings containing embedded NULs.
// Limited to Linux because we can only do this with std::string's. // Limited to Linux because we can only do this with std::string's.
TEST(StreamableTest, stringWithEmbeddedNUL) { TEST(StreamableTest, stringWithEmbeddedNUL) {
static const char char_array_with_nul[] = static const char char_array_with_nul[] =
"Here's a NUL\0 and some more string"; "Here's a NUL\0 and some more string";
static const std::string string_with_nul(char_array_with_nul, static const std::string string_with_nul(
sizeof(char_array_with_nul) char_array_with_nul,
- 1); // drops the trailing NUL sizeof(char_array_with_nul) - 1); // drops the trailing NUL
EXPECT_FATAL_FAILURE(FAIL() << string_with_nul, EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
"Here's a NUL\\0 and some more string"); "Here's a NUL\\0 and some more string");
} }
// Tests that we can output a NUL char. // Tests that we can output a NUL char.
TEST(StreamableTest, NULChar) { TEST(StreamableTest, NULChar) {
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
FAIL() << "A NUL" << '\0' << " and some more string"; { // NOLINT
}, "A NUL\\0 and some more string"); FAIL() << "A NUL" << '\0' << " and some more string";
},
"A NUL\\0 and some more string");
} }
// Tests using int as an assertion message. // Tests using int as an assertion message.
TEST(StreamableTest, int) { TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); }
EXPECT_FATAL_FAILURE(FAIL() << 900913,
"900913");
}
// Tests using NULL char pointer as an assertion message. // Tests using NULL char pointer as an assertion message.
// //
// In MSVC, streaming a NULL char * causes access violation. Google Test // In MSVC, streaming a NULL char * causes access violation. Google Test
// implemented a workaround (substituting "(null)" for NULL). This // implemented a workaround (substituting "(null)" for NULL). This
// tests whether the workaround works. // tests whether the workaround works.
TEST(StreamableTest, NullCharPtr) { TEST(StreamableTest, NullCharPtr) {
EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)"); EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
} }
// Tests that basic IO manipulators (endl, ends, and flush) can be // Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to testing::Message. // streamed to testing::Message.
TEST(StreamableTest, BasicIoManip) { TEST(StreamableTest, BasicIoManip) {
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
FAIL() << "Line 1." << std::endl { // NOLINT
<< "A NUL char " << std::ends << std::flush << " in line 2."; FAIL() << "Line 1." << std::endl
}, "Line 1.\nA NUL char \\0 in line 2."); << "A NUL char " << std::ends << std::flush << " in line 2.";
},
"Line 1.\nA NUL char \\0 in line 2.");
} }
// Tests the macros that haven't been covered so far. // Tests the macros that haven't been covered so far.
void AddFailureHelper(bool* aborted) { void AddFailureHelper(bool* aborted) {
*aborted = true; *aborted = true;
ADD_FAILURE() << "Intentional failure."; ADD_FAILURE() << "Intentional failure.";
*aborted = false; *aborted = false;
} }
// Tests ADD_FAILURE. // Tests ADD_FAILURE.
TEST(MacroTest, ADD_FAILURE) { TEST(MacroTest, ADD_FAILURE) {
bool aborted = true; bool aborted = true;
EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Intentional failure.");
"Intentional failure.");
EXPECT_FALSE(aborted); EXPECT_FALSE(aborted);
} }
// Tests ADD_FAILURE_AT. // Tests ADD_FAILURE_AT.
TEST(MacroTest, ADD_FAILURE_AT) { TEST(MacroTest, ADD_FAILURE_AT) {
// Verifies that ADD_FAILURE_AT does generate a nonfatal failure and // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
// the failure message contains the user-streamed part. // the failure message contains the user-streamed part.
EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!"); EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
// Verifies that the user-streamed part is optional. // Verifies that the user-streamed part is optional.
EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed"); EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
// Unfortunately, we cannot verify that the failure message contains // Unfortunately, we cannot verify that the failure message contains
// the right file path and line number the same way, as // the right file path and line number the same way, as
// EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
// line number. Instead, we do that in googletest-output-test_.cc. // line number. Instead, we do that in googletest-output-test_.cc.
} }
// Tests FAIL. // Tests FAIL.
TEST(MacroTest, FAIL) { TEST(MacroTest, FAIL) {
EXPECT_FATAL_FAILURE(FAIL(), EXPECT_FATAL_FAILURE(FAIL(), "Failed");
"Failed");
EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.", EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
"Intentional failure."); "Intentional failure.");
} }
// Tests GTEST_FAIL_AT. // Tests GTEST_FAIL_AT.
TEST(MacroTest, GTEST_FAIL_AT) { TEST(MacroTest, GTEST_FAIL_AT) {
// Verifies that GTEST_FAIL_AT does generate a fatal failure and // Verifies that GTEST_FAIL_AT does generate a fatal failure and
// the failure message contains the user-streamed part. // the failure message contains the user-streamed part.
EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!"); EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
skipping to change at line 4798 skipping to change at line 4717
// Tests for EXPECT_EQ() and ASSERT_EQ(). // Tests for EXPECT_EQ() and ASSERT_EQ().
// //
// These tests fail *intentionally*, s.t. the failure messages can be // These tests fail *intentionally*, s.t. the failure messages can be
// generated and tested. // generated and tested.
// //
// We have different tests for different argument types. // We have different tests for different argument types.
// Tests using bool values in {EXPECT|ASSERT}_EQ. // Tests using bool values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Bool) { TEST(EqAssertionTest, Bool) {
EXPECT_EQ(true, true); EXPECT_EQ(true, true);
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE(
bool false_value = false; {
ASSERT_EQ(false_value, true); bool false_value = false;
}, " false_value\n Which is: false\n true"); ASSERT_EQ(false_value, true);
},
" false_value\n Which is: false\n true");
} }
// Tests using int values in {EXPECT|ASSERT}_EQ. // Tests using int values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Int) { TEST(EqAssertionTest, Int) {
ASSERT_EQ(32, 32); ASSERT_EQ(32, 32);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), " 32\n 33");
" 32\n 33");
} }
// Tests using time_t values in {EXPECT|ASSERT}_EQ. // Tests using time_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Time_T) { TEST(EqAssertionTest, Time_T) {
EXPECT_EQ(static_cast<time_t>(0), EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0));
static_cast<time_t>(0)); EXPECT_FATAL_FAILURE(
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0), ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), "1234");
static_cast<time_t>(1234)),
"1234");
} }
// Tests using char values in {EXPECT|ASSERT}_EQ. // Tests using char values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Char) { TEST(EqAssertionTest, Char) {
ASSERT_EQ('z', 'z'); ASSERT_EQ('z', 'z');
const char ch = 'b'; const char ch = 'b';
EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), " ch\n Which is: 'b'");
" ch\n Which is: 'b'"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), " ch\n Which is: 'b'");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
" ch\n Which is: 'b'");
} }
// Tests using wchar_t values in {EXPECT|ASSERT}_EQ. // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, WideChar) { TEST(EqAssertionTest, WideChar) {
EXPECT_EQ(L'b', L'b'); EXPECT_EQ(L'b', L'b');
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
"Expected equality of these values:\n" "Expected equality of these values:\n"
" L'\0'\n" " L'\0'\n"
" Which is: L'\0' (0, 0x0)\n" " Which is: L'\0' (0, 0x0)\n"
" L'x'\n" " L'x'\n"
" Which is: L'x' (120, 0x78)"); " Which is: L'x' (120, 0x78)");
static wchar_t wchar; static wchar_t wchar;
wchar = L'b'; wchar = L'b';
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar");
"wchar");
wchar = 0x8119; wchar = 0x8119;
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar), EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
" wchar\n Which is: L'"); " wchar\n Which is: L'");
} }
// Tests using ::std::string values in {EXPECT|ASSERT}_EQ. // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, StdString) { TEST(EqAssertionTest, StdString) {
// Compares a const char* to an std::string that has identical // Compares a const char* to an std::string that has identical
// content. // content.
ASSERT_EQ("Test", ::std::string("Test")); ASSERT_EQ("Test", ::std::string("Test"));
// Compares two identical std::strings. // Compares two identical std::strings.
static const ::std::string str1("A * in the middle"); static const ::std::string str1("A * in the middle");
static const ::std::string str2(str1); static const ::std::string str2(str1);
EXPECT_EQ(str1, str2); EXPECT_EQ(str1, str2);
// Compares a const char* to an std::string that has different // Compares a const char* to an std::string that has different
// content // content
EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "\"test\"");
"\"test\"");
// Compares an std::string to a char* that has different content. // Compares an std::string to a char* that has different content.
char* const p1 = const_cast<char*>("foo"); char* const p1 = const_cast<char*>("foo");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1");
"p1");
// Compares two std::strings that have different contents, one of // Compares two std::strings that have different contents, one of
// which having a NUL character in the middle. This should fail. // which having a NUL character in the middle. This should fail.
static ::std::string str3(str1); static ::std::string str3(str1);
str3.at(2) = '\0'; str3.at(2) = '\0';
EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3), EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
" str3\n Which is: \"A \\0 in the middle\""); " str3\n Which is: \"A \\0 in the middle\"");
} }
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ. // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, StdWideString) { TEST(EqAssertionTest, StdWideString) {
// Compares two identical std::wstrings. // Compares two identical std::wstrings.
const ::std::wstring wstr1(L"A * in the middle"); const ::std::wstring wstr1(L"A * in the middle");
const ::std::wstring wstr2(wstr1); const ::std::wstring wstr2(wstr1);
ASSERT_EQ(wstr1, wstr2); ASSERT_EQ(wstr1, wstr2);
// Compares an std::wstring to a const wchar_t* that has identical // Compares an std::wstring to a const wchar_t* that has identical
// content. // content.
const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; const wchar_t kTestX8119[] = {'T', 'e', 's', 't', 0x8119, '\0'};
EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119); EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
// Compares an std::wstring to a const wchar_t* that has different // Compares an std::wstring to a const wchar_t* that has different
// content. // content.
const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; const wchar_t kTestX8120[] = {'T', 'e', 's', 't', 0x8120, '\0'};
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120); { // NOLINT
}, "kTestX8120"); EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
},
"kTestX8120");
// Compares two std::wstrings that have different contents, one of // Compares two std::wstrings that have different contents, one of
// which having a NUL character in the middle. // which having a NUL character in the middle.
::std::wstring wstr3(wstr1); ::std::wstring wstr3(wstr1);
wstr3.at(2) = L'\0'; wstr3.at(2) = L'\0';
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3");
"wstr3");
// Compares a wchar_t* to an std::wstring that has different // Compares a wchar_t* to an std::wstring that has different
// content. // content.
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar")); { // NOLINT
}, ""); ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
},
"");
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
// Tests using char pointers in {EXPECT|ASSERT}_EQ. // Tests using char pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, CharPointer) { TEST(EqAssertionTest, CharPointer) {
char* const p0 = nullptr; char* const p0 = nullptr;
// Only way to get the Nokia compiler to compile the cast // Only way to get the Nokia compiler to compile the cast
// is to have a separate void* variable first. Putting // is to have a separate void* variable first. Putting
// the two casts on the same line doesn't work, neither does // the two casts on the same line doesn't work, neither does
// a direct C-style to char*. // a direct C-style to char*.
void* pv1 = (void*)0x1234; // NOLINT void* pv1 = (void*)0x1234; // NOLINT
void* pv2 = (void*)0xABC0; // NOLINT void* pv2 = (void*)0xABC0; // NOLINT
char* const p1 = reinterpret_cast<char*>(pv1); char* const p1 = reinterpret_cast<char*>(pv1);
char* const p2 = reinterpret_cast<char*>(pv2); char* const p2 = reinterpret_cast<char*>(pv2);
ASSERT_EQ(p1, p1); ASSERT_EQ(p1, p1);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:");
" p2\n Which is:"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
" p2\n Which is:");
EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234), EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
reinterpret_cast<char*>(0xABC0)), reinterpret_cast<char*>(0xABC0)),
"ABC0"); "ABC0");
} }
// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ. // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, WideCharPointer) { TEST(EqAssertionTest, WideCharPointer) {
wchar_t* const p0 = nullptr; wchar_t* const p0 = nullptr;
// Only way to get the Nokia compiler to compile the cast // Only way to get the Nokia compiler to compile the cast
// is to have a separate void* variable first. Putting // is to have a separate void* variable first. Putting
// the two casts on the same line doesn't work, neither does // the two casts on the same line doesn't work, neither does
// a direct C-style to char*. // a direct C-style to char*.
void* pv1 = (void*)0x1234; // NOLINT void* pv1 = (void*)0x1234; // NOLINT
void* pv2 = (void*)0xABC0; // NOLINT void* pv2 = (void*)0xABC0; // NOLINT
wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1); wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2); wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
EXPECT_EQ(p0, p0); EXPECT_EQ(p0, p0);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:");
" p2\n Which is:"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
" p2\n Which is:");
void* pv3 = (void*)0x1234; // NOLINT void* pv3 = (void*)0x1234; // NOLINT
void* pv4 = (void*)0xABC0; // NOLINT void* pv4 = (void*)0xABC0; // NOLINT
const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3); const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4); const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4");
"p4");
} }
// Tests using other types of pointers in {EXPECT|ASSERT}_EQ. // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, OtherPointer) { TEST(EqAssertionTest, OtherPointer) {
ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr)); ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr), EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
reinterpret_cast<const int*>(0x1234)), reinterpret_cast<const int*>(0x1234)),
"0x1234"); "0x1234");
} }
skipping to change at line 4983 skipping to change at line 4894
class UnprintableChar { class UnprintableChar {
public: public:
explicit UnprintableChar(char ch) : char_(ch) {} explicit UnprintableChar(char ch) : char_(ch) {}
bool operator==(const UnprintableChar& rhs) const { bool operator==(const UnprintableChar& rhs) const {
return char_ == rhs.char_; return char_ == rhs.char_;
} }
bool operator!=(const UnprintableChar& rhs) const { bool operator!=(const UnprintableChar& rhs) const {
return char_ != rhs.char_; return char_ != rhs.char_;
} }
bool operator<(const UnprintableChar& rhs) const { bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; }
return char_ < rhs.char_;
}
bool operator<=(const UnprintableChar& rhs) const { bool operator<=(const UnprintableChar& rhs) const {
return char_ <= rhs.char_; return char_ <= rhs.char_;
} }
bool operator>(const UnprintableChar& rhs) const { bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; }
return char_ > rhs.char_;
}
bool operator>=(const UnprintableChar& rhs) const { bool operator>=(const UnprintableChar& rhs) const {
return char_ >= rhs.char_; return char_ >= rhs.char_;
} }
private: private:
char char_; char char_;
}; };
// Tests that ASSERT_EQ() and friends don't require the arguments to // Tests that ASSERT_EQ() and friends don't require the arguments to
// be printable. // be printable.
skipping to change at line 5053 skipping to change at line 4960
int Bar() const { return 1; } int Bar() const { return 1; }
// Declares the friend tests that can access the private member // Declares the friend tests that can access the private member
// Bar(). // Bar().
FRIEND_TEST(FRIEND_TEST_Test, TEST); FRIEND_TEST(FRIEND_TEST_Test, TEST);
FRIEND_TEST(FRIEND_TEST_Test2, TEST_F); FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
}; };
// Tests that the FRIEND_TEST declaration allows a TEST to access a // Tests that the FRIEND_TEST declaration allows a TEST to access a
// class's private members. This should compile. // class's private members. This should compile.
TEST(FRIEND_TEST_Test, TEST) { TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); }
ASSERT_EQ(1, Foo().Bar());
}
// The fixture needed to test using FRIEND_TEST with TEST_F. // The fixture needed to test using FRIEND_TEST with TEST_F.
class FRIEND_TEST_Test2 : public Test { class FRIEND_TEST_Test2 : public Test {
protected: protected:
Foo foo; Foo foo;
}; };
// Tests that the FRIEND_TEST declaration allows a TEST_F to access a // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
// class's private members. This should compile. // class's private members. This should compile.
TEST_F(FRIEND_TEST_Test2, TEST_F) { TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); }
ASSERT_EQ(1, foo.Bar());
}
// Tests the life cycle of Test objects. // Tests the life cycle of Test objects.
// The test fixture for testing the life cycle of Test objects. // The test fixture for testing the life cycle of Test objects.
// //
// This class counts the number of live test objects that uses this // This class counts the number of live test objects that uses this
// fixture. // fixture.
class TestLifeCycleTest : public Test { class TestLifeCycleTest : public Test {
protected: protected:
// Constructor. Increments the number of test objects that uses // Constructor. Increments the number of test objects that uses
skipping to change at line 5202 skipping to change at line 5105
ConvertibleToAssertionResult obj; ConvertibleToAssertionResult obj;
EXPECT_TRUE(obj); EXPECT_TRUE(obj);
} }
// Tests streaming a user type whose definition and operator << are // Tests streaming a user type whose definition and operator << are
// both in the global namespace. // both in the global namespace.
class Base { class Base {
public: public:
explicit Base(int an_x) : x_(an_x) {} explicit Base(int an_x) : x_(an_x) {}
int x() const { return x_; } int x() const { return x_; }
private: private:
int x_; int x_;
}; };
std::ostream& operator<<(std::ostream& os, std::ostream& operator<<(std::ostream& os, const Base& val) {
const Base& val) {
return os << val.x(); return os << val.x();
} }
std::ostream& operator<<(std::ostream& os, std::ostream& operator<<(std::ostream& os, const Base* pointer) {
const Base* pointer) {
return os << "(" << pointer->x() << ")"; return os << "(" << pointer->x() << ")";
} }
TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) { TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
Message msg; Message msg;
Base a(1); Base a(1);
msg << a << &a; // Uses ::operator<<. msg << a << &a; // Uses ::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str()); EXPECT_STREQ("1(1)", msg.GetString().c_str());
} }
// Tests streaming a user type whose definition and operator<< are // Tests streaming a user type whose definition and operator<< are
// both in an unnamed namespace. // both in an unnamed namespace.
namespace { namespace {
class MyTypeInUnnamedNameSpace : public Base { class MyTypeInUnnamedNameSpace : public Base {
public: public:
explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {} explicit MyTypeInUnnamedNameSpace(int an_x) : Base(an_x) {}
}; };
std::ostream& operator<<(std::ostream& os, std::ostream& operator<<(std::ostream& os,
const MyTypeInUnnamedNameSpace& val) { const MyTypeInUnnamedNameSpace& val) {
return os << val.x(); return os << val.x();
} }
std::ostream& operator<<(std::ostream& os, std::ostream& operator<<(std::ostream& os,
const MyTypeInUnnamedNameSpace* pointer) { const MyTypeInUnnamedNameSpace* pointer) {
return os << "(" << pointer->x() << ")"; return os << "(" << pointer->x() << ")";
} }
} // namespace } // namespace
skipping to change at line 5252 skipping to change at line 5154
msg << a << &a; // Uses <unnamed_namespace>::operator<<. msg << a << &a; // Uses <unnamed_namespace>::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str()); EXPECT_STREQ("1(1)", msg.GetString().c_str());
} }
// Tests streaming a user type whose definition and operator<< are // Tests streaming a user type whose definition and operator<< are
// both in a user namespace. // both in a user namespace.
namespace namespace1 { namespace namespace1 {
class MyTypeInNameSpace1 : public Base { class MyTypeInNameSpace1 : public Base {
public: public:
explicit MyTypeInNameSpace1(int an_x): Base(an_x) {} explicit MyTypeInNameSpace1(int an_x) : Base(an_x) {}
}; };
std::ostream& operator<<(std::ostream& os, std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) {
const MyTypeInNameSpace1& val) {
return os << val.x(); return os << val.x();
} }
std::ostream& operator<<(std::ostream& os, std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) {
const MyTypeInNameSpace1* pointer) {
return os << "(" << pointer->x() << ")"; return os << "(" << pointer->x() << ")";
} }
} // namespace namespace1 } // namespace namespace1
TEST(MessageTest, CanStreamUserTypeInUserNameSpace) { TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
Message msg; Message msg;
namespace1::MyTypeInNameSpace1 a(1); namespace1::MyTypeInNameSpace1 a(1);
msg << a << &a; // Uses namespace1::operator<<. msg << a << &a; // Uses namespace1::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str()); EXPECT_STREQ("1(1)", msg.GetString().c_str());
} }
// Tests streaming a user type whose definition is in a user namespace // Tests streaming a user type whose definition is in a user namespace
// but whose operator<< is in the global namespace. // but whose operator<< is in the global namespace.
namespace namespace2 { namespace namespace2 {
class MyTypeInNameSpace2 : public ::Base { class MyTypeInNameSpace2 : public ::Base {
public: public:
explicit MyTypeInNameSpace2(int an_x): Base(an_x) {} explicit MyTypeInNameSpace2(int an_x) : Base(an_x) {}
}; };
} // namespace namespace2 } // namespace namespace2
std::ostream& operator<<(std::ostream& os, std::ostream& operator<<(std::ostream& os,
const namespace2::MyTypeInNameSpace2& val) { const namespace2::MyTypeInNameSpace2& val) {
return os << val.x(); return os << val.x();
} }
std::ostream& operator<<(std::ostream& os, std::ostream& operator<<(std::ostream& os,
const namespace2::MyTypeInNameSpace2* pointer) { const namespace2::MyTypeInNameSpace2* pointer) {
return os << "(" << pointer->x() << ")"; return os << "(" << pointer->x() << ")";
} }
skipping to change at line 5308 skipping to change at line 5208
TEST(MessageTest, NullPointers) { TEST(MessageTest, NullPointers) {
Message msg; Message msg;
char* const p1 = nullptr; char* const p1 = nullptr;
unsigned char* const p2 = nullptr; unsigned char* const p2 = nullptr;
int* p3 = nullptr; int* p3 = nullptr;
double* p4 = nullptr; double* p4 = nullptr;
bool* p5 = nullptr; bool* p5 = nullptr;
Message* p6 = nullptr; Message* p6 = nullptr;
msg << p1 << p2 << p3 << p4 << p5 << p6; msg << p1 << p2 << p3 << p4 << p5 << p6;
ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str());
msg.GetString().c_str());
} }
// Tests streaming wide strings to testing::Message. // Tests streaming wide strings to testing::Message.
TEST(MessageTest, WideStrings) { TEST(MessageTest, WideStrings) {
// Streams a NULL of type const wchar_t*. // Streams a NULL of type const wchar_t*.
const wchar_t* const_wstr = nullptr; const wchar_t* const_wstr = nullptr;
EXPECT_STREQ("(null)", EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str());
(Message() << const_wstr).GetString().c_str());
// Streams a NULL of type wchar_t*. // Streams a NULL of type wchar_t*.
wchar_t* wstr = nullptr; wchar_t* wstr = nullptr;
EXPECT_STREQ("(null)", EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str());
(Message() << wstr).GetString().c_str());
// Streams a non-NULL of type const wchar_t*. // Streams a non-NULL of type const wchar_t*.
const_wstr = L"abc\x8119"; const_wstr = L"abc\x8119";
EXPECT_STREQ("abc\xe8\x84\x99", EXPECT_STREQ("abc\xe8\x84\x99",
(Message() << const_wstr).GetString().c_str()); (Message() << const_wstr).GetString().c_str());
// Streams a non-NULL of type wchar_t*. // Streams a non-NULL of type wchar_t*.
wstr = const_cast<wchar_t*>(const_wstr); wstr = const_cast<wchar_t*>(const_wstr);
EXPECT_STREQ("abc\xe8\x84\x99", EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str());
(Message() << wstr).GetString().c_str());
} }
// This line tests that we can define tests in the testing namespace. // This line tests that we can define tests in the testing namespace.
namespace testing { namespace testing {
// Tests the TestInfo class. // Tests the TestInfo class.
class TestInfoTest : public Test { class TestInfoTest : public Test {
protected: protected:
static const TestInfo* GetTestInfo(const char* test_name) { static const TestInfo* GetTestInfo(const char* test_name) {
const TestSuite* const test_suite = const TestSuite* const test_suite =
GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr); GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
for (int i = 0; i < test_suite->total_test_count(); ++i) { for (int i = 0; i < test_suite->total_test_count(); ++i) {
const TestInfo* const test_info = test_suite->GetTestInfo(i); const TestInfo* const test_info = test_suite->GetTestInfo(i);
if (strcmp(test_name, test_info->name()) == 0) if (strcmp(test_name, test_info->name()) == 0) return test_info;
return test_info;
} }
return nullptr; return nullptr;
} }
static const TestResult* GetTestResult( static const TestResult* GetTestResult(const TestInfo* test_info) {
const TestInfo* test_info) {
return test_info->result(); return test_info->result();
} }
}; };
// Tests TestInfo::test_case_name() and TestInfo::name(). // Tests TestInfo::test_case_name() and TestInfo::name().
TEST_F(TestInfoTest, Names) { TEST_F(TestInfoTest, Names) {
const TestInfo* const test_info = GetTestInfo("Names"); const TestInfo* const test_info = GetTestInfo("Names");
ASSERT_STREQ("TestInfoTest", test_info->test_suite_name()); ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
ASSERT_STREQ("Names", test_info->name()); ASSERT_STREQ("Names", test_info->name());
skipping to change at line 5379 skipping to change at line 5273
TEST_F(TestInfoTest, result) { TEST_F(TestInfoTest, result) {
const TestInfo* const test_info = GetTestInfo("result"); const TestInfo* const test_info = GetTestInfo("result");
// Initially, there is no TestPartResult for this test. // Initially, there is no TestPartResult for this test.
ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
// After the previous assertion, there is still none. // After the previous assertion, there is still none.
ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
} }
#define VERIFY_CODE_LOCATION \ #define VERIFY_CODE_LOCATION \
const int expected_line = __LINE__ - 1; \ const int expected_line = __LINE__ - 1; \
const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \ const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
ASSERT_TRUE(test_info); \ ASSERT_TRUE(test_info); \
EXPECT_STREQ(__FILE__, test_info->file()); \ EXPECT_STREQ(__FILE__, test_info->file()); \
EXPECT_EQ(expected_line, test_info->line()) EXPECT_EQ(expected_line, test_info->line())
// clang-format off
TEST(CodeLocationForTEST, Verify) { TEST(CodeLocationForTEST, Verify) {
VERIFY_CODE_LOCATION; VERIFY_CODE_LOCATION;
} }
class CodeLocationForTESTF : public Test { class CodeLocationForTESTF : public Test {};
};
TEST_F(CodeLocationForTESTF, Verify) { TEST_F(CodeLocationForTESTF, Verify) {
VERIFY_CODE_LOCATION; VERIFY_CODE_LOCATION;
} }
class CodeLocationForTESTP : public TestWithParam<int> { class CodeLocationForTESTP : public TestWithParam<int> {};
};
TEST_P(CodeLocationForTESTP, Verify) { TEST_P(CodeLocationForTESTP, Verify) {
VERIFY_CODE_LOCATION; VERIFY_CODE_LOCATION;
} }
INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0)); INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
template <typename T> template <typename T>
class CodeLocationForTYPEDTEST : public Test { class CodeLocationForTYPEDTEST : public Test {};
};
TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int); TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
TYPED_TEST(CodeLocationForTYPEDTEST, Verify) { TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
VERIFY_CODE_LOCATION; VERIFY_CODE_LOCATION;
} }
template <typename T> template <typename T>
class CodeLocationForTYPEDTESTP : public Test { class CodeLocationForTYPEDTESTP : public Test {};
};
TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP); TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) { TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
VERIFY_CODE_LOCATION; VERIFY_CODE_LOCATION;
} }
REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify); REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int); INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
#undef VERIFY_CODE_LOCATION #undef VERIFY_CODE_LOCATION
// clang-format on
// Tests setting up and tearing down a test case. // Tests setting up and tearing down a test case.
// Legacy API is deprecated but still available // Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
class SetUpTestCaseTest : public Test { class SetUpTestCaseTest : public Test {
protected: protected:
// This will be called once before the first test in this test case // This will be called once before the first test in this test case
// is run. // is run.
static void SetUpTestCase() { static void SetUpTestCase() {
printf("Setting up the test case . . .\n"); printf("Setting up the test case . . .\n");
skipping to change at line 5490 skipping to change at line 5382
static const char* shared_resource_; static const char* shared_resource_;
}; };
int SetUpTestCaseTest::counter_ = 0; int SetUpTestCaseTest::counter_ = 0;
const char* SetUpTestCaseTest::shared_resource_ = nullptr; const char* SetUpTestCaseTest::shared_resource_ = nullptr;
// A test that uses the shared resource. // A test that uses the shared resource.
TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); } TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
// Another test that uses the shared resource. // Another test that uses the shared resource.
TEST_F(SetUpTestCaseTest, Test2) { TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); }
EXPECT_STREQ("123", shared_resource_);
}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Tests SetupTestSuite/TearDown TestSuite // Tests SetupTestSuite/TearDown TestSuite
class SetUpTestSuiteTest : public Test { class SetUpTestSuiteTest : public Test {
protected: protected:
// This will be called once before the first test in this test case // This will be called once before the first test in this test case
// is run. // is run.
static void SetUpTestSuite() { static void SetUpTestSuite() {
printf("Setting up the test suite . . .\n"); printf("Setting up the test suite . . .\n");
skipping to change at line 5575 skipping to change at line 5465
catch_exceptions(false), catch_exceptions(false),
death_test_use_fork(false), death_test_use_fork(false),
fail_fast(false), fail_fast(false),
filter(""), filter(""),
list_tests(false), list_tests(false),
output(""), output(""),
brief(false), brief(false),
print_time(true), print_time(true),
random_seed(0), random_seed(0),
repeat(1), repeat(1),
recreate_environments_when_repeating(true),
shuffle(false), shuffle(false),
stack_trace_depth(kMaxStackTraceDepth), stack_trace_depth(kMaxStackTraceDepth),
stream_result_to(""), stream_result_to(""),
throw_on_failure(false) {} throw_on_failure(false) {}
// Factory methods. // Factory methods.
// Creates a Flags struct where the gtest_also_run_disabled_tests flag has // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
// the given value. // the given value.
static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) { static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
skipping to change at line 5678 skipping to change at line 5569
} }
// Creates a Flags struct where the gtest_repeat flag has the given // Creates a Flags struct where the gtest_repeat flag has the given
// value. // value.
static Flags Repeat(int32_t repeat) { static Flags Repeat(int32_t repeat) {
Flags flags; Flags flags;
flags.repeat = repeat; flags.repeat = repeat;
return flags; return flags;
} }
// Creates a Flags struct where the gtest_recreate_environments_when_repeating
// flag has the given value.
static Flags RecreateEnvironmentsWhenRepeating(
bool recreate_environments_when_repeating) {
Flags flags;
flags.recreate_environments_when_repeating =
recreate_environments_when_repeating;
return flags;
}
// Creates a Flags struct where the gtest_shuffle flag has the given // Creates a Flags struct where the gtest_shuffle flag has the given
// value. // value.
static Flags Shuffle(bool shuffle) { static Flags Shuffle(bool shuffle) {
Flags flags; Flags flags;
flags.shuffle = shuffle; flags.shuffle = shuffle;
return flags; return flags;
} }
// Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
// the given value. // the given value.
skipping to change at line 5723 skipping to change at line 5624
bool catch_exceptions; bool catch_exceptions;
bool death_test_use_fork; bool death_test_use_fork;
bool fail_fast; bool fail_fast;
const char* filter; const char* filter;
bool list_tests; bool list_tests;
const char* output; const char* output;
bool brief; bool brief;
bool print_time; bool print_time;
int32_t random_seed; int32_t random_seed;
int32_t repeat; int32_t repeat;
bool recreate_environments_when_repeating;
bool shuffle; bool shuffle;
int32_t stack_trace_depth; int32_t stack_trace_depth;
const char* stream_result_to; const char* stream_result_to;
bool throw_on_failure; bool throw_on_failure;
}; };
// Fixture for testing ParseGoogleTestFlagsOnly(). // Fixture for testing ParseGoogleTestFlagsOnly().
class ParseFlagsTest : public Test { class ParseFlagsTest : public Test {
protected: protected:
// Clears the flags before each test. // Clears the flags before each test.
void SetUp() override { void SetUp() override {
GTEST_FLAG(also_run_disabled_tests) = false; GTEST_FLAG_SET(also_run_disabled_tests, false);
GTEST_FLAG(break_on_failure) = false; GTEST_FLAG_SET(break_on_failure, false);
GTEST_FLAG(catch_exceptions) = false; GTEST_FLAG_SET(catch_exceptions, false);
GTEST_FLAG(death_test_use_fork) = false; GTEST_FLAG_SET(death_test_use_fork, false);
GTEST_FLAG(fail_fast) = false; GTEST_FLAG_SET(fail_fast, false);
GTEST_FLAG(filter) = ""; GTEST_FLAG_SET(filter, "");
GTEST_FLAG(list_tests) = false; GTEST_FLAG_SET(list_tests, false);
GTEST_FLAG(output) = ""; GTEST_FLAG_SET(output, "");
GTEST_FLAG(brief) = false; GTEST_FLAG_SET(brief, false);
GTEST_FLAG(print_time) = true; GTEST_FLAG_SET(print_time, true);
GTEST_FLAG(random_seed) = 0; GTEST_FLAG_SET(random_seed, 0);
GTEST_FLAG(repeat) = 1; GTEST_FLAG_SET(repeat, 1);
GTEST_FLAG(shuffle) = false; GTEST_FLAG_SET(recreate_environments_when_repeating, true);
GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; GTEST_FLAG_SET(shuffle, false);
GTEST_FLAG(stream_result_to) = ""; GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
GTEST_FLAG(throw_on_failure) = false; GTEST_FLAG_SET(stream_result_to, "");
GTEST_FLAG_SET(throw_on_failure, false);
} }
// Asserts that two narrow or wide string arrays are equal. // Asserts that two narrow or wide string arrays are equal.
template <typename CharType> template <typename CharType>
static void AssertStringArrayEq(int size1, CharType** array1, int size2, static void AssertStringArrayEq(int size1, CharType** array1, int size2,
CharType** array2) { CharType** array2) {
ASSERT_EQ(size1, size2) << " Array sizes different."; ASSERT_EQ(size1, size2) << " Array sizes different.";
for (int i = 0; i != size1; i++) { for (int i = 0; i != size1; i++) {
ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i; ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
} }
} }
// Verifies that the flag values match the expected values. // Verifies that the flag values match the expected values.
static void CheckFlags(const Flags& expected) { static void CheckFlags(const Flags& expected) {
EXPECT_EQ(expected.also_run_disabled_tests, EXPECT_EQ(expected.also_run_disabled_tests,
GTEST_FLAG(also_run_disabled_tests)); GTEST_FLAG_GET(also_run_disabled_tests));
EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure)); EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));
EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions)); EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));
EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork)); EXPECT_EQ(expected.death_test_use_fork,
EXPECT_EQ(expected.fail_fast, GTEST_FLAG(fail_fast)); GTEST_FLAG_GET(death_test_use_fork));
EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str()); EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));
EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests)); EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());
EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str()); EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));
EXPECT_EQ(expected.brief, GTEST_FLAG(brief)); EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());
EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time)); EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));
EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed)); EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));
EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat)); EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));
EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle)); EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));
EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth)); EXPECT_EQ(expected.recreate_environments_when_repeating,
GTEST_FLAG_GET(recreate_environments_when_repeating));
EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));
EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));
EXPECT_STREQ(expected.stream_result_to, EXPECT_STREQ(expected.stream_result_to,
GTEST_FLAG(stream_result_to).c_str()); GTEST_FLAG_GET(stream_result_to).c_str());
EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure)); EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));
} }
// Parses a command line (specified by argc1 and argv1), then // Parses a command line (specified by argc1 and argv1), then
// verifies that the flag values are expected and that the // verifies that the flag values are expected and that the
// recognized flags are removed from the command line. // recognized flags are removed from the command line.
template <typename CharType> template <typename CharType>
static void TestParsingFlags(int argc1, const CharType** argv1, static void TestParsingFlags(int argc1, const CharType** argv1, int argc2,
int argc2, const CharType** argv2, const CharType** argv2, const Flags& expected,
const Flags& expected, bool should_print_help) { bool should_print_help) {
const bool saved_help_flag = ::testing::internal::g_help_flag; const bool saved_help_flag = ::testing::internal::g_help_flag;
::testing::internal::g_help_flag = false; ::testing::internal::g_help_flag = false;
# if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
CaptureStdout(); CaptureStdout();
# endif #endif
// Parses the command line. // Parses the command line.
internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1)); internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
# if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
const std::string captured_stdout = GetCapturedStdout(); const std::string captured_stdout = GetCapturedStdout();
# endif #endif
// Verifies the flag values. // Verifies the flag values.
CheckFlags(expected); CheckFlags(expected);
// Verifies that the recognized flags are removed from the command // Verifies that the recognized flags are removed from the command
// line. // line.
AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2); AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
// ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
// help message for the flags it recognizes. // help message for the flags it recognizes.
EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag); EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
# if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
const char* const expected_help_fragment = const char* const expected_help_fragment =
"This program contains tests written using"; "This program contains tests written using";
if (should_print_help) { if (should_print_help) {
EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout); EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
} else { } else {
EXPECT_PRED_FORMAT2(IsNotSubstring, EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment,
expected_help_fragment, captured_stdout); captured_stdout);
} }
# endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
::testing::internal::g_help_flag = saved_help_flag; ::testing::internal::g_help_flag = saved_help_flag;
} }
// This macro wraps TestParsingFlags s.t. the user doesn't need // This macro wraps TestParsingFlags s.t. the user doesn't need
// to specify the array sizes. // to specify the array sizes.
# define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \ TestParsingFlags(sizeof(argv1) / sizeof(*argv1) - 1, argv1, \
sizeof(argv2)/sizeof(*argv2) - 1, argv2, \ sizeof(argv2) / sizeof(*argv2) - 1, argv2, expected, \
expected, should_print_help) should_print_help)
}; };
// Tests parsing an empty command line. // Tests parsing an empty command line.
TEST_F(ParseFlagsTest, Empty) { TEST_F(ParseFlagsTest, Empty) {
const char* argv[] = {nullptr}; const char* argv[] = {nullptr};
const char* argv2[] = {nullptr}; const char* argv2[] = {nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
} }
skipping to change at line 5867 skipping to change at line 5773
// Tests parsing --gtest_fail_fast. // Tests parsing --gtest_fail_fast.
TEST_F(ParseFlagsTest, FailFast) { TEST_F(ParseFlagsTest, FailFast) {
const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr}; const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
} }
// Tests parsing a bad --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterBad) {
const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
}
// Tests parsing an empty --gtest_filter flag. // Tests parsing an empty --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterEmpty) { TEST_F(ParseFlagsTest, FilterEmpty) {
const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr}; const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
} }
// Tests parsing a non-empty --gtest_filter flag. // Tests parsing a non-empty --gtest_filter flag.
skipping to change at line 6028 skipping to change at line 5925
// Tests parsing --gtest_list_tests=F. // Tests parsing --gtest_list_tests=F.
TEST_F(ParseFlagsTest, ListTestsFalse_F) { TEST_F(ParseFlagsTest, ListTestsFalse_F) {
const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr}; const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
} }
// Tests parsing --gtest_output (invalid).
TEST_F(ParseFlagsTest, OutputEmpty) {
const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
}
// Tests parsing --gtest_output=xml // Tests parsing --gtest_output=xml
TEST_F(ParseFlagsTest, OutputXml) { TEST_F(ParseFlagsTest, OutputXml) {
const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr}; const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
} }
// Tests parsing --gtest_output=xml:file // Tests parsing --gtest_output=xml:file
skipping to change at line 6062 skipping to change at line 5950
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
} }
// Tests parsing --gtest_output=xml:directory/path/ // Tests parsing --gtest_output=xml:directory/path/
TEST_F(ParseFlagsTest, OutputXmlDirectory) { TEST_F(ParseFlagsTest, OutputXmlDirectory) {
const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/", const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
nullptr}; nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"),
Flags::Output("xml:directory/path/"), false); false);
} }
// Tests having a --gtest_brief flag // Tests having a --gtest_brief flag
TEST_F(ParseFlagsTest, BriefFlag) { TEST_F(ParseFlagsTest, BriefFlag) {
const char* argv[] = {"foo.exe", "--gtest_brief", nullptr}; const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
} }
skipping to change at line 6156 skipping to change at line 6044
// Tests parsing --gtest_repeat=number // Tests parsing --gtest_repeat=number
TEST_F(ParseFlagsTest, Repeat) { TEST_F(ParseFlagsTest, Repeat) {
const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr}; const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
} }
// Tests parsing --gtest_recreate_environments_when_repeating
TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {
const char* argv[] = {
"foo.exe",
"--gtest_recreate_environments_when_repeating=0",
nullptr,
};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(
argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);
}
// Tests having a --gtest_also_run_disabled_tests flag // Tests having a --gtest_also_run_disabled_tests flag
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) { TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr}; const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
false); false);
} }
skipping to change at line 6230 skipping to change at line 6132
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
} }
TEST_F(ParseFlagsTest, StreamResultTo) { TEST_F(ParseFlagsTest, StreamResultTo) {
const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234", const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
nullptr}; nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_( GTEST_TEST_PARSING_FLAGS_(argv, argv2,
argv, argv2, Flags::StreamResultTo("localhost:1234"), false); Flags::StreamResultTo("localhost:1234"), false);
} }
// Tests parsing --gtest_throw_on_failure. // Tests parsing --gtest_throw_on_failure.
TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) { TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr}; const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
} }
skipping to change at line 6262 skipping to change at line 6164
// Tests parsing a --gtest_throw_on_failure flag that has a "true" // Tests parsing a --gtest_throw_on_failure flag that has a "true"
// definition. // definition.
TEST_F(ParseFlagsTest, ThrowOnFailureTrue) { TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr}; const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
} }
# if GTEST_OS_WINDOWS // Tests parsing a bad --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterBad) {
const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST
// Invalid flag arguments are a fatal error when using the Abseil Flags.
EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true),
testing::ExitedWithCode(1),
"ERROR: Missing the value for the flag 'gtest_filter'");
#elif !GTEST_HAS_ABSL
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
#else
static_cast<void>(argv);
static_cast<void>(argv2);
#endif
}
// Tests parsing --gtest_output (invalid).
TEST_F(ParseFlagsTest, OutputEmpty) {
const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST
// Invalid flag arguments are a fatal error when using the Abseil Flags.
EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true),
testing::ExitedWithCode(1),
"ERROR: Missing the value for the flag 'gtest_output'");
#elif !GTEST_HAS_ABSL
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
#else
static_cast<void>(argv);
static_cast<void>(argv2);
#endif
}
#if GTEST_HAS_ABSL
TEST_F(ParseFlagsTest, AbseilPositionalFlags) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", "--",
"--other_flag", nullptr};
// When using Abseil flags, it should be possible to pass flags not recognized
// using "--" to delimit positional arguments. These flags should be returned
// though argv.
const char* argv2[] = {"foo.exe", "--other_flag", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
}
#endif
#if GTEST_OS_WINDOWS
// Tests parsing wide strings. // Tests parsing wide strings.
TEST_F(ParseFlagsTest, WideStrings) { TEST_F(ParseFlagsTest, WideStrings) {
const wchar_t* argv[] = { const wchar_t* argv[] = {L"foo.exe",
L"foo.exe", L"--gtest_filter=Foo*",
L"--gtest_filter=Foo*", L"--gtest_list_tests=1",
L"--gtest_list_tests=1", L"--gtest_break_on_failure",
L"--gtest_break_on_failure", L"--non_gtest_flag",
L"--non_gtest_flag", NULL};
NULL
};
const wchar_t* argv2[] = { const wchar_t* argv2[] = {L"foo.exe", L"--non_gtest_flag", NULL};
L"foo.exe",
L"--non_gtest_flag",
NULL
};
Flags expected_flags; Flags expected_flags;
expected_flags.break_on_failure = true; expected_flags.break_on_failure = true;
expected_flags.filter = "Foo*"; expected_flags.filter = "Foo*";
expected_flags.list_tests = true; expected_flags.list_tests = true;
GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
#if GTEST_USE_OWN_FLAGFILE_FLAG_ #if GTEST_USE_OWN_FLAGFILE_FLAG_
class FlagfileTest : public ParseFlagsTest { class FlagfileTest : public ParseFlagsTest {
public: public:
void SetUp() override { void SetUp() override {
ParseFlagsTest::SetUp(); ParseFlagsTest::SetUp();
testdata_path_.Set(internal::FilePath( testdata_path_.Set(internal::FilePath(
testing::TempDir() + internal::GetCurrentExecutableName().string() + testing::TempDir() + internal::GetCurrentExecutableName().string() +
"_flagfile_test")); "_flagfile_test"));
skipping to change at line 6335 skipping to change at line 6283
const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
} }
// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile. // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
TEST_F(FlagfileTest, FilterNonEmpty) { TEST_F(FlagfileTest, FilterNonEmpty) {
internal::FilePath flagfile_path(CreateFlagfile( internal::FilePath flagfile_path(
"--" GTEST_FLAG_PREFIX_ "filter=abc")); CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc"));
std::string flagfile_flag = std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
} }
// Tests passing several flags via --gtest_flagfile. // Tests passing several flags via --gtest_flagfile.
TEST_F(FlagfileTest, SeveralFlags) { TEST_F(FlagfileTest, SeveralFlags) {
internal::FilePath flagfile_path(CreateFlagfile( internal::FilePath flagfile_path(
"--" GTEST_FLAG_PREFIX_ "filter=abc\n" CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc\n"
"--" GTEST_FLAG_PREFIX_ "break_on_failure\n" "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
"--" GTEST_FLAG_PREFIX_ "list_tests")); "--" GTEST_FLAG_PREFIX_ "list_tests"));
std::string flagfile_flag = std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
const char* argv2[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr};
Flags expected_flags; Flags expected_flags;
expected_flags.break_on_failure = true; expected_flags.break_on_failure = true;
expected_flags.filter = "abc"; expected_flags.filter = "abc";
skipping to change at line 6376 skipping to change at line 6324
} }
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
// Tests current_test_info() in UnitTest. // Tests current_test_info() in UnitTest.
class CurrentTestInfoTest : public Test { class CurrentTestInfoTest : public Test {
protected: protected:
// Tests that current_test_info() returns NULL before the first test in // Tests that current_test_info() returns NULL before the first test in
// the test case is run. // the test case is run.
static void SetUpTestSuite() { static void SetUpTestSuite() {
// There should be no tests running at this point. // There should be no tests running at this point.
const TestInfo* test_info = const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
UnitTest::GetInstance()->current_test_info();
EXPECT_TRUE(test_info == nullptr) EXPECT_TRUE(test_info == nullptr)
<< "There should be no tests running at this point."; << "There should be no tests running at this point.";
} }
// Tests that current_test_info() returns NULL after the last test in // Tests that current_test_info() returns NULL after the last test in
// the test case has run. // the test case has run.
static void TearDownTestSuite() { static void TearDownTestSuite() {
const TestInfo* test_info = const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
UnitTest::GetInstance()->current_test_info();
EXPECT_TRUE(test_info == nullptr) EXPECT_TRUE(test_info == nullptr)
<< "There should be no tests running at this point."; << "There should be no tests running at this point.";
} }
}; };
// Tests that current_test_info() returns TestInfo for currently running // Tests that current_test_info() returns TestInfo for currently running
// test by checking the expected test name against the actual one. // test by checking the expected test name against the actual one.
TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) { TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
const TestInfo* test_info = const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info) ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo."; << "There is a test running so we should have a valid TestInfo.";
EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
<< "Expected the name of the currently running test suite."; << "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name()) EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test."; << "Expected the name of the currently running test.";
} }
// Tests that current_test_info() returns TestInfo for currently running // Tests that current_test_info() returns TestInfo for currently running
// test by checking the expected test name against the actual one. We // test by checking the expected test name against the actual one. We
// use this test to see that the TestInfo object actually changed from // use this test to see that the TestInfo object actually changed from
// the previous invocation. // the previous invocation.
TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) { TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
const TestInfo* test_info = const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info) ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo."; << "There is a test running so we should have a valid TestInfo.";
EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
<< "Expected the name of the currently running test suite."; << "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name()) EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test."; << "Expected the name of the currently running test.";
} }
} // namespace testing } // namespace testing
skipping to change at line 6470 skipping to change at line 6414
void SetUp() override { Test::SetUp(); } void SetUp() override { Test::SetUp(); }
void TearDown() override { Test::TearDown(); } void TearDown() override { Test::TearDown(); }
}; };
// StreamingAssertionsTest tests the streaming versions of a representative // StreamingAssertionsTest tests the streaming versions of a representative
// sample of assertions. // sample of assertions.
TEST(StreamingAssertionsTest, Unconditional) { TEST(StreamingAssertionsTest, Unconditional) {
SUCCEED() << "expected success"; SUCCEED() << "expected success";
EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure", EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
"expected failure"); "expected failure");
EXPECT_FATAL_FAILURE(FAIL() << "expected failure", EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure");
"expected failure");
} }
#ifdef __BORLANDC__ #ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code" // Silences warnings: "Condition is always true", "Unreachable code"
# pragma option push -w-ccc -w-rch #pragma option push -w-ccc -w-rch
#endif #endif
TEST(StreamingAssertionsTest, Truth) { TEST(StreamingAssertionsTest, Truth) {
EXPECT_TRUE(true) << "unexpected failure"; EXPECT_TRUE(true) << "unexpected failure";
ASSERT_TRUE(true) << "unexpected failure"; ASSERT_TRUE(true) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure", EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
"expected failure"); "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure", EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
"expected failure"); "expected failure");
} }
skipping to change at line 6499 skipping to change at line 6442
EXPECT_FALSE(false) << "unexpected failure"; EXPECT_FALSE(false) << "unexpected failure";
ASSERT_FALSE(false) << "unexpected failure"; ASSERT_FALSE(false) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure", EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
"expected failure"); "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure", EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
"expected failure"); "expected failure");
} }
#ifdef __BORLANDC__ #ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them // Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop #pragma option pop
#endif #endif
TEST(StreamingAssertionsTest, IntegerEquals) { TEST(StreamingAssertionsTest, IntegerEquals) {
EXPECT_EQ(1, 1) << "unexpected failure"; EXPECT_EQ(1, 1) << "unexpected failure";
ASSERT_EQ(1, 1) << "unexpected failure"; ASSERT_EQ(1, 1) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure", EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
"expected failure"); "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure", EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
"expected failure"); "expected failure");
} }
skipping to change at line 6570 skipping to change at line 6513
"expected failure"); "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure", EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
"expected failure"); "expected failure");
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
TEST(StreamingAssertionsTest, Throw) { TEST(StreamingAssertionsTest, Throw) {
EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure"; EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure"; ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) << EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool)
"expected failure", "expected failure"); << "expected failure",
EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) << "expected failure");
"expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool)
<< "expected failure",
"expected failure");
} }
TEST(StreamingAssertionsTest, NoThrow) { TEST(StreamingAssertionsTest, NoThrow) {
EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure"; EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure"; ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) << EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger())
"expected failure", "expected failure"); << "expected failure",
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure");
"expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure",
"expected failure");
} }
TEST(StreamingAssertionsTest, AnyThrow) { TEST(StreamingAssertionsTest, AnyThrow) {
EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) << EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing())
"expected failure", "expected failure"); << "expected failure",
EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure");
"expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure",
"expected failure");
} }
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
// Tests that Google Test correctly decides whether to use colors in the output. // Tests that Google Test correctly decides whether to use colors in the output.
TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
GTEST_FLAG(color) = "yes"; GTEST_FLAG_SET(color, "yes");
SetEnv("TERM", "xterm"); // TERM supports colors. SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
SetEnv("TERM", "dumb"); // TERM doesn't support colors. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
} }
TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
SetEnv("TERM", "dumb"); // TERM doesn't support colors. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
GTEST_FLAG(color) = "True"; GTEST_FLAG_SET(color, "True");
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
GTEST_FLAG(color) = "t"; GTEST_FLAG_SET(color, "t");
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
GTEST_FLAG(color) = "1"; GTEST_FLAG_SET(color, "1");
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
} }
TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
GTEST_FLAG(color) = "no"; GTEST_FLAG_SET(color, "no");
SetEnv("TERM", "xterm"); // TERM supports colors. SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
SetEnv("TERM", "dumb"); // TERM doesn't support colors. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
} }
TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
SetEnv("TERM", "xterm"); // TERM supports colors. SetEnv("TERM", "xterm"); // TERM supports colors.
GTEST_FLAG(color) = "F"; GTEST_FLAG_SET(color, "F");
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
GTEST_FLAG(color) = "0"; GTEST_FLAG_SET(color, "0");
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
GTEST_FLAG(color) = "unknown"; GTEST_FLAG_SET(color, "unknown");
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
} }
TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
GTEST_FLAG(color) = "auto"; GTEST_FLAG_SET(color, "auto");
SetEnv("TERM", "xterm"); // TERM supports colors. SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
} }
TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
GTEST_FLAG(color) = "auto"; GTEST_FLAG_SET(color, "auto");
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
// On Windows, we ignore the TERM variable as it's usually not set. // On Windows, we ignore the TERM variable as it's usually not set.
SetEnv("TERM", "dumb"); SetEnv("TERM", "dumb");
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", ""); SetEnv("TERM", "");
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm"); SetEnv("TERM", "xterm");
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
#else #else
// On non-Windows platforms, we rely on TERM to determine if the // On non-Windows platforms, we rely on TERM to determine if the
// terminal supports colors. // terminal supports colors.
SetEnv("TERM", "dumb"); // TERM doesn't support colors. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "emacs"); // TERM doesn't support colors. SetEnv("TERM", "emacs"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "vt100"); // TERM doesn't support colors. SetEnv("TERM", "vt100"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm"); // TERM supports colors. SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-color"); // TERM supports colors. SetEnv("TERM", "xterm-color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-256color"); // TERM supports colors. SetEnv("TERM", "xterm-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "screen"); // TERM supports colors. SetEnv("TERM", "screen"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "screen-256color"); // TERM supports colors. SetEnv("TERM", "screen-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "tmux"); // TERM supports colors. SetEnv("TERM", "tmux"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "tmux-256color"); // TERM supports colors. SetEnv("TERM", "tmux-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "rxvt-unicode"); // TERM supports colors. SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors. SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "linux"); // TERM supports colors. SetEnv("TERM", "linux"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "cygwin"); // TERM supports colors. SetEnv("TERM", "cygwin"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
} }
// Verifies that StaticAssertTypeEq works in a namespace scope. // Verifies that StaticAssertTypeEq works in a namespace scope.
static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>(); static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ = static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
StaticAssertTypeEq<const int, const int>(); StaticAssertTypeEq<const int, const int>();
skipping to change at line 6836 skipping to change at line 6783
ADD_FAILURE(); ADD_FAILURE();
const bool has_failure = HasFailureHelper(); const bool has_failure = HasFailureHelper();
ClearCurrentTestPartResults(); ClearCurrentTestPartResults();
EXPECT_TRUE(has_failure); EXPECT_TRUE(has_failure);
} }
class TestListener : public EmptyTestEventListener { class TestListener : public EmptyTestEventListener {
public: public:
TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {} TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
TestListener(int* on_start_counter, bool* is_destroyed) TestListener(int* on_start_counter, bool* is_destroyed)
: on_start_counter_(on_start_counter), : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {}
is_destroyed_(is_destroyed) {}
~TestListener() override { ~TestListener() override {
if (is_destroyed_) if (is_destroyed_) *is_destroyed_ = true;
*is_destroyed_ = true;
} }
protected: protected:
void OnTestProgramStart(const UnitTest& /*unit_test*/) override { void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
if (on_start_counter_ != nullptr) (*on_start_counter_)++; if (on_start_counter_ != nullptr) (*on_start_counter_)++;
} }
private: private:
int* on_start_counter_; int* on_start_counter_;
bool* is_destroyed_; bool* is_destroyed_;
skipping to change at line 6898 skipping to change at line 6843
// Tests that a listener Append'ed to a TestEventListeners list starts // Tests that a listener Append'ed to a TestEventListeners list starts
// receiving events. // receiving events.
TEST(TestEventListenersTest, Append) { TEST(TestEventListenersTest, Append) {
int on_start_counter = 0; int on_start_counter = 0;
bool is_destroyed = false; bool is_destroyed = false;
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{ {
TestEventListeners listeners; TestEventListeners listeners;
listeners.Append(listener); listeners.Append(listener);
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter); EXPECT_EQ(1, on_start_counter);
} }
EXPECT_TRUE(is_destroyed); EXPECT_TRUE(is_destroyed);
} }
// Tests that listeners receive events in the order they were appended to // Tests that listeners receive events in the order they were appended to
// the list, except for *End requests, which must be received in the reverse // the list, except for *End requests, which must be received in the reverse
// order. // order.
class SequenceTestingListener : public EmptyTestEventListener { class SequenceTestingListener : public EmptyTestEventListener {
public: public:
skipping to change at line 6942 skipping to change at line 6887
private: private:
std::string GetEventDescription(const char* method) { std::string GetEventDescription(const char* method) {
Message message; Message message;
message << id_ << "." << method; message << id_ << "." << method;
return message.GetString(); return message.GetString();
} }
std::vector<std::string>* vector_; std::vector<std::string>* vector_;
const char* const id_; const char* const id_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener); SequenceTestingListener(const SequenceTestingListener&) = delete;
SequenceTestingListener& operator=(const SequenceTestingListener&) = delete;
}; };
TEST(EventListenerTest, AppendKeepsOrder) { TEST(EventListenerTest, AppendKeepsOrder) {
std::vector<std::string> vec; std::vector<std::string> vec;
TestEventListeners listeners; TestEventListeners listeners;
listeners.Append(new SequenceTestingListener(&vec, "1st")); listeners.Append(new SequenceTestingListener(&vec, "1st"));
listeners.Append(new SequenceTestingListener(&vec, "2nd")); listeners.Append(new SequenceTestingListener(&vec, "2nd"));
listeners.Append(new SequenceTestingListener(&vec, "3rd")); listeners.Append(new SequenceTestingListener(&vec, "3rd"));
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
ASSERT_EQ(3U, vec.size()); ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str()); EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str()); EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str()); EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
vec.clear(); vec.clear();
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramEnd(*UnitTest::GetInstance());
ASSERT_EQ(3U, vec.size()); ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str()); EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str()); EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str()); EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
vec.clear(); vec.clear();
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance(), 0); ->OnTestIterationStart(*UnitTest::GetInstance(), 0);
ASSERT_EQ(3U, vec.size()); ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str()); EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str()); EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str()); EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
vec.clear(); vec.clear();
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance(), 0); ->OnTestIterationEnd(*UnitTest::GetInstance(), 0);
ASSERT_EQ(3U, vec.size()); ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str()); EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str()); EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str()); EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
} }
// Tests that a listener removed from a TestEventListeners list stops receiving // Tests that a listener removed from a TestEventListeners list stops receiving
// events and is not deleted when the list is destroyed. // events and is not deleted when the list is destroyed.
TEST(TestEventListenersTest, Release) { TEST(TestEventListenersTest, Release) {
int on_start_counter = 0; int on_start_counter = 0;
bool is_destroyed = false; bool is_destroyed = false;
// Although Append passes the ownership of this object to the list, // Although Append passes the ownership of this object to the list,
// the following calls release it, and we need to delete it before the // the following calls release it, and we need to delete it before the
// test ends. // test ends.
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{ {
TestEventListeners listeners; TestEventListeners listeners;
listeners.Append(listener); listeners.Append(listener);
EXPECT_EQ(listener, listeners.Release(listener)); EXPECT_EQ(listener, listeners.Release(listener));
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
EXPECT_TRUE(listeners.Release(listener) == nullptr); EXPECT_TRUE(listeners.Release(listener) == nullptr);
} }
EXPECT_EQ(0, on_start_counter); EXPECT_EQ(0, on_start_counter);
EXPECT_FALSE(is_destroyed); EXPECT_FALSE(is_destroyed);
delete listener; delete listener;
} }
// Tests that no events are forwarded when event forwarding is disabled. // Tests that no events are forwarded when event forwarding is disabled.
TEST(EventListenerTest, SuppressEventForwarding) { TEST(EventListenerTest, SuppressEventForwarding) {
int on_start_counter = 0; int on_start_counter = 0;
TestListener* listener = new TestListener(&on_start_counter, nullptr); TestListener* listener = new TestListener(&on_start_counter, nullptr);
TestEventListeners listeners; TestEventListeners listeners;
listeners.Append(listener); listeners.Append(listener);
ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
TestEventListenersAccessor::SuppressEventForwarding(&listeners); TestEventListenersAccessor::SuppressEventForwarding(&listeners);
ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
EXPECT_EQ(0, on_start_counter); EXPECT_EQ(0, on_start_counter);
} }
// Tests that events generated by Google Test are not forwarded in // Tests that events generated by Google Test are not forwarded in
// death test subprocesses. // death test subprocesses.
TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) { TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED(
GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( {
*GetUnitTestImpl()->listeners())) << "expected failure";}, GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
*GetUnitTestImpl()->listeners()))
<< "expected failure";
},
"expected failure"); "expected failure");
} }
// Tests that a listener installed via SetDefaultResultPrinter() starts // Tests that a listener installed via SetDefaultResultPrinter() starts
// receiving events and is returned via default_result_printer() and that // receiving events and is returned via default_result_printer() and that
// the previous default_result_printer is removed from the list and deleted. // the previous default_result_printer is removed from the list and deleted.
TEST(EventListenerTest, default_result_printer) { TEST(EventListenerTest, default_result_printer) {
int on_start_counter = 0; int on_start_counter = 0;
bool is_destroyed = false; bool is_destroyed = false;
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
TestEventListeners listeners; TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
EXPECT_EQ(listener, listeners.default_result_printer()); EXPECT_EQ(listener, listeners.default_result_printer());
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter); EXPECT_EQ(1, on_start_counter);
// Replacing default_result_printer with something else should remove it // Replacing default_result_printer with something else should remove it
// from the list and destroy it. // from the list and destroy it.
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr); TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
EXPECT_TRUE(listeners.default_result_printer() == nullptr); EXPECT_TRUE(listeners.default_result_printer() == nullptr);
EXPECT_TRUE(is_destroyed); EXPECT_TRUE(is_destroyed);
// After broadcasting an event the counter is still the same, indicating // After broadcasting an event the counter is still the same, indicating
// the listener is not in the list anymore. // the listener is not in the list anymore.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter); EXPECT_EQ(1, on_start_counter);
} }
// Tests that the default_result_printer listener stops receiving events // Tests that the default_result_printer listener stops receiving events
// when removed via Release and that is not owned by the list anymore. // when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) { TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
int on_start_counter = 0; int on_start_counter = 0;
bool is_destroyed = false; bool is_destroyed = false;
// Although Append passes the ownership of this object to the list, // Although Append passes the ownership of this object to the list,
// the following calls release it, and we need to delete it before the // the following calls release it, and we need to delete it before the
skipping to change at line 7080 skipping to change at line 7029
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{ {
TestEventListeners listeners; TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
EXPECT_EQ(listener, listeners.Release(listener)); EXPECT_EQ(listener, listeners.Release(listener));
EXPECT_TRUE(listeners.default_result_printer() == nullptr); EXPECT_TRUE(listeners.default_result_printer() == nullptr);
EXPECT_FALSE(is_destroyed); EXPECT_FALSE(is_destroyed);
// Broadcasting events now should not affect default_result_printer. // Broadcasting events now should not affect default_result_printer.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
EXPECT_EQ(0, on_start_counter); EXPECT_EQ(0, on_start_counter);
} }
// Destroying the list should not affect the listener now, too. // Destroying the list should not affect the listener now, too.
EXPECT_FALSE(is_destroyed); EXPECT_FALSE(is_destroyed);
delete listener; delete listener;
} }
// Tests that a listener installed via SetDefaultXmlGenerator() starts // Tests that a listener installed via SetDefaultXmlGenerator() starts
// receiving events and is returned via default_xml_generator() and that // receiving events and is returned via default_xml_generator() and that
// the previous default_xml_generator is removed from the list and deleted. // the previous default_xml_generator is removed from the list and deleted.
TEST(EventListenerTest, default_xml_generator) { TEST(EventListenerTest, default_xml_generator) {
int on_start_counter = 0; int on_start_counter = 0;
bool is_destroyed = false; bool is_destroyed = false;
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
TestEventListeners listeners; TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
EXPECT_EQ(listener, listeners.default_xml_generator()); EXPECT_EQ(listener, listeners.default_xml_generator());
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter); EXPECT_EQ(1, on_start_counter);
// Replacing default_xml_generator with something else should remove it // Replacing default_xml_generator with something else should remove it
// from the list and destroy it. // from the list and destroy it.
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr); TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
EXPECT_TRUE(listeners.default_xml_generator() == nullptr); EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
EXPECT_TRUE(is_destroyed); EXPECT_TRUE(is_destroyed);
// After broadcasting an event the counter is still the same, indicating // After broadcasting an event the counter is still the same, indicating
// the listener is not in the list anymore. // the listener is not in the list anymore.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter); EXPECT_EQ(1, on_start_counter);
} }
// Tests that the default_xml_generator listener stops receiving events // Tests that the default_xml_generator listener stops receiving events
// when removed via Release and that is not owned by the list anymore. // when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) { TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
int on_start_counter = 0; int on_start_counter = 0;
bool is_destroyed = false; bool is_destroyed = false;
// Although Append passes the ownership of this object to the list, // Although Append passes the ownership of this object to the list,
// the following calls release it, and we need to delete it before the // the following calls release it, and we need to delete it before the
skipping to change at line 7139 skipping to change at line 7088
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{ {
TestEventListeners listeners; TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
EXPECT_EQ(listener, listeners.Release(listener)); EXPECT_EQ(listener, listeners.Release(listener));
EXPECT_TRUE(listeners.default_xml_generator() == nullptr); EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
EXPECT_FALSE(is_destroyed); EXPECT_FALSE(is_destroyed);
// Broadcasting events now should not affect default_xml_generator. // Broadcasting events now should not affect default_xml_generator.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( TestEventListenersAccessor::GetRepeater(&listeners)
*UnitTest::GetInstance()); ->OnTestProgramStart(*UnitTest::GetInstance());
EXPECT_EQ(0, on_start_counter); EXPECT_EQ(0, on_start_counter);
} }
// Destroying the list should not affect the listener now, too. // Destroying the list should not affect the listener now, too.
EXPECT_FALSE(is_destroyed); EXPECT_FALSE(is_destroyed);
delete listener; delete listener;
} }
// Sanity tests to ensure that the alternative, verbose spellings of // Tests to ensure that the alternative, verbose spellings of
// some of the macros work. We don't test them thoroughly as that // some of the macros work. We don't test them thoroughly as that
// would be quite involved. Since their implementations are // would be quite involved. Since their implementations are
// straightforward, and they are rarely used, we'll just rely on the // straightforward, and they are rarely used, we'll just rely on the
// users to tell us when they are broken. // users to tell us when they are broken.
GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED. GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
// GTEST_FAIL is the same as FAIL. // GTEST_FAIL is the same as FAIL.
EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure", EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
"An expected failure"); "An expected failure");
skipping to change at line 7228 skipping to change at line 7177
struct MissingDebugStringMethod { struct MissingDebugStringMethod {
std::string DebugString() { return ""; } std::string DebugString() { return ""; }
}; };
struct IncompleteType; struct IncompleteType;
// Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time // Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
// constant. // constant.
TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) { TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
GTEST_COMPILE_ASSERT_( static_assert(HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
HasDebugStringAndShortDebugString<HasDebugStringMethods>::value, "const_true");
const_true); static_assert(
GTEST_COMPILE_ASSERT_(
HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value, HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
const_true); "const_true");
GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString< static_assert(HasDebugStringAndShortDebugString<
const InheritsDebugStringMethods>::value, const InheritsDebugStringMethods>::value,
const_true); "const_true");
GTEST_COMPILE_ASSERT_( static_assert(
!HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value, !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
const_false); "const_false");
GTEST_COMPILE_ASSERT_( static_assert(
!HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value, !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
const_false); "const_false");
GTEST_COMPILE_ASSERT_( static_assert(
!HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value, !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
const_false); "const_false");
GTEST_COMPILE_ASSERT_( static_assert(!HasDebugStringAndShortDebugString<IncompleteType>::value,
!HasDebugStringAndShortDebugString<IncompleteType>::value, const_false); "const_false");
GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value, static_assert(!HasDebugStringAndShortDebugString<int>::value, "const_false");
const_false);
} }
// Tests that HasDebugStringAndShortDebugString<T>::value is true when T has // Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
// needed methods. // needed methods.
TEST(HasDebugStringAndShortDebugStringTest, TEST(HasDebugStringAndShortDebugStringTest,
ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) { ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
EXPECT_TRUE( EXPECT_TRUE(
HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value); HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
} }
skipping to change at line 7311 skipping to change at line 7258
class NonContainer {}; class NonContainer {};
TEST(IsContainerTestTest, WorksForNonContainer) { TEST(IsContainerTestTest, WorksForNonContainer) {
EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0))); EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0))); EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0))); EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
} }
TEST(IsContainerTestTest, WorksForContainer) { TEST(IsContainerTestTest, WorksForContainer) {
EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool>>(0)));
EXPECT_EQ(sizeof(IsContainer), EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<std::vector<bool> >(0))); sizeof(IsContainerTest<std::map<int, double>>(0)));
EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<std::map<int, double> >(0)));
} }
struct ConstOnlyContainerWithPointerIterator { struct ConstOnlyContainerWithPointerIterator {
using const_iterator = int*; using const_iterator = int*;
const_iterator begin() const; const_iterator begin() const;
const_iterator end() const; const_iterator end() const;
}; };
struct ConstOnlyContainerWithClassIterator { struct ConstOnlyContainerWithClassIterator {
struct const_iterator { struct const_iterator {
skipping to change at line 7363 skipping to change at line 7309
// Tests ArrayEq(). // Tests ArrayEq().
TEST(ArrayEqTest, WorksForDegeneratedArrays) { TEST(ArrayEqTest, WorksForDegeneratedArrays) {
EXPECT_TRUE(ArrayEq(5, 5L)); EXPECT_TRUE(ArrayEq(5, 5L));
EXPECT_FALSE(ArrayEq('a', 0)); EXPECT_FALSE(ArrayEq('a', 0));
} }
TEST(ArrayEqTest, WorksForOneDimensionalArrays) { TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
// Note that a and b are distinct but compatible types. // Note that a and b are distinct but compatible types.
const int a[] = { 0, 1 }; const int a[] = {0, 1};
long b[] = { 0, 1 }; long b[] = {0, 1};
EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, b));
EXPECT_TRUE(ArrayEq(a, 2, b)); EXPECT_TRUE(ArrayEq(a, 2, b));
b[0] = 2; b[0] = 2;
EXPECT_FALSE(ArrayEq(a, b)); EXPECT_FALSE(ArrayEq(a, b));
EXPECT_FALSE(ArrayEq(a, 1, b)); EXPECT_FALSE(ArrayEq(a, 1, b));
} }
TEST(ArrayEqTest, WorksForTwoDimensionalArrays) { TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
const char a[][3] = { "hi", "lo" }; const char a[][3] = {"hi", "lo"};
const char b[][3] = { "hi", "lo" }; const char b[][3] = {"hi", "lo"};
const char c[][3] = { "hi", "li" }; const char c[][3] = {"hi", "li"};
EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, b));
EXPECT_TRUE(ArrayEq(a, 2, b)); EXPECT_TRUE(ArrayEq(a, 2, b));
EXPECT_FALSE(ArrayEq(a, c)); EXPECT_FALSE(ArrayEq(a, c));
EXPECT_FALSE(ArrayEq(a, 2, c)); EXPECT_FALSE(ArrayEq(a, 2, c));
} }
// Tests ArrayAwareFind(). // Tests ArrayAwareFind().
TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) { TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
const char a[] = "hello"; const char a[] = "hello";
EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o')); EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x')); EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
} }
TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) { TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; int a[][2] = {{0, 1}, {2, 3}, {4, 5}};
const int b[2] = { 2, 3 }; const int b[2] = {2, 3};
EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b)); EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
const int c[2] = { 6, 7 }; const int c[2] = {6, 7};
EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c)); EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
} }
// Tests CopyArray(). // Tests CopyArray().
TEST(CopyArrayTest, WorksForDegeneratedArrays) { TEST(CopyArrayTest, WorksForDegeneratedArrays) {
int n = 0; int n = 0;
CopyArray('a', &n); CopyArray('a', &n);
EXPECT_EQ('a', n); EXPECT_EQ('a', n);
} }
skipping to change at line 7424 skipping to change at line 7370
CopyArray(a, &b); CopyArray(a, &b);
EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, b));
#endif #endif
int c[3]; int c[3];
CopyArray(a, 3, c); CopyArray(a, 3, c);
EXPECT_TRUE(ArrayEq(a, c)); EXPECT_TRUE(ArrayEq(a, c));
} }
TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } }; const int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
int b[2][3]; int b[2][3];
#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
CopyArray(a, &b); CopyArray(a, &b);
EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, b));
#endif #endif
int c[2][3]; int c[2][3];
CopyArray(a, 2, c); CopyArray(a, 2, c);
EXPECT_TRUE(ArrayEq(a, c)); EXPECT_TRUE(ArrayEq(a, c));
} }
// Tests NativeArray. // Tests NativeArray.
TEST(NativeArrayTest, ConstructorFromArrayWorks) { TEST(NativeArrayTest, ConstructorFromArrayWorks) {
const int a[3] = { 0, 1, 2 }; const int a[3] = {0, 1, 2};
NativeArray<int> na(a, 3, RelationToSourceReference()); NativeArray<int> na(a, 3, RelationToSourceReference());
EXPECT_EQ(3U, na.size()); EXPECT_EQ(3U, na.size());
EXPECT_EQ(a, na.begin()); EXPECT_EQ(a, na.begin());
} }
TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) { TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
typedef int Array[2]; typedef int Array[2];
Array* a = new Array[1]; Array* a = new Array[1];
(*a)[0] = 0; (*a)[0] = 0;
(*a)[1] = 1; (*a)[1] = 1;
skipping to change at line 7469 skipping to change at line 7415
TEST(NativeArrayTest, TypeMembersAreCorrect) { TEST(NativeArrayTest, TypeMembersAreCorrect) {
StaticAssertTypeEq<char, NativeArray<char>::value_type>(); StaticAssertTypeEq<char, NativeArray<char>::value_type>();
StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>(); StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>(); StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>(); StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
} }
TEST(NativeArrayTest, MethodsWork) { TEST(NativeArrayTest, MethodsWork) {
const int a[3] = { 0, 1, 2 }; const int a[3] = {0, 1, 2};
NativeArray<int> na(a, 3, RelationToSourceCopy()); NativeArray<int> na(a, 3, RelationToSourceCopy());
ASSERT_EQ(3U, na.size()); ASSERT_EQ(3U, na.size());
EXPECT_EQ(3, na.end() - na.begin()); EXPECT_EQ(3, na.end() - na.begin());
NativeArray<int>::const_iterator it = na.begin(); NativeArray<int>::const_iterator it = na.begin();
EXPECT_EQ(0, *it); EXPECT_EQ(0, *it);
++it; ++it;
EXPECT_EQ(1, *it); EXPECT_EQ(1, *it);
it++; it++;
EXPECT_EQ(2, *it); EXPECT_EQ(2, *it);
++it; ++it;
EXPECT_EQ(na.end(), it); EXPECT_EQ(na.end(), it);
EXPECT_TRUE(na == na); EXPECT_TRUE(na == na);
NativeArray<int> na2(a, 3, RelationToSourceReference()); NativeArray<int> na2(a, 3, RelationToSourceReference());
EXPECT_TRUE(na == na2); EXPECT_TRUE(na == na2);
const int b1[3] = { 0, 1, 1 }; const int b1[3] = {0, 1, 1};
const int b2[4] = { 0, 1, 2, 3 }; const int b2[4] = {0, 1, 2, 3};
EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference())); EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy())); EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
} }
TEST(NativeArrayTest, WorksForTwoDimensionalArray) { TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
const char a[2][3] = { "hi", "lo" }; const char a[2][3] = {"hi", "lo"};
NativeArray<char[3]> na(a, 2, RelationToSourceReference()); NativeArray<char[3]> na(a, 2, RelationToSourceReference());
ASSERT_EQ(2U, na.size()); ASSERT_EQ(2U, na.size());
EXPECT_EQ(a, na.begin()); EXPECT_EQ(a, na.begin());
} }
// IndexSequence // IndexSequence
TEST(IndexSequence, MakeIndexSequence) { TEST(IndexSequence, MakeIndexSequence) {
using testing::internal::IndexSequence; using testing::internal::IndexSequence;
using testing::internal::MakeIndexSequence; using testing::internal::MakeIndexSequence;
EXPECT_TRUE( EXPECT_TRUE(
skipping to change at line 7775 skipping to change at line 7721
if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue; if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
// Found it. // Found it.
EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE"); EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE"); EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
return; return;
} }
} }
FAIL() << "Didn't find the test!"; FAIL() << "Didn't find the test!";
} }
// Test that the pattern globbing algorithm is linear. If not, this test should
// time out.
TEST(PatternGlobbingTest, MatchesFilterLinearRuntime) {
std::string name(100, 'a'); // Construct the string (a^100)b
name.push_back('b');
std::string pattern; // Construct the string ((a*)^100)b
for (int i = 0; i < 100; ++i) {
pattern.append("a*");
}
pattern.push_back('b');
EXPECT_TRUE(
testing::internal::UnitTestOptions::MatchesFilter(name, pattern.c_str()));
}
TEST(PatternGlobbingTest, MatchesFilterWithMultiplePatterns) {
const std::string name = "aaaa";
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*"));
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*:"));
EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab"));
EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:"));
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:a*"));
}
TEST(PatternGlobbingTest, MatchesFilterEdgeCases) {
EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("", "*a"));
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", "*"));
EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("a", ""));
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", ""));
}
 End of changes. 395 change blocks. 
996 lines changed or deleted 942 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)