Commit 25905b9f authored by Gennadiy Civil's avatar Gennadiy Civil
Browse files

Merge branch 'master' of https://github.com/google/googletest

parents 4665eee1 3bedb5a9
...@@ -348,7 +348,7 @@ void PrintTo(const wchar_t* s, ostream* os) { ...@@ -348,7 +348,7 @@ void PrintTo(const wchar_t* s, ostream* os) {
*os << "NULL"; *os << "NULL";
} else { } else {
*os << ImplicitCast_<const void*>(s) << " pointing to "; *os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintCharsAsStringTo(s, std::wcslen(s), os); PrintCharsAsStringTo(s, wcslen(s), os);
} }
} }
#endif // wchar_t is native #endif // wchar_t is native
......
...@@ -423,9 +423,6 @@ void AssertHelper::operator=(const Message& message) const { ...@@ -423,9 +423,6 @@ void AssertHelper::operator=(const Message& message) const {
); // NOLINT ); // NOLINT
} }
// Mutex for linked pointers.
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
// A copy of all command line arguments. Set by InitGoogleTest(). // A copy of all command line arguments. Set by InitGoogleTest().
static ::std::vector<std::string> g_argvs; static ::std::vector<std::string> g_argvs;
...@@ -445,7 +442,7 @@ static ::std::vector<std::string> g_argvs; ...@@ -445,7 +442,7 @@ static ::std::vector<std::string> g_argvs;
FilePath GetCurrentExecutableName() { FilePath GetCurrentExecutableName() {
FilePath result; FilePath result;
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS || GTEST_OS_OS2
result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
#else #else
result.Set(FilePath(GetArgvs()[0])); result.Set(FilePath(GetArgvs()[0]));
...@@ -905,11 +902,10 @@ TimeInMillis GetTimeInMillis() { ...@@ -905,11 +902,10 @@ TimeInMillis GetTimeInMillis() {
// value using delete[]. Returns the wide string, or NULL if the // value using delete[]. Returns the wide string, or NULL if the
// input is NULL. // input is NULL.
LPCWSTR String::AnsiToUtf16(const char* ansi) { LPCWSTR String::AnsiToUtf16(const char* ansi) {
if (!ansi) return NULL; if (!ansi) return nullptr;
const int length = strlen(ansi); const int length = strlen(ansi);
const int unicode_length = const int unicode_length =
MultiByteToWideChar(CP_ACP, 0, ansi, length, MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
NULL, 0);
WCHAR* unicode = new WCHAR[unicode_length + 1]; WCHAR* unicode = new WCHAR[unicode_length + 1];
MultiByteToWideChar(CP_ACP, 0, ansi, length, MultiByteToWideChar(CP_ACP, 0, ansi, length,
unicode, unicode_length); unicode, unicode_length);
...@@ -922,13 +918,12 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { ...@@ -922,13 +918,12 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) {
// value using delete[]. Returns the ANSI string, or NULL if the // value using delete[]. Returns the ANSI string, or NULL if the
// input is NULL. // input is NULL.
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
if (!utf16_str) return NULL; if (!utf16_str) return nullptr;
const int ansi_length = const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, 0, nullptr, nullptr);
NULL, 0, NULL, NULL);
char* ansi = new char[ansi_length + 1]; char* ansi = new char[ansi_length + 1];
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
ansi, ansi_length, NULL, NULL); nullptr);
ansi[ansi_length] = 0; ansi[ansi_length] = 0;
return ansi; return ansi;
} }
...@@ -1725,12 +1720,12 @@ AssertionResult HRESULTFailureHelper(const char* expr, ...@@ -1725,12 +1720,12 @@ AssertionResult HRESULTFailureHelper(const char* expr,
// Gets the system's human readable message string for this HRESULT. // Gets the system's human readable message string for this HRESULT.
char error_text[kBufSize] = { '\0' }; char error_text[kBufSize] = { '\0' };
DWORD message_length = ::FormatMessageA(kFlags, DWORD message_length = ::FormatMessageA(kFlags,
0, // no source, we're asking system 0, // no source, we're asking system
hr, // the error hr, // the error
0, // no line width restrictions 0, // no line width restrictions
error_text, // output buffer error_text, // output buffer
kBufSize, // buf size kBufSize, // buf size
NULL); // no arguments for inserts nullptr); // no arguments for inserts
// Trims tailing white space (FormatMessage leaves a trailing CR-LF) // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
for (; message_length && IsSpace(error_text[message_length - 1]); for (; message_length && IsSpace(error_text[message_length - 1]);
--message_length) { --message_length) {
...@@ -2402,7 +2397,7 @@ namespace internal { ...@@ -2402,7 +2397,7 @@ namespace internal {
static std::string FormatCxxExceptionMessage(const char* description, static std::string FormatCxxExceptionMessage(const char* description,
const char* location) { const char* location) {
Message message; Message message;
if (description != NULL) { if (description != nullptr) {
message << "C++ exception with description \"" << description << "\""; message << "C++ exception with description \"" << description << "\"";
} else { } else {
message << "Unknown C++ exception"; message << "Unknown C++ exception";
...@@ -2500,7 +2495,7 @@ Result HandleExceptionsInMethodIfSupported( ...@@ -2500,7 +2495,7 @@ Result HandleExceptionsInMethodIfSupported(
} catch (...) { // NOLINT } catch (...) { // NOLINT
internal::ReportFailureInUnknownLocation( internal::ReportFailureInUnknownLocation(
TestPartResult::kFatalFailure, TestPartResult::kFatalFailure,
FormatCxxExceptionMessage(NULL, location)); FormatCxxExceptionMessage(nullptr, location));
} }
return static_cast<Result>(0); return static_cast<Result>(0);
#else #else
...@@ -2520,8 +2515,9 @@ void Test::Run() { ...@@ -2520,8 +2515,9 @@ void Test::Run() {
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
impl->os_stack_trace_getter()->UponLeavingGTest(); impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
// We will run the test only if SetUp() was successful. // We will run the test only if SetUp() was successful and didn't call
if (!HasFatalFailure()) { // GTEST_SKIP().
if (!HasFatalFailure() && !IsSkipped()) {
impl->os_stack_trace_getter()->UponLeavingGTest(); impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported( internal::HandleExceptionsInMethodIfSupported(
this, &Test::TestBody, "the test body"); this, &Test::TestBody, "the test body");
...@@ -2698,9 +2694,10 @@ void TestInfo::Run() { ...@@ -2698,9 +2694,10 @@ void TestInfo::Run() {
factory_, &internal::TestFactoryBase::CreateTest, factory_, &internal::TestFactoryBase::CreateTest,
"the test fixture's constructor"); "the test fixture's constructor");
// Runs the test if the constructor didn't generate a fatal failure. // Runs the test if the constructor didn't generate a fatal failure or invoke
// GTEST_SKIP().
// Note that the object will not be null // Note that the object will not be null
if (!Test::HasFatalFailure()) { if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
// This doesn't throw as all user code that can throw are wrapped into // This doesn't throw as all user code that can throw are wrapped into
// exception handling code. // exception handling code.
test->Run(); test->Run();
...@@ -3114,19 +3111,19 @@ class PrettyUnitTestResultPrinter : public TestEventListener { ...@@ -3114,19 +3111,19 @@ class PrettyUnitTestResultPrinter : public TestEventListener {
} }
// The following methods override what's in the TestEventListener class. // The following methods override what's in the TestEventListener class.
virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
virtual void OnTestCaseStart(const TestCase& test_case); void OnTestCaseStart(const TestCase& test_case) override;
virtual void OnTestStart(const TestInfo& test_info); void OnTestStart(const TestInfo& test_info) override;
virtual void OnTestPartResult(const TestPartResult& result); void OnTestPartResult(const TestPartResult& result) override;
virtual void OnTestEnd(const TestInfo& test_info); void OnTestEnd(const TestInfo& test_info) override;
virtual void OnTestCaseEnd(const TestCase& test_case); void OnTestCaseEnd(const TestCase& test_case) override;
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
private: private:
static void PrintFailedTests(const UnitTest& unit_test); static void PrintFailedTests(const UnitTest& unit_test);
...@@ -3355,7 +3352,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, ...@@ -3355,7 +3352,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
class TestEventRepeater : public TestEventListener { class TestEventRepeater : public TestEventListener {
public: public:
TestEventRepeater() : forwarding_enabled_(true) {} TestEventRepeater() : forwarding_enabled_(true) {}
virtual ~TestEventRepeater(); ~TestEventRepeater() override;
void Append(TestEventListener *listener); void Append(TestEventListener *listener);
TestEventListener* Release(TestEventListener* listener); TestEventListener* Release(TestEventListener* listener);
...@@ -3364,19 +3361,19 @@ class TestEventRepeater : public TestEventListener { ...@@ -3364,19 +3361,19 @@ class TestEventRepeater : public TestEventListener {
bool forwarding_enabled() const { return forwarding_enabled_; } bool forwarding_enabled() const { return forwarding_enabled_; }
void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
virtual void OnTestProgramStart(const UnitTest& unit_test); void OnTestProgramStart(const UnitTest& unit_test) override;
virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
virtual void OnTestCaseStart(const TestCase& test_case); void OnTestCaseStart(const TestCase& test_case) override;
virtual void OnTestStart(const TestInfo& test_info); void OnTestStart(const TestInfo& test_info) override;
virtual void OnTestPartResult(const TestPartResult& result); void OnTestPartResult(const TestPartResult& result) override;
virtual void OnTestEnd(const TestInfo& test_info); void OnTestEnd(const TestInfo& test_info) override;
virtual void OnTestCaseEnd(const TestCase& test_case); void OnTestCaseEnd(const TestCase& test_case) override;
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
virtual void OnTestProgramEnd(const UnitTest& unit_test); void OnTestProgramEnd(const UnitTest& unit_test) override;
private: private:
// Controls whether events will be forwarded to listeners_. Set to false // Controls whether events will be forwarded to listeners_. Set to false
...@@ -3469,7 +3466,7 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener { ...@@ -3469,7 +3466,7 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener {
public: public:
explicit XmlUnitTestResultPrinter(const char* output_file); explicit XmlUnitTestResultPrinter(const char* output_file);
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
void ListTestsMatchingFilter(const std::vector<TestCase*>& test_cases); void ListTestsMatchingFilter(const std::vector<TestCase*>& test_cases);
// Prints an XML summary of all unit tests. // Prints an XML summary of all unit tests.
...@@ -3674,8 +3671,7 @@ static bool PortableLocaltime(time_t seconds, struct tm* out) { ...@@ -3674,8 +3671,7 @@ static bool PortableLocaltime(time_t seconds, struct tm* out) {
// MINGW <time.h> provides neither localtime_r nor localtime_s, but uses // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
// Windows' localtime(), which has a thread-local tm buffer. // Windows' localtime(), which has a thread-local tm buffer.
struct tm* tm_ptr = localtime(&seconds); // NOLINT struct tm* tm_ptr = localtime(&seconds); // NOLINT
if (tm_ptr == NULL) if (tm_ptr == nullptr) return false;
return false;
*out = *tm_ptr; *out = *tm_ptr;
return true; return true;
#else #else
...@@ -3765,7 +3761,8 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, ...@@ -3765,7 +3761,8 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
} }
OutputXmlAttribute(stream, kTestcase, "status", OutputXmlAttribute(stream, kTestcase, "status",
test_info.should_run() ? "run" : "notrun"); result.Skipped() ? "skipped" :
test_info.should_run() ? "run" : "notrun");
OutputXmlAttribute(stream, kTestcase, "time", OutputXmlAttribute(stream, kTestcase, "time",
FormatTimeInMillisAsSeconds(result.elapsed_time())); FormatTimeInMillisAsSeconds(result.elapsed_time()));
OutputXmlAttribute(stream, kTestcase, "classname", test_case_name); OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
...@@ -3928,7 +3925,7 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener { ...@@ -3928,7 +3925,7 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener {
public: public:
explicit JsonUnitTestResultPrinter(const char* output_file); explicit JsonUnitTestResultPrinter(const char* output_file);
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
// Prints an JSON summary of all unit tests. // Prints an JSON summary of all unit tests.
static void PrintJsonTestList(::std::ostream* stream, static void PrintJsonTestList(::std::ostream* stream,
...@@ -4130,6 +4127,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, ...@@ -4130,6 +4127,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
} }
OutputJsonKey(stream, kTestcase, "status", OutputJsonKey(stream, kTestcase, "status",
result.Skipped() ? "SKIPPED" :
test_info.should_run() ? "RUN" : "NOTRUN", kIndent); test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
OutputJsonKey(stream, kTestcase, "time", OutputJsonKey(stream, kTestcase, "time",
FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent); FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
...@@ -4541,24 +4539,17 @@ void TestEventListeners::SuppressEventForwarding() { ...@@ -4541,24 +4539,17 @@ void TestEventListeners::SuppressEventForwarding() {
// call this before main() starts, from which point on the return // call this before main() starts, from which point on the return
// value will never change. // value will never change.
UnitTest* UnitTest::GetInstance() { UnitTest* UnitTest::GetInstance() {
// When compiled with MSVC 7.1 in optimized mode, destroying the
// UnitTest object upon exiting the program messes up the exit code,
// causing successful tests to appear failed. We have to use a
// different implementation in this case to bypass the compiler bug.
// This implementation makes the compiler happy, at the cost of
// leaking the UnitTest object.
// CodeGear C++Builder insists on a public destructor for the // CodeGear C++Builder insists on a public destructor for the
// default implementation. Use this implementation to keep good OO // default implementation. Use this implementation to keep good OO
// design with private destructor. // design with private destructor.
#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) #if defined(__BORLANDC__)
static UnitTest* const instance = new UnitTest; static UnitTest* const instance = new UnitTest;
return instance; return instance;
#else #else
static UnitTest instance; static UnitTest instance;
return &instance; return &instance;
#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) #endif // defined(__BORLANDC__)
} }
// Gets the number of successful test cases. // Gets the number of successful test cases.
...@@ -4730,11 +4721,11 @@ void UnitTest::AddTestPartResult( ...@@ -4730,11 +4721,11 @@ void UnitTest::AddTestPartResult(
// with clang/gcc we can achieve the same effect on x86 by invoking int3 // with clang/gcc we can achieve the same effect on x86 by invoking int3
asm("int3"); asm("int3");
#else #else
// Dereference NULL through a volatile pointer to prevent the compiler // Dereference nullptr through a volatile pointer to prevent the compiler
// from removing. We use this rather than abort() or __builtin_trap() for // from removing. We use this rather than abort() or __builtin_trap() for
// portability: Symbian doesn't implement abort() well, and some debuggers // portability: Symbian doesn't implement abort() well, and some debuggers
// don't correctly trap abort(). // don't correctly trap abort().
*static_cast<volatile int*>(NULL) = 1; *static_cast<volatile int*>(nullptr) = 1;
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
} else if (GTEST_FLAG(throw_on_failure)) { } else if (GTEST_FLAG(throw_on_failure)) {
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
...@@ -4816,18 +4807,12 @@ int UnitTest::Run() { ...@@ -4816,18 +4807,12 @@ int UnitTest::Run() {
_set_error_mode(_OUT_TO_STDERR); _set_error_mode(_OUT_TO_STDERR);
# endif # endif
# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
// In the debug version, Visual Studio pops up a separate dialog // In the debug version, Visual Studio pops up a separate dialog
// offering a choice to debug the aborted program. We need to suppress // offering a choice to debug the aborted program. We need to suppress
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
// executed. Google Test will notify the user of any unexpected // executed. Google Test will notify the user of any unexpected
// failure via stderr. // failure via stderr.
//
// VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
// Users of prior VC versions shall suffer the agony and pain of
// clicking through the countless debug dialogs.
// FIXME: find a way to suppress the abort dialog() in the
// debug mode when compiled with VC 7.1 or lower.
if (!GTEST_FLAG(break_on_failure)) if (!GTEST_FLAG(break_on_failure))
_set_abort_behavior( _set_abort_behavior(
0x0, // Clear the following flags: 0x0, // Clear the following flags:
...@@ -5807,7 +5792,7 @@ static const char kColorEncodedHelpMessage[] = ...@@ -5807,7 +5792,7 @@ static const char kColorEncodedHelpMessage[] =
" @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" " @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
" Generate a JSON or XML report in the given directory or with the given\n" " Generate a JSON or XML report in the given directory or with the given\n"
" file name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
# if GTEST_CAN_STREAM_RESULTS_ # if GTEST_CAN_STREAM_RESULTS_
" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
" Stream test results to the given server.\n" " Stream test results to the given server.\n"
...@@ -6026,7 +6011,7 @@ std::string TempDir() { ...@@ -6026,7 +6011,7 @@ std::string TempDir() {
return "\\temp\\"; return "\\temp\\";
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
const char* temp_dir = internal::posix::GetEnv("TEMP"); const char* temp_dir = internal::posix::GetEnv("TEMP");
if (temp_dir == NULL || temp_dir[0] == '\0') if (temp_dir == nullptr || temp_dir[0] == '\0')
return "\\temp\\"; return "\\temp\\";
else if (temp_dir[strlen(temp_dir) - 1] == '\\') else if (temp_dir[strlen(temp_dir) - 1] == '\\')
return temp_dir; return temp_dir;
......
...@@ -30,8 +30,24 @@ ...@@ -30,8 +30,24 @@
#include <stdio.h> #include <stdio.h>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#ifdef ARDUINO
void setup() {
// Since Arduino doesn't have a command line, fake out the argc/argv arguments
int argc = 1;
const auto arg0 = "PlatformIO";
char* argv0 = const_cast<char*>(arg0);
char** argv = &argv0;
testing::InitGoogleTest(&argc, argv);
}
void loop() { RUN_ALL_TESTS(); }
#else
GTEST_API_ int main(int argc, char **argv) { GTEST_API_ int main(int argc, char **argv) {
printf("Running main() from %s\n", __FILE__); printf("Running main() from %s\n", __FILE__);
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
#endif
...@@ -34,22 +34,7 @@ ...@@ -34,22 +34,7 @@
licenses(["notice"]) licenses(["notice"])
config_setting( #on windows exclude gtest-tuple.h
name = "windows",
values = {"cpu": "x64_windows"},
)
config_setting(
name = "windows_msvc",
values = {"cpu": "x64_windows_msvc"},
)
config_setting(
name = "has_absl",
values = {"define": "absl=1"},
)
#on windows exclude gtest-tuple.h and googletest-tuple-test.cc
cc_test( cc_test(
name = "gtest_all_test", name = "gtest_all_test",
size = "small", size = "small",
...@@ -62,7 +47,6 @@ cc_test( ...@@ -62,7 +47,6 @@ cc_test(
], ],
exclude = [ exclude = [
"gtest-unittest-api_test.cc", "gtest-unittest-api_test.cc",
"googletest-tuple-test.cc",
"googletest/src/gtest-all.cc", "googletest/src/gtest-all.cc",
"gtest_all_test.cc", "gtest_all_test.cc",
"gtest-death-test_ex_test.cc", "gtest-death-test_ex_test.cc",
...@@ -74,28 +58,23 @@ cc_test( ...@@ -74,28 +58,23 @@ cc_test(
"googletest-env-var-test_.cc", "googletest-env-var-test_.cc",
"googletest-filter-unittest_.cc", "googletest-filter-unittest_.cc",
"googletest-break-on-failure-unittest_.cc", "googletest-break-on-failure-unittest_.cc",
"googletest-listener-test.cc", "googletest-listener-test.cc",
"googletest-output-test_.cc", "googletest-output-test_.cc",
"googletest-list-tests-unittest_.cc", "googletest-list-tests-unittest_.cc",
"googletest-shuffle-test_.cc", "googletest-shuffle-test_.cc",
"googletest-uninitialized-test_.cc", "googletest-uninitialized-test_.cc",
"googletest-death-test_ex_test.cc", "googletest-death-test_ex_test.cc",
"googletest-param-test-test", "googletest-param-test-test",
"googletest-throw-on-failure-test_.cc", "googletest-throw-on-failure-test_.cc",
"googletest-param-test-invalid-name1-test_.cc", "googletest-param-test-invalid-name1-test_.cc",
"googletest-param-test-invalid-name2-test_.cc", "googletest-param-test-invalid-name2-test_.cc",
], ],
) + select({ ) + select({
"//:windows": [], "//:windows": [],
"//:windows_msvc": [], "//conditions:default": [],
"//conditions:default": [
"googletest-tuple-test.cc",
],
}), }),
copts = select({ copts = select({
"//:windows": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], "//:windows": ["-DGTEST_USE_OWN_TR1_TUPLE=0"],
"//:windows_msvc": ["-DGTEST_USE_OWN_TR1_TUPLE=0"],
"//conditions:default": ["-DGTEST_USE_OWN_TR1_TUPLE=1"], "//conditions:default": ["-DGTEST_USE_OWN_TR1_TUPLE=1"],
}), }),
includes = [ includes = [
...@@ -106,15 +85,11 @@ cc_test( ...@@ -106,15 +85,11 @@ cc_test(
], ],
linkopts = select({ linkopts = select({
"//:windows": [], "//:windows": [],
"//:windows_msvc": [], "//conditions:default": ["-pthread"],
"//conditions:default": [
"-pthread",
],
}), }),
deps = ["//:gtest_main"], deps = ["//:gtest_main"],
) )
# Tests death tests. # Tests death tests.
cc_test( cc_test(
name = "googletest-death-test-test", name = "googletest-death-test-test",
...@@ -199,13 +174,12 @@ cc_binary( ...@@ -199,13 +174,12 @@ cc_binary(
deps = ["//:gtest"], deps = ["//:gtest"],
) )
py_test( py_test(
name = "googletest-output-test", name = "googletest-output-test",
size = "small", size = "small",
srcs = ["googletest-output-test.py"], srcs = ["googletest-output-test.py"],
args = select({ args = select({
":has_absl": [], "//:has_absl": [],
"//conditions:default": ["--no_stacktrace_support"], "//conditions:default": ["--no_stacktrace_support"],
}), }),
data = [ data = [
...@@ -260,7 +234,6 @@ py_test( ...@@ -260,7 +234,6 @@ py_test(
deps = [":gtest_test_utils"], deps = [":gtest_test_utils"],
) )
cc_binary( cc_binary(
name = "googletest-break-on-failure-unittest_", name = "googletest-break-on-failure-unittest_",
testonly = 1, testonly = 1,
...@@ -268,8 +241,6 @@ cc_binary( ...@@ -268,8 +241,6 @@ cc_binary(
deps = ["//:gtest"], deps = ["//:gtest"],
) )
py_test( py_test(
name = "googletest-break-on-failure-unittest", name = "googletest-break-on-failure-unittest",
size = "small", size = "small",
...@@ -278,7 +249,6 @@ py_test( ...@@ -278,7 +249,6 @@ py_test(
deps = [":gtest_test_utils"], deps = [":gtest_test_utils"],
) )
cc_test( cc_test(
name = "gtest_assert_by_exception_test", name = "gtest_assert_by_exception_test",
size = "small", size = "small",
...@@ -286,8 +256,6 @@ cc_test( ...@@ -286,8 +256,6 @@ cc_test(
deps = ["//:gtest"], deps = ["//:gtest"],
) )
cc_binary( cc_binary(
name = "googletest-throw-on-failure-test_", name = "googletest-throw-on-failure-test_",
testonly = 1, testonly = 1,
...@@ -303,7 +271,6 @@ py_test( ...@@ -303,7 +271,6 @@ py_test(
deps = [":gtest_test_utils"], deps = [":gtest_test_utils"],
) )
cc_binary( cc_binary(
name = "googletest-list-tests-unittest_", name = "googletest-list-tests-unittest_",
testonly = 1, testonly = 1,
...@@ -311,6 +278,13 @@ cc_binary( ...@@ -311,6 +278,13 @@ cc_binary(
deps = ["//:gtest"], deps = ["//:gtest"],
) )
cc_test(
name = "gtest_skip_test",
size = "small",
srcs = ["gtest_skip_test.cc"],
deps = ["//:gtest_main"],
)
py_test( py_test(
name = "googletest-list-tests-unittest", name = "googletest-list-tests-unittest",
size = "small", size = "small",
...@@ -381,7 +355,7 @@ py_test( ...@@ -381,7 +355,7 @@ py_test(
"gtest_xml_test_utils.py", "gtest_xml_test_utils.py",
], ],
args = select({ args = select({
":has_absl": [], "//:has_absl": [],
"//conditions:default": ["--no_stacktrace_support"], "//conditions:default": ["--no_stacktrace_support"],
}), }),
data = [ data = [
...@@ -452,7 +426,6 @@ py_test( ...@@ -452,7 +426,6 @@ py_test(
deps = [":gtest_test_utils"], deps = [":gtest_test_utils"],
) )
py_test( py_test(
name = "googletest-json-outfiles-test", name = "googletest-json-outfiles-test",
size = "small", size = "small",
...@@ -474,18 +447,19 @@ py_test( ...@@ -474,18 +447,19 @@ py_test(
"googletest-json-output-unittest.py", "googletest-json-output-unittest.py",
"gtest_json_test_utils.py", "gtest_json_test_utils.py",
], ],
args = select({
"//:has_absl": [],
"//conditions:default": ["--no_stacktrace_support"],
}),
data = [ data = [
# We invoke gtest_no_test_unittest to verify the JSON output # We invoke gtest_no_test_unittest to verify the JSON output
# when the test program contains no test definition. # when the test program contains no test definition.
":gtest_no_test_unittest", ":gtest_no_test_unittest",
":gtest_xml_output_unittest_", ":gtest_xml_output_unittest_",
], ],
args = select({
":has_absl": [],
"//conditions:default": ["--no_stacktrace_support"],
}),
deps = [":gtest_test_utils"], deps = [":gtest_test_utils"],
) )
# Verifies interaction of death tests and exceptions. # Verifies interaction of death tests and exceptions.
cc_test( cc_test(
name = "googletest-death-test_ex_catch_test", name = "googletest-death-test_ex_catch_test",
......
...@@ -116,17 +116,17 @@ class CxxExceptionInConstructorTest : public Test { ...@@ -116,17 +116,17 @@ class CxxExceptionInConstructorTest : public Test {
} }
protected: protected:
~CxxExceptionInConstructorTest() { ~CxxExceptionInConstructorTest() override {
ADD_FAILURE() << "CxxExceptionInConstructorTest destructor " ADD_FAILURE() << "CxxExceptionInConstructorTest destructor "
<< "called unexpectedly."; << "called unexpectedly.";
} }
virtual void SetUp() { void SetUp() override {
ADD_FAILURE() << "CxxExceptionInConstructorTest::SetUp() " ADD_FAILURE() << "CxxExceptionInConstructorTest::SetUp() "
<< "called unexpectedly."; << "called unexpectedly.";
} }
virtual void TearDown() { void TearDown() override {
ADD_FAILURE() << "CxxExceptionInConstructorTest::TearDown() " ADD_FAILURE() << "CxxExceptionInConstructorTest::TearDown() "
<< "called unexpectedly."; << "called unexpectedly.";
} }
...@@ -157,19 +157,19 @@ class CxxExceptionInSetUpTestCaseTest : public Test { ...@@ -157,19 +157,19 @@ class CxxExceptionInSetUpTestCaseTest : public Test {
} }
protected: protected:
~CxxExceptionInSetUpTestCaseTest() { ~CxxExceptionInSetUpTestCaseTest() override {
printf("%s", printf("%s",
"CxxExceptionInSetUpTestCaseTest destructor " "CxxExceptionInSetUpTestCaseTest destructor "
"called as expected.\n"); "called as expected.\n");
} }
virtual void SetUp() { void SetUp() override {
printf("%s", printf("%s",
"CxxExceptionInSetUpTestCaseTest::SetUp() " "CxxExceptionInSetUpTestCaseTest::SetUp() "
"called as expected.\n"); "called as expected.\n");
} }
virtual void TearDown() { void TearDown() override {
printf("%s", printf("%s",
"CxxExceptionInSetUpTestCaseTest::TearDown() " "CxxExceptionInSetUpTestCaseTest::TearDown() "
"called as expected.\n"); "called as expected.\n");
...@@ -200,15 +200,15 @@ class CxxExceptionInSetUpTest : public Test { ...@@ -200,15 +200,15 @@ class CxxExceptionInSetUpTest : public Test {
} }
protected: protected:
~CxxExceptionInSetUpTest() { ~CxxExceptionInSetUpTest() override {
printf("%s", printf("%s",
"CxxExceptionInSetUpTest destructor " "CxxExceptionInSetUpTest destructor "
"called as expected.\n"); "called as expected.\n");
} }
virtual void SetUp() { throw std::runtime_error("Standard C++ exception"); } void SetUp() override { throw std::runtime_error("Standard C++ exception"); }
virtual void TearDown() { void TearDown() override {
printf("%s", printf("%s",
"CxxExceptionInSetUpTest::TearDown() " "CxxExceptionInSetUpTest::TearDown() "
"called as expected.\n"); "called as expected.\n");
...@@ -229,13 +229,13 @@ class CxxExceptionInTearDownTest : public Test { ...@@ -229,13 +229,13 @@ class CxxExceptionInTearDownTest : public Test {
} }
protected: protected:
~CxxExceptionInTearDownTest() { ~CxxExceptionInTearDownTest() override {
printf("%s", printf("%s",
"CxxExceptionInTearDownTest destructor " "CxxExceptionInTearDownTest destructor "
"called as expected.\n"); "called as expected.\n");
} }
virtual void TearDown() { void TearDown() override {
throw std::runtime_error("Standard C++ exception"); throw std::runtime_error("Standard C++ exception");
} }
}; };
...@@ -251,13 +251,13 @@ class CxxExceptionInTestBodyTest : public Test { ...@@ -251,13 +251,13 @@ class CxxExceptionInTestBodyTest : public Test {
} }
protected: protected:
~CxxExceptionInTestBodyTest() { ~CxxExceptionInTestBodyTest() override {
printf("%s", printf("%s",
"CxxExceptionInTestBodyTest destructor " "CxxExceptionInTestBodyTest destructor "
"called as expected.\n"); "called as expected.\n");
} }
virtual void TearDown() { void TearDown() override {
printf("%s", printf("%s",
"CxxExceptionInTestBodyTest::TearDown() " "CxxExceptionInTestBodyTest::TearDown() "
"called as expected.\n"); "called as expected.\n");
......
...@@ -31,6 +31,7 @@ ...@@ -31,6 +31,7 @@
// Tests for death tests. // Tests for death tests.
#include "gtest/gtest-death-test.h" #include "gtest/gtest-death-test.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-filepath.h"
...@@ -59,6 +60,8 @@ using testing::internal::AlwaysTrue; ...@@ -59,6 +60,8 @@ using testing::internal::AlwaysTrue;
namespace posix = ::testing::internal::posix; namespace posix = ::testing::internal::posix;
using testing::ContainsRegex;
using testing::Matcher;
using testing::Message; using testing::Message;
using testing::internal::DeathTest; using testing::internal::DeathTest;
using testing::internal::DeathTestFactory; using testing::internal::DeathTestFactory;
...@@ -97,6 +100,8 @@ class ReplaceDeathTestFactory { ...@@ -97,6 +100,8 @@ class ReplaceDeathTestFactory {
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
namespace {
void DieWithMessage(const ::std::string& message) { void DieWithMessage(const ::std::string& message) {
fprintf(stderr, "%s", message.c_str()); fprintf(stderr, "%s", message.c_str());
fflush(stderr); // Make sure the text is printed before the process exits. fflush(stderr); // Make sure the text is printed before the process exits.
...@@ -123,9 +128,7 @@ class TestForDeathTest : public testing::Test { ...@@ -123,9 +128,7 @@ class TestForDeathTest : public testing::Test {
protected: protected:
TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {} TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
virtual ~TestForDeathTest() { ~TestForDeathTest() override { posix::ChDir(original_dir_.c_str()); }
posix::ChDir(original_dir_.c_str());
}
// A static member function that's expected to die. // A static member function that's expected to die.
static void StaticMemberFunction() { DieInside("StaticMemberFunction"); } static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
...@@ -297,14 +300,14 @@ TEST_F(TestForDeathTest, SingleStatement) { ...@@ -297,14 +300,14 @@ TEST_F(TestForDeathTest, SingleStatement) {
EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3; EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
} }
# if GTEST_USES_PCRE
void DieWithEmbeddedNul() { void DieWithEmbeddedNul() {
fprintf(stderr, "Hello%cmy null world.\n", '\0'); fprintf(stderr, "Hello%cmy null world.\n", '\0');
fflush(stderr); fflush(stderr);
_exit(1); _exit(1);
} }
# if GTEST_USES_PCRE
// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
// message has a NUL character in it. // message has a NUL character in it.
TEST_F(TestForDeathTest, EmbeddedNulInMessage) { TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
...@@ -452,16 +455,12 @@ TEST_F(TestForDeathTest, MixedStyles) { ...@@ -452,16 +455,12 @@ TEST_F(TestForDeathTest, MixedStyles) {
# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
namespace {
bool pthread_flag; bool pthread_flag;
void SetPthreadFlag() { void SetPthreadFlag() {
pthread_flag = true; pthread_flag = true;
} }
} // namespace
TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
if (!testing::GTEST_FLAG(death_test_use_fork)) { if (!testing::GTEST_FLAG(death_test_use_fork)) {
testing::GTEST_FLAG(death_test_style) = "threadsafe"; testing::GTEST_FLAG(death_test_style) = "threadsafe";
...@@ -499,6 +498,10 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { ...@@ -499,6 +498,10 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
const ::string regex_str(regex_c_str); const ::string regex_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_str); EXPECT_DEATH(GlobalFunction(), regex_str);
// This one is tricky; a temporary pointer into another temporary. Reference
// lifetime extension of the pointer is not sufficient.
EXPECT_DEATH(GlobalFunction(), ::string(regex_c_str).c_str());
# endif // GTEST_HAS_GLOBAL_STRING # endif // GTEST_HAS_GLOBAL_STRING
# if !GTEST_USES_PCRE # if !GTEST_USES_PCRE
...@@ -506,6 +509,10 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { ...@@ -506,6 +509,10 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
const ::std::string regex_std_str(regex_c_str); const ::std::string regex_std_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_std_str); EXPECT_DEATH(GlobalFunction(), regex_std_str);
// This one is tricky; a temporary pointer into another temporary. Reference
// lifetime extension of the pointer is not sufficient.
EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());
# endif // !GTEST_USES_PCRE # endif // !GTEST_USES_PCRE
} }
...@@ -876,9 +883,9 @@ TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) { ...@@ -876,9 +883,9 @@ TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
class MockDeathTestFactory : public DeathTestFactory { class MockDeathTestFactory : public DeathTestFactory {
public: public:
MockDeathTestFactory(); MockDeathTestFactory();
virtual bool Create(const char* statement, bool Create(const char* statement,
const ::testing::internal::RE* regex, testing::Matcher<const std::string&> matcher, const char* file,
const char* file, int line, DeathTest** test); int line, DeathTest** test) override;
// Sets the parameters for subsequent calls to Create. // Sets the parameters for subsequent calls to Create.
void SetParameters(bool create, DeathTest::TestRole role, void SetParameters(bool create, DeathTest::TestRole role,
...@@ -933,22 +940,20 @@ class MockDeathTest : public DeathTest { ...@@ -933,22 +940,20 @@ class MockDeathTest : public DeathTest {
TestRole role, int status, bool passed) : TestRole role, int status, bool passed) :
parent_(parent), role_(role), status_(status), passed_(passed) { parent_(parent), role_(role), status_(status), passed_(passed) {
} }
virtual ~MockDeathTest() { ~MockDeathTest() override { parent_->test_deleted_ = true; }
parent_->test_deleted_ = true; TestRole AssumeRole() override {
}
virtual TestRole AssumeRole() {
++parent_->assume_role_calls_; ++parent_->assume_role_calls_;
return role_; return role_;
} }
virtual int Wait() { int Wait() override {
++parent_->wait_calls_; ++parent_->wait_calls_;
return status_; return status_;
} }
virtual bool Passed(bool exit_status_ok) { bool Passed(bool exit_status_ok) override {
parent_->passed_args_.push_back(exit_status_ok); parent_->passed_args_.push_back(exit_status_ok);
return passed_; return passed_;
} }
virtual void Abort(AbortReason reason) { void Abort(AbortReason reason) override {
parent_->abort_args_.push_back(reason); parent_->abort_args_.push_back(reason);
} }
...@@ -992,11 +997,9 @@ void MockDeathTestFactory::SetParameters(bool create, ...@@ -992,11 +997,9 @@ void MockDeathTestFactory::SetParameters(bool create,
// Sets test to NULL (if create_ is false) or to the address of a new // Sets test to NULL (if create_ is false) or to the address of a new
// MockDeathTest object with parameters taken from the last call // MockDeathTest object with parameters taken from the last call
// to SetParameters (if create_ is true). Always returns true. // to SetParameters (if create_ is true). Always returns true.
bool MockDeathTestFactory::Create(const char* /*statement*/, bool MockDeathTestFactory::Create(
const ::testing::internal::RE* /*regex*/, const char* /*statement*/, testing::Matcher<const std::string&> /*matcher*/,
const char* /*file*/, const char* /*file*/, int /*line*/, DeathTest** test) {
int /*line*/,
DeathTest** test) {
test_deleted_ = false; test_deleted_ = false;
if (create_) { if (create_) {
*test = new MockDeathTest(this, role_, status_, passed_); *test = new MockDeathTest(this, role_, status_, passed_);
...@@ -1318,8 +1321,49 @@ TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { ...@@ -1318,8 +1321,49 @@ TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
}, "Inside"); }, "Inside");
} }
void DieWithMessage(const char* message) {
fputs(message, stderr);
fflush(stderr); // Make sure the text is printed before the process exits.
_exit(1);
}
TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) {
// googletest tests this, of course; here we ensure that including googlemock
// has not broken it.
EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e");
}
TEST(MatcherDeathTest, MonomorphicMatcherMatches) {
EXPECT_DEATH(DieWithMessage("Behind O, I am slain!"),
Matcher<const std::string&>(ContainsRegex("I am slain")));
}
TEST(MatcherDeathTest, MonomorphicMatcherDoesNotMatch) {
EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(
DieWithMessage("Behind O, I am slain!"),
Matcher<const std::string&>(ContainsRegex("Ow, I am slain"))),
"Expected: contains regular expression \"Ow, I am slain\"");
}
TEST(MatcherDeathTest, PolymorphicMatcherMatches) {
EXPECT_DEATH(DieWithMessage("The rest is silence."),
ContainsRegex("rest is silence"));
}
TEST(MatcherDeathTest, PolymorphicMatcherDoesNotMatch) {
EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieWithMessage("The rest is silence."),
ContainsRegex("rest is science")),
"Expected: contains regular expression \"rest is science\"");
}
} // namespace
#else // !GTEST_HAS_DEATH_TEST follows #else // !GTEST_HAS_DEATH_TEST follows
namespace {
using testing::internal::CaptureStderr; using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr; using testing::internal::GetCapturedStderr;
...@@ -1368,8 +1412,12 @@ TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) { ...@@ -1368,8 +1412,12 @@ TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
EXPECT_EQ(1, n); EXPECT_EQ(1, n);
} }
} // namespace
#endif // !GTEST_HAS_DEATH_TEST #endif // !GTEST_HAS_DEATH_TEST
namespace {
// Tests that the death test macros expand to code which may or may not // Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text // be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement. // comprises only a single C++ statement.
...@@ -1420,3 +1468,5 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { ...@@ -1420,3 +1468,5 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
TEST(NotADeathTest, Test) { TEST(NotADeathTest, Test) {
SUCCEED(); SUCCEED();
} }
} // namespace
...@@ -59,7 +59,7 @@ TEST(CxxExceptionDeathTest, ExceptionIsFailure) { ...@@ -59,7 +59,7 @@ TEST(CxxExceptionDeathTest, ExceptionIsFailure) {
class TestException : public std::exception { class TestException : public std::exception {
public: public:
virtual const char* what() const throw() { return "exceptional message"; } const char* what() const throw() override { return "exceptional message"; }
}; };
TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
......
...@@ -45,8 +45,8 @@ environ = os.environ.copy() ...@@ -45,8 +45,8 @@ environ = os.environ.copy()
def AssertEq(expected, actual): def AssertEq(expected, actual):
if expected != actual: if expected != actual:
print 'Expected: %s' % (expected,) print('Expected: %s' % (expected,))
print ' Actual: %s' % (actual,) print(' Actual: %s' % (actual,))
raise AssertionError raise AssertionError
......
...@@ -80,7 +80,7 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) { ...@@ -80,7 +80,7 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) {
const FilePath cwd = FilePath::GetCurrentDir(); const FilePath cwd = FilePath::GetCurrentDir();
posix::ChDir(original_dir.c_str()); posix::ChDir(original_dir.c_str());
# if GTEST_OS_WINDOWS # if GTEST_OS_WINDOWS || GTEST_OS_OS2
// Skips the ":". // Skips the ":".
const char* const cwd_without_drive = strchr(cwd.c_str(), ':'); const char* const cwd_without_drive = strchr(cwd.c_str(), ':');
...@@ -479,7 +479,7 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) { ...@@ -479,7 +479,7 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
class DirectoryCreationTest : public Test { class DirectoryCreationTest : public Test {
protected: protected:
virtual void SetUp() { void SetUp() override {
testdata_path_.Set(FilePath( testdata_path_.Set(FilePath(
TempDir() + GetCurrentExecutableName().string() + TempDir() + GetCurrentExecutableName().string() +
"_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
...@@ -496,7 +496,7 @@ class DirectoryCreationTest : public Test { ...@@ -496,7 +496,7 @@ class DirectoryCreationTest : public Test {
posix::RmDir(testdata_path_.c_str()); posix::RmDir(testdata_path_.c_str());
} }
virtual void TearDown() { void TearDown() override {
remove(testdata_file_.c_str()); remove(testdata_file_.c_str());
remove(unique_file0_.c_str()); remove(unique_file0_.c_str());
remove(unique_file1_.c_str()); remove(unique_file1_.c_str());
......
...@@ -42,7 +42,10 @@ we test that here also. ...@@ -42,7 +42,10 @@ we test that here also.
import os import os
import re import re
import sets try:
from sets import Set as set # For Python 2.3 compatibility
except ImportError:
pass
import sys import sys
import gtest_test_utils import gtest_test_utils
...@@ -57,7 +60,7 @@ CAN_PASS_EMPTY_ENV = False ...@@ -57,7 +60,7 @@ CAN_PASS_EMPTY_ENV = False
if sys.executable: if sys.executable:
os.environ['EMPTY_VAR'] = '' os.environ['EMPTY_VAR'] = ''
child = gtest_test_utils.Subprocess( child = gtest_test_utils.Subprocess(
[sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ']) [sys.executable, '-c', 'import os; print(\'EMPTY_VAR\' in os.environ)'])
CAN_PASS_EMPTY_ENV = eval(child.output) CAN_PASS_EMPTY_ENV = eval(child.output)
...@@ -72,7 +75,7 @@ if sys.executable: ...@@ -72,7 +75,7 @@ if sys.executable:
os.environ['UNSET_VAR'] = 'X' os.environ['UNSET_VAR'] = 'X'
del os.environ['UNSET_VAR'] del os.environ['UNSET_VAR']
child = gtest_test_utils.Subprocess( child = gtest_test_utils.Subprocess(
[sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ' [sys.executable, '-c', 'import os; print(\'UNSET_VAR\' not in os.environ)'
]) ])
CAN_UNSET_ENV = eval(child.output) CAN_UNSET_ENV = eval(child.output)
...@@ -245,14 +248,14 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): ...@@ -245,14 +248,14 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
for slice_var in list_of_sets: for slice_var in list_of_sets:
full_partition.extend(slice_var) full_partition.extend(slice_var)
self.assertEqual(len(set_var), len(full_partition)) self.assertEqual(len(set_var), len(full_partition))
self.assertEqual(sets.Set(set_var), sets.Set(full_partition)) self.assertEqual(set(set_var), set(full_partition))
def AdjustForParameterizedTests(self, tests_to_run): def AdjustForParameterizedTests(self, tests_to_run):
"""Adjust tests_to_run in case value parameterized tests are disabled.""" """Adjust tests_to_run in case value parameterized tests are disabled."""
global param_tests_present global param_tests_present
if not param_tests_present: if not param_tests_present:
return list(sets.Set(tests_to_run) - sets.Set(PARAM_TESTS)) return list(set(tests_to_run) - set(PARAM_TESTS))
else: else:
return tests_to_run return tests_to_run
......
...@@ -57,7 +57,7 @@ else: ...@@ -57,7 +57,7 @@ else:
STACK_TRACE_TEMPLATE = '' STACK_TRACE_TEMPLATE = ''
EXPECTED_NON_EMPTY = { EXPECTED_NON_EMPTY = {
u'tests': 23, u'tests': 24,
u'failures': 4, u'failures': 4,
u'disabled': 2, u'disabled': 2,
u'errors': 0, u'errors': 0,
...@@ -123,6 +123,22 @@ EXPECTED_NON_EMPTY = { ...@@ -123,6 +123,22 @@ EXPECTED_NON_EMPTY = {
} }
] ]
}, },
{
u'name': u'SkippedTest',
u'tests': 1,
u'failures': 0,
u'disabled': 0,
u'errors': 0,
u'time': u'*',
u'testsuite': [
{
u'name': u'Skipped',
u'status': u'SKIPPED',
u'time': u'*',
u'classname': u'SkippedTest'
}
]
},
{ {
u'name': u'MixedResultTest', u'name': u'MixedResultTest',
u'tests': 3, u'tests': 3,
......
// Copyright 2003, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdlib.h>
#include "gtest/internal/gtest-linked_ptr.h"
#include "gtest/gtest.h"
namespace {
using testing::Message;
using testing::internal::linked_ptr;
int num;
Message* history = nullptr;
// Class which tracks allocation/deallocation
class A {
public:
A(): mynum(num++) { *history << "A" << mynum << " ctor\n"; }
virtual ~A() { *history << "A" << mynum << " dtor\n"; }
virtual void Use() { *history << "A" << mynum << " use\n"; }
protected:
int mynum;
};
// Subclass
class B : public A {
public:
B() { *history << "B" << mynum << " ctor\n"; }
~B() { *history << "B" << mynum << " dtor\n"; }
virtual void Use() { *history << "B" << mynum << " use\n"; }
};
class LinkedPtrTest : public testing::Test {
public:
LinkedPtrTest() {
num = 0;
history = new Message;
}
virtual ~LinkedPtrTest() {
delete history;
history = nullptr;
}
};
TEST_F(LinkedPtrTest, GeneralTest) {
{
linked_ptr<A> a0, a1, a2;
// Use explicit function call notation here to suppress self-assign warning.
a0.operator=(a0);
a1 = a2;
ASSERT_EQ(a0.get(), static_cast<A*>(nullptr));
ASSERT_EQ(a1.get(), static_cast<A*>(nullptr));
ASSERT_EQ(a2.get(), static_cast<A*>(nullptr));
ASSERT_TRUE(a0 == nullptr);
ASSERT_TRUE(a1 == nullptr);
ASSERT_TRUE(a2 == nullptr);
{
linked_ptr<A> a3(new A);
a0 = a3;
ASSERT_TRUE(a0 == a3);
ASSERT_TRUE(a0 != nullptr);
ASSERT_TRUE(a0.get() == a3);
ASSERT_TRUE(a0 == a3.get());
linked_ptr<A> a4(a0);
a1 = a4;
linked_ptr<A> a5(new A);
ASSERT_TRUE(a5.get() != a3);
ASSERT_TRUE(a5 != a3.get());
a2 = a5;
linked_ptr<B> b0(new B);
linked_ptr<A> a6(b0);
ASSERT_TRUE(b0 == a6);
ASSERT_TRUE(a6 == b0);
ASSERT_TRUE(b0 != nullptr);
a5 = b0;
a5 = b0;
a3->Use();
a4->Use();
a5->Use();
a6->Use();
b0->Use();
(*b0).Use();
b0.get()->Use();
}
a0->Use();
a1->Use();
a2->Use();
a1 = a2;
a2.reset(new A);
a0.reset();
linked_ptr<A> a7;
}
ASSERT_STREQ(
"A0 ctor\n"
"A1 ctor\n"
"A2 ctor\n"
"B2 ctor\n"
"A0 use\n"
"A0 use\n"
"B2 use\n"
"B2 use\n"
"B2 use\n"
"B2 use\n"
"B2 use\n"
"B2 dtor\n"
"A2 dtor\n"
"A0 use\n"
"A0 use\n"
"A1 use\n"
"A3 ctor\n"
"A0 dtor\n"
"A3 dtor\n"
"A1 dtor\n",
history->GetString().c_str());
}
} // Unnamed namespace
...@@ -57,63 +57,63 @@ class EventRecordingListener : public TestEventListener { ...@@ -57,63 +57,63 @@ class EventRecordingListener : public TestEventListener {
explicit EventRecordingListener(const char* name) : name_(name) {} explicit EventRecordingListener(const char* name) : name_(name) {}
protected: protected:
virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
g_events->push_back(GetFullMethodName("OnTestProgramStart")); g_events->push_back(GetFullMethodName("OnTestProgramStart"));
} }
virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, void OnTestIterationStart(const UnitTest& /*unit_test*/,
int iteration) { int iteration) override {
Message message; Message message;
message << GetFullMethodName("OnTestIterationStart") message << GetFullMethodName("OnTestIterationStart")
<< "(" << iteration << ")"; << "(" << iteration << ")";
g_events->push_back(message.GetString()); g_events->push_back(message.GetString());
} }
virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) { void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {
g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpStart")); g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpStart"));
} }
virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) { void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {
g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpEnd")); g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpEnd"));
} }
virtual void OnTestCaseStart(const TestCase& /*test_case*/) { void OnTestCaseStart(const TestCase& /*test_case*/) override {
g_events->push_back(GetFullMethodName("OnTestCaseStart")); g_events->push_back(GetFullMethodName("OnTestCaseStart"));
} }
virtual void OnTestStart(const TestInfo& /*test_info*/) { void OnTestStart(const TestInfo& /*test_info*/) override {
g_events->push_back(GetFullMethodName("OnTestStart")); g_events->push_back(GetFullMethodName("OnTestStart"));
} }
virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) { void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {
g_events->push_back(GetFullMethodName("OnTestPartResult")); g_events->push_back(GetFullMethodName("OnTestPartResult"));
} }
virtual void OnTestEnd(const TestInfo& /*test_info*/) { void OnTestEnd(const TestInfo& /*test_info*/) override {
g_events->push_back(GetFullMethodName("OnTestEnd")); g_events->push_back(GetFullMethodName("OnTestEnd"));
} }
virtual void OnTestCaseEnd(const TestCase& /*test_case*/) { void OnTestCaseEnd(const TestCase& /*test_case*/) override {
g_events->push_back(GetFullMethodName("OnTestCaseEnd")); g_events->push_back(GetFullMethodName("OnTestCaseEnd"));
} }
virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) { void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {
g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownStart")); g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownStart"));
} }
virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) { void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {
g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownEnd")); g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownEnd"));
} }
virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, void OnTestIterationEnd(const UnitTest& /*unit_test*/,
int iteration) { int iteration) override {
Message message; Message message;
message << GetFullMethodName("OnTestIterationEnd") message << GetFullMethodName("OnTestIterationEnd")
<< "(" << iteration << ")"; << "(" << iteration << ")";
g_events->push_back(message.GetString()); g_events->push_back(message.GetString());
} }
virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) { void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
g_events->push_back(GetFullMethodName("OnTestProgramEnd")); g_events->push_back(GetFullMethodName("OnTestProgramEnd"));
} }
...@@ -127,13 +127,9 @@ class EventRecordingListener : public TestEventListener { ...@@ -127,13 +127,9 @@ class EventRecordingListener : public TestEventListener {
class EnvironmentInvocationCatcher : public Environment { class EnvironmentInvocationCatcher : public Environment {
protected: protected:
virtual void SetUp() { void SetUp() override { g_events->push_back("Environment::SetUp"); }
g_events->push_back("Environment::SetUp");
}
virtual void TearDown() { void TearDown() override { g_events->push_back("Environment::TearDown"); }
g_events->push_back("Environment::TearDown");
}
}; };
class ListenerTest : public Test { class ListenerTest : public Test {
...@@ -146,13 +142,9 @@ class ListenerTest : public Test { ...@@ -146,13 +142,9 @@ class ListenerTest : public Test {
g_events->push_back("ListenerTest::TearDownTestCase"); g_events->push_back("ListenerTest::TearDownTestCase");
} }
virtual void SetUp() { void SetUp() override { g_events->push_back("ListenerTest::SetUp"); }
g_events->push_back("ListenerTest::SetUp");
}
virtual void TearDown() { void TearDown() override { g_events->push_back("ListenerTest::TearDown"); }
g_events->push_back("ListenerTest::TearDown");
}
}; };
TEST_F(ListenerTest, DoesFoo) { TEST_F(ListenerTest, DoesFoo) {
......
...@@ -102,6 +102,12 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { ...@@ -102,6 +102,12 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
_strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 || _strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 ||
_strcmpi("gtest_all_test", exe_str.c_str()) == 0 || _strcmpi("gtest_all_test", exe_str.c_str()) == 0 ||
_strcmpi("gtest_dll_test", exe_str.c_str()) == 0; _strcmpi("gtest_dll_test", exe_str.c_str()) == 0;
#elif GTEST_OS_OS2
const bool success =
strcasecmp("googletest-options-test", exe_str.c_str()) == 0 ||
strcasecmp("gtest-options-ex_test", exe_str.c_str()) == 0 ||
strcasecmp("gtest_all_test", exe_str.c_str()) == 0 ||
strcasecmp("gtest_dll_test", exe_str.c_str()) == 0;
#elif GTEST_OS_FUCHSIA #elif GTEST_OS_FUCHSIA
const bool success = exe_str == "app"; const bool success = exe_str == "app";
#else #else
...@@ -120,7 +126,7 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { ...@@ -120,7 +126,7 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
class XmlOutputChangeDirTest : public Test { class XmlOutputChangeDirTest : public Test {
protected: protected:
virtual void SetUp() { void SetUp() override {
original_working_dir_ = FilePath::GetCurrentDir(); original_working_dir_ = FilePath::GetCurrentDir();
posix::ChDir(".."); posix::ChDir("..");
// This will make the test fail if run from the root directory. // This will make the test fail if run from the root directory.
...@@ -128,7 +134,7 @@ class XmlOutputChangeDirTest : public Test { ...@@ -128,7 +134,7 @@ class XmlOutputChangeDirTest : public Test {
FilePath::GetCurrentDir().string()); FilePath::GetCurrentDir().string());
} }
virtual void TearDown() { void TearDown() override {
posix::ChDir(original_working_dir_.string().c_str()); posix::ChDir(original_working_dir_.string().c_str());
} }
......
...@@ -12,7 +12,7 @@ Expected equality of these values: ...@@ -12,7 +12,7 @@ Expected equality of these values:
3 3
Stack trace: (omitted) Stack trace: (omitted)
[==========] Running 76 tests from 34 test cases. [==========] Running 83 tests from 38 test cases.
[----------] Global test environment set-up. [----------] Global test environment set-up.
FooEnvironment::SetUp() called. FooEnvironment::SetUp() called.
BarEnvironment::SetUp() called. BarEnvironment::SetUp() called.
...@@ -870,6 +870,84 @@ Expected non-fatal failure. ...@@ -870,6 +870,84 @@ Expected non-fatal failure.
Stack trace: (omitted) Stack trace: (omitted)
[ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread [ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread
[----------] 2 tests from DynamicFixture
DynamicFixture::SetUpTestCase
[ RUN ] DynamicFixture.DynamicTestPass
DynamicFixture()
DynamicFixture::SetUp
DynamicFixture::TearDown
~DynamicFixture()
[ OK ] DynamicFixture.DynamicTestPass
[ RUN ] DynamicFixture.DynamicTestFail
DynamicFixture()
DynamicFixture::SetUp
googletest-output-test_.cc:#: Failure
Value of: Pass
Actual: false
Expected: true
Stack trace: (omitted)
DynamicFixture::TearDown
~DynamicFixture()
[ FAILED ] DynamicFixture.DynamicTestFail
DynamicFixture::TearDownTestCase
[----------] 1 test from DynamicFixtureAnotherName
DynamicFixture::SetUpTestCase
[ RUN ] DynamicFixtureAnotherName.DynamicTestPass
DynamicFixture()
DynamicFixture::SetUp
DynamicFixture::TearDown
~DynamicFixture()
[ OK ] DynamicFixtureAnotherName.DynamicTestPass
DynamicFixture::TearDownTestCase
[----------] 2 tests from BadDynamicFixture1
DynamicFixture::SetUpTestCase
[ RUN ] BadDynamicFixture1.FixtureBase
DynamicFixture()
DynamicFixture::SetUp
DynamicFixture::TearDown
~DynamicFixture()
[ OK ] BadDynamicFixture1.FixtureBase
[ RUN ] BadDynamicFixture1.TestBase
DynamicFixture()
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class, so mixing TEST_F and TEST in the same test case is
illegal. In test case BadDynamicFixture1,
test FixtureBase is defined using TEST_F but
test TestBase is defined using TEST. You probably
want to change the TEST to TEST_F or move it to another test
case.
Stack trace: (omitted)
~DynamicFixture()
[ FAILED ] BadDynamicFixture1.TestBase
DynamicFixture::TearDownTestCase
[----------] 2 tests from BadDynamicFixture2
DynamicFixture::SetUpTestCase
[ RUN ] BadDynamicFixture2.FixtureBase
DynamicFixture()
DynamicFixture::SetUp
DynamicFixture::TearDown
~DynamicFixture()
[ OK ] BadDynamicFixture2.FixtureBase
[ RUN ] BadDynamicFixture2.Derived
DynamicFixture()
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class. However, in test case BadDynamicFixture2,
you defined test FixtureBase and test Derived
using two different test fixture classes. This can happen if
the two classes are from different namespaces or translation
units and have the same name. You should probably rename one
of the classes to put the tests into different test cases.
Stack trace: (omitted)
~DynamicFixture()
[ FAILED ] BadDynamicFixture2.Derived
DynamicFixture::TearDownTestCase
[----------] 1 test from PrintingFailingParams/FailingParamTest [----------] 1 test from PrintingFailingParams/FailingParamTest
[ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 [ RUN ] PrintingFailingParams/FailingParamTest.Fails/0
googletest-output-test_.cc:#: Failure googletest-output-test_.cc:#: Failure
...@@ -906,9 +984,9 @@ Failed ...@@ -906,9 +984,9 @@ Failed
Expected fatal failure. Expected fatal failure.
Stack trace: (omitted) Stack trace: (omitted)
[==========] 76 tests from 34 test cases ran. [==========] 83 tests from 38 test cases ran.
[ PASSED ] 26 tests. [ PASSED ] 30 tests.
[ FAILED ] 50 tests, listed below: [ FAILED ] 53 tests, listed below:
[ FAILED ] NonfatalFailureTest.EscapesStringOperands [ FAILED ] NonfatalFailureTest.EscapesStringOperands
[ FAILED ] NonfatalFailureTest.DiffForLongStrings [ FAILED ] NonfatalFailureTest.DiffForLongStrings
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine [ FAILED ] FatalFailureTest.FatalFailureInSubroutine
...@@ -957,10 +1035,13 @@ Stack trace: (omitted) ...@@ -957,10 +1035,13 @@ Stack trace: (omitted)
[ FAILED ] ExpectFailureWithThreadsTest.ExpectFatalFailure [ FAILED ] ExpectFailureWithThreadsTest.ExpectFatalFailure
[ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure [ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure
[ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread [ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread
[ FAILED ] DynamicFixture.DynamicTestFail
[ FAILED ] BadDynamicFixture1.TestBase
[ FAILED ] BadDynamicFixture2.Derived
[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 [ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" [ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
50 FAILED TESTS 53 FAILED TESTS
 YOU HAVE 1 DISABLED TEST  YOU HAVE 1 DISABLED TEST
Note: Google Test filter = FatalFailureTest.*:LoggingTest.* Note: Google Test filter = FatalFailureTest.*:LoggingTest.*
......
...@@ -287,7 +287,7 @@ class GTestOutputTest(gtest_test_utils.TestCase): ...@@ -287,7 +287,7 @@ class GTestOutputTest(gtest_test_utils.TestCase):
# sequences when we read the golden file irrespective of an operating # sequences when we read the golden file irrespective of an operating
# system used. Therefore, we need to strip those \r's from newlines # system used. Therefore, we need to strip those \r's from newlines
# unconditionally. # unconditionally.
golden = ToUnixLineEnding(golden_file.read()) golden = ToUnixLineEnding(golden_file.read().decode())
golden_file.close() golden_file.close()
# We want the test to pass regardless of certain features being # We want the test to pass regardless of certain features being
......
...@@ -364,15 +364,13 @@ class NonFatalFailureInFixtureConstructorTest : public testing::Test { ...@@ -364,15 +364,13 @@ class NonFatalFailureInFixtureConstructorTest : public testing::Test {
ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor."; ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
} }
~NonFatalFailureInFixtureConstructorTest() { ~NonFatalFailureInFixtureConstructorTest() override {
ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor."; ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
} }
virtual void SetUp() { void SetUp() override { ADD_FAILURE() << "Expected failure #2, in SetUp()."; }
ADD_FAILURE() << "Expected failure #2, in SetUp().";
}
virtual void TearDown() { void TearDown() override {
ADD_FAILURE() << "Expected failure #4, in TearDown."; ADD_FAILURE() << "Expected failure #4, in TearDown.";
} }
}; };
...@@ -389,17 +387,17 @@ class FatalFailureInFixtureConstructorTest : public testing::Test { ...@@ -389,17 +387,17 @@ class FatalFailureInFixtureConstructorTest : public testing::Test {
Init(); Init();
} }
~FatalFailureInFixtureConstructorTest() { ~FatalFailureInFixtureConstructorTest() override {
ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor."; ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
} }
virtual void SetUp() { void SetUp() override {
ADD_FAILURE() << "UNEXPECTED failure in SetUp(). " ADD_FAILURE() << "UNEXPECTED failure in SetUp(). "
<< "We should never get here, as the test fixture c'tor " << "We should never get here, as the test fixture c'tor "
<< "had a fatal failure."; << "had a fatal failure.";
} }
virtual void TearDown() { void TearDown() override {
ADD_FAILURE() << "UNEXPECTED failure in TearDown(). " ADD_FAILURE() << "UNEXPECTED failure in TearDown(). "
<< "We should never get here, as the test fixture c'tor " << "We should never get here, as the test fixture c'tor "
<< "had a fatal failure."; << "had a fatal failure.";
...@@ -420,18 +418,15 @@ TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { ...@@ -420,18 +418,15 @@ TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
// Tests non-fatal failures in SetUp(). // Tests non-fatal failures in SetUp().
class NonFatalFailureInSetUpTest : public testing::Test { class NonFatalFailureInSetUpTest : public testing::Test {
protected: protected:
virtual ~NonFatalFailureInSetUpTest() { ~NonFatalFailureInSetUpTest() override { Deinit(); }
Deinit();
}
virtual void SetUp() { void SetUp() override {
printf("(expecting 4 failures)\n"); printf("(expecting 4 failures)\n");
ADD_FAILURE() << "Expected failure #1, in SetUp()."; ADD_FAILURE() << "Expected failure #1, in SetUp().";
} }
virtual void TearDown() { void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; }
FAIL() << "Expected failure #3, in TearDown().";
}
private: private:
void Deinit() { void Deinit() {
FAIL() << "Expected failure #4, in the test fixture d'tor."; FAIL() << "Expected failure #4, in the test fixture d'tor.";
...@@ -445,18 +440,15 @@ TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { ...@@ -445,18 +440,15 @@ TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
// Tests fatal failures in SetUp(). // Tests fatal failures in SetUp().
class FatalFailureInSetUpTest : public testing::Test { class FatalFailureInSetUpTest : public testing::Test {
protected: protected:
virtual ~FatalFailureInSetUpTest() { ~FatalFailureInSetUpTest() override { Deinit(); }
Deinit();
}
virtual void SetUp() { void SetUp() override {
printf("(expecting 3 failures)\n"); printf("(expecting 3 failures)\n");
FAIL() << "Expected failure #1, in SetUp()."; FAIL() << "Expected failure #1, in SetUp().";
} }
virtual void TearDown() { void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; }
FAIL() << "Expected failure #2, in TearDown().";
}
private: private:
void Deinit() { void Deinit() {
FAIL() << "Expected failure #3, in the test fixture d'tor."; FAIL() << "Expected failure #3, in the test fixture d'tor.";
...@@ -508,7 +500,7 @@ static void ThreadRoutine(SpawnThreadNotifications* notifications) { ...@@ -508,7 +500,7 @@ static void ThreadRoutine(SpawnThreadNotifications* notifications) {
class DeathTestAndMultiThreadsTest : public testing::Test { class DeathTestAndMultiThreadsTest : public testing::Test {
protected: protected:
// Starts a thread and waits for it to begin. // Starts a thread and waits for it to begin.
virtual void SetUp() { void SetUp() override {
thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>( thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>(
&ThreadRoutine, &notifications_, nullptr)); &ThreadRoutine, &notifications_, nullptr));
notifications_.spawn_thread_started.WaitForNotification(); notifications_.spawn_thread_started.WaitForNotification();
...@@ -518,14 +510,13 @@ class DeathTestAndMultiThreadsTest : public testing::Test { ...@@ -518,14 +510,13 @@ class DeathTestAndMultiThreadsTest : public testing::Test {
// a manager thread might still be left running that will interfere // a manager thread might still be left running that will interfere
// with later death tests. This is unfortunate, but this class // with later death tests. This is unfortunate, but this class
// cleans up after itself as best it can. // cleans up after itself as best it can.
virtual void TearDown() { void TearDown() override {
notifications_.spawn_thread_ok_to_terminate.Notify(); notifications_.spawn_thread_ok_to_terminate.Notify();
} }
private: private:
SpawnThreadNotifications notifications_; SpawnThreadNotifications notifications_;
testing::internal::scoped_ptr<ThreadWithParam<SpawnThreadNotifications*> > std::unique_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_;
thread_;
}; };
#endif // GTEST_IS_THREADSAFE #endif // GTEST_IS_THREADSAFE
...@@ -1033,16 +1024,64 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { ...@@ -1033,16 +1024,64 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
"Some other non-fatal failure."); "Some other non-fatal failure.");
} }
class DynamicFixture : public testing::Test {
protected:
DynamicFixture() { printf("DynamicFixture()\n"); }
~DynamicFixture() override { printf("~DynamicFixture()\n"); }
void SetUp() override { printf("DynamicFixture::SetUp\n"); }
void TearDown() override { printf("DynamicFixture::TearDown\n"); }
static void SetUpTestCase() { printf("DynamicFixture::SetUpTestCase\n"); }
static void TearDownTestCase() {
printf("DynamicFixture::TearDownTestCase\n");
}
};
template <bool Pass>
class DynamicTest : public DynamicFixture {
public:
void TestBody() override { EXPECT_TRUE(Pass); }
};
auto dynamic_test = (
// Register two tests with the same fixture correctly.
testing::RegisterTest(
"DynamicFixture", "DynamicTestPass", nullptr, nullptr, __FILE__,
__LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
testing::RegisterTest(
"DynamicFixture", "DynamicTestFail", nullptr, nullptr, __FILE__,
__LINE__, []() -> DynamicFixture* { return new DynamicTest<false>; }),
// Register the same fixture with another name. That's fine.
testing::RegisterTest(
"DynamicFixtureAnotherName", "DynamicTestPass", nullptr, nullptr,
__FILE__, __LINE__,
[]() -> DynamicFixture* { return new DynamicTest<true>; }),
// Register two tests with the same fixture incorrectly.
testing::RegisterTest(
"BadDynamicFixture1", "FixtureBase", nullptr, nullptr, __FILE__,
__LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
testing::RegisterTest(
"BadDynamicFixture1", "TestBase", nullptr, nullptr, __FILE__, __LINE__,
[]() -> testing::Test* { return new DynamicTest<true>; }),
// Register two tests with the same fixture incorrectly by ommiting the
// return type.
testing::RegisterTest(
"BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__,
__LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
testing::RegisterTest("BadDynamicFixture2", "Derived", nullptr, nullptr,
__FILE__, __LINE__,
[]() { return new DynamicTest<true>; }));
// Two test environments for testing testing::AddGlobalTestEnvironment(). // Two test environments for testing testing::AddGlobalTestEnvironment().
class FooEnvironment : public testing::Environment { class FooEnvironment : public testing::Environment {
public: public:
virtual void SetUp() { void SetUp() override { printf("%s", "FooEnvironment::SetUp() called.\n"); }
printf("%s", "FooEnvironment::SetUp() called.\n");
}
virtual void TearDown() { void TearDown() override {
printf("%s", "FooEnvironment::TearDown() called.\n"); printf("%s", "FooEnvironment::TearDown() called.\n");
FAIL() << "Expected fatal failure."; FAIL() << "Expected fatal failure.";
} }
...@@ -1050,11 +1089,9 @@ class FooEnvironment : public testing::Environment { ...@@ -1050,11 +1089,9 @@ class FooEnvironment : public testing::Environment {
class BarEnvironment : public testing::Environment { class BarEnvironment : public testing::Environment {
public: public:
virtual void SetUp() { void SetUp() override { printf("%s", "BarEnvironment::SetUp() called.\n"); }
printf("%s", "BarEnvironment::SetUp() called.\n");
}
virtual void TearDown() { void TearDown() override {
printf("%s", "BarEnvironment::TearDown() called.\n"); printf("%s", "BarEnvironment::TearDown() called.\n");
ADD_FAILURE() << "Expected non-fatal failure."; ADD_FAILURE() << "Expected non-fatal failure.";
} }
......
...@@ -49,19 +49,13 @@ using ::std::sort; ...@@ -49,19 +49,13 @@ using ::std::sort;
using ::testing::AddGlobalTestEnvironment; using ::testing::AddGlobalTestEnvironment;
using ::testing::Bool; using ::testing::Bool;
using ::testing::Combine;
using ::testing::Message; using ::testing::Message;
using ::testing::Range; using ::testing::Range;
using ::testing::TestWithParam; using ::testing::TestWithParam;
using ::testing::Values; using ::testing::Values;
using ::testing::ValuesIn; using ::testing::ValuesIn;
# if GTEST_HAS_COMBINE
using ::testing::Combine;
using ::testing::get;
using ::testing::make_tuple;
using ::testing::tuple;
# endif // GTEST_HAS_COMBINE
using ::testing::internal::ParamGenerator; using ::testing::internal::ParamGenerator;
using ::testing::internal::UnitTestOptions; using ::testing::internal::UnitTestOptions;
...@@ -73,49 +67,9 @@ using ::testing::internal::UnitTestOptions; ...@@ -73,49 +67,9 @@ using ::testing::internal::UnitTestOptions;
// EXPECT_THAT() and the matchers know how to print tuples. // EXPECT_THAT() and the matchers know how to print tuples.
template <typename T> template <typename T>
::std::string PrintValue(const T& value) { ::std::string PrintValue(const T& value) {
::std::stringstream stream; return testing::PrintToString(value);
stream << value;
return stream.str();
}
# if GTEST_HAS_COMBINE
// These overloads allow printing tuples in our tests. We cannot
// define an operator<< for tuples, as that definition needs to be in
// the std namespace in order to be picked up by Google Test via
// Argument-Dependent Lookup, yet defining anything in the std
// namespace in non-STL code is undefined behavior.
template <typename T1, typename T2>
::std::string PrintValue(const tuple<T1, T2>& value) {
::std::stringstream stream;
stream << "(" << get<0>(value) << ", " << get<1>(value) << ")";
return stream.str();
}
template <typename T1, typename T2, typename T3>
::std::string PrintValue(const tuple<T1, T2, T3>& value) {
::std::stringstream stream;
stream << "(" << get<0>(value) << ", " << get<1>(value)
<< ", "<< get<2>(value) << ")";
return stream.str();
}
template <typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6, typename T7, typename T8, typename T9, typename T10>
::std::string PrintValue(
const tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& value) {
::std::stringstream stream;
stream << "(" << get<0>(value) << ", " << get<1>(value)
<< ", "<< get<2>(value) << ", " << get<3>(value)
<< ", "<< get<4>(value) << ", " << get<5>(value)
<< ", "<< get<6>(value) << ", " << get<7>(value)
<< ", "<< get<8>(value) << ", " << get<9>(value) << ")";
return stream.str();
} }
# endif // GTEST_HAS_COMBINE
// Verifies that a sequence generated by the generator and accessed // Verifies that a sequence generated by the generator and accessed
// via the iterator object matches the expected one using Google Test // via the iterator object matches the expected one using Google Test
// assertions. // assertions.
...@@ -450,31 +404,28 @@ TEST(BoolTest, BoolWorks) { ...@@ -450,31 +404,28 @@ TEST(BoolTest, BoolWorks) {
VerifyGenerator(gen, expected_values); VerifyGenerator(gen, expected_values);
} }
# if GTEST_HAS_COMBINE
// Tests that Combine() with two parameters generates the expected sequence. // Tests that Combine() with two parameters generates the expected sequence.
TEST(CombineTest, CombineWithTwoParameters) { TEST(CombineTest, CombineWithTwoParameters) {
const char* foo = "foo"; const char* foo = "foo";
const char* bar = "bar"; const char* bar = "bar";
const ParamGenerator<tuple<const char*, int> > gen = const ParamGenerator<std::tuple<const char*, int> > gen =
Combine(Values(foo, bar), Values(3, 4)); Combine(Values(foo, bar), Values(3, 4));
tuple<const char*, int> expected_values[] = { std::tuple<const char*, int> expected_values[] = {
make_tuple(foo, 3), make_tuple(foo, 4), std::make_tuple(foo, 3), std::make_tuple(foo, 4), std::make_tuple(bar, 3),
make_tuple(bar, 3), make_tuple(bar, 4)}; std::make_tuple(bar, 4)};
VerifyGenerator(gen, expected_values); VerifyGenerator(gen, expected_values);
} }
// Tests that Combine() with three parameters generates the expected sequence. // Tests that Combine() with three parameters generates the expected sequence.
TEST(CombineTest, CombineWithThreeParameters) { TEST(CombineTest, CombineWithThreeParameters) {
const ParamGenerator<tuple<int, int, int> > gen = Combine(Values(0, 1), const ParamGenerator<std::tuple<int, int, int> > gen =
Values(3, 4), Combine(Values(0, 1), Values(3, 4), Values(5, 6));
Values(5, 6)); std::tuple<int, int, int> expected_values[] = {
tuple<int, int, int> expected_values[] = { std::make_tuple(0, 3, 5), std::make_tuple(0, 3, 6),
make_tuple(0, 3, 5), make_tuple(0, 3, 6), std::make_tuple(0, 4, 5), std::make_tuple(0, 4, 6),
make_tuple(0, 4, 5), make_tuple(0, 4, 6), std::make_tuple(1, 3, 5), std::make_tuple(1, 3, 6),
make_tuple(1, 3, 5), make_tuple(1, 3, 6), std::make_tuple(1, 4, 5), std::make_tuple(1, 4, 6)};
make_tuple(1, 4, 5), make_tuple(1, 4, 6)};
VerifyGenerator(gen, expected_values); VerifyGenerator(gen, expected_values);
} }
...@@ -482,10 +433,11 @@ TEST(CombineTest, CombineWithThreeParameters) { ...@@ -482,10 +433,11 @@ TEST(CombineTest, CombineWithThreeParameters) {
// sequence generates a sequence with the number of elements equal to the // sequence generates a sequence with the number of elements equal to the
// number of elements in the sequence generated by the second parameter. // number of elements in the sequence generated by the second parameter.
TEST(CombineTest, CombineWithFirstParameterSingleValue) { TEST(CombineTest, CombineWithFirstParameterSingleValue) {
const ParamGenerator<tuple<int, int> > gen = Combine(Values(42), const ParamGenerator<std::tuple<int, int> > gen =
Values(0, 1)); Combine(Values(42), Values(0, 1));
tuple<int, int> expected_values[] = {make_tuple(42, 0), make_tuple(42, 1)}; std::tuple<int, int> expected_values[] = {std::make_tuple(42, 0),
std::make_tuple(42, 1)};
VerifyGenerator(gen, expected_values); VerifyGenerator(gen, expected_values);
} }
...@@ -493,26 +445,27 @@ TEST(CombineTest, CombineWithFirstParameterSingleValue) { ...@@ -493,26 +445,27 @@ TEST(CombineTest, CombineWithFirstParameterSingleValue) {
// sequence generates a sequence with the number of elements equal to the // sequence generates a sequence with the number of elements equal to the
// number of elements in the sequence generated by the first parameter. // number of elements in the sequence generated by the first parameter.
TEST(CombineTest, CombineWithSecondParameterSingleValue) { TEST(CombineTest, CombineWithSecondParameterSingleValue) {
const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1), const ParamGenerator<std::tuple<int, int> > gen =
Values(42)); Combine(Values(0, 1), Values(42));
tuple<int, int> expected_values[] = {make_tuple(0, 42), make_tuple(1, 42)}; std::tuple<int, int> expected_values[] = {std::make_tuple(0, 42),
std::make_tuple(1, 42)};
VerifyGenerator(gen, expected_values); VerifyGenerator(gen, expected_values);
} }
// Tests that when the first parameter produces an empty sequence, // Tests that when the first parameter produces an empty sequence,
// Combine() produces an empty sequence, too. // Combine() produces an empty sequence, too.
TEST(CombineTest, CombineWithFirstParameterEmptyRange) { TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
const ParamGenerator<tuple<int, int> > gen = Combine(Range(0, 0), const ParamGenerator<std::tuple<int, int> > gen =
Values(0, 1)); Combine(Range(0, 0), Values(0, 1));
VerifyGeneratorIsEmpty(gen); VerifyGeneratorIsEmpty(gen);
} }
// Tests that when the second parameter produces an empty sequence, // Tests that when the second parameter produces an empty sequence,
// Combine() produces an empty sequence, too. // Combine() produces an empty sequence, too.
TEST(CombineTest, CombineWithSecondParameterEmptyRange) { TEST(CombineTest, CombineWithSecondParameterEmptyRange) {
const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1), const ParamGenerator<std::tuple<int, int> > gen =
Range(1, 1)); Combine(Values(0, 1), Range(1, 1));
VerifyGeneratorIsEmpty(gen); VerifyGeneratorIsEmpty(gen);
} }
...@@ -521,17 +474,15 @@ TEST(CombineTest, CombineWithSecondParameterEmptyRange) { ...@@ -521,17 +474,15 @@ TEST(CombineTest, CombineWithSecondParameterEmptyRange) {
TEST(CombineTest, CombineWithMaxNumberOfParameters) { TEST(CombineTest, CombineWithMaxNumberOfParameters) {
const char* foo = "foo"; const char* foo = "foo";
const char* bar = "bar"; const char* bar = "bar";
const ParamGenerator<tuple<const char*, int, int, int, int, int, int, int, const ParamGenerator<
int, int> > gen = Combine(Values(foo, bar), std::tuple<const char*, int, int, int, int, int, int, int, int, int> >
Values(1), Values(2), gen =
Values(3), Values(4), Combine(Values(foo, bar), Values(1), Values(2), Values(3), Values(4),
Values(5), Values(6), Values(5), Values(6), Values(7), Values(8), Values(9));
Values(7), Values(8),
Values(9)); std::tuple<const char*, int, int, int, int, int, int, int, int, int>
expected_values[] = {std::make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9),
tuple<const char*, int, int, int, int, int, int, int, int, int> std::make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)};
expected_values[] = {make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9),
make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)};
VerifyGenerator(gen, expected_values); VerifyGenerator(gen, expected_values);
} }
...@@ -551,12 +502,12 @@ class NonDefaultConstructAssignString { ...@@ -551,12 +502,12 @@ class NonDefaultConstructAssignString {
}; };
TEST(CombineTest, NonDefaultConstructAssign) { TEST(CombineTest, NonDefaultConstructAssign) {
const ParamGenerator<tuple<int, NonDefaultConstructAssignString> > gen = const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> > gen =
Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"), Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
NonDefaultConstructAssignString("B"))); NonDefaultConstructAssignString("B")));
ParamGenerator<tuple<int, NonDefaultConstructAssignString> >::iterator it = ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> >::iterator
gen.begin(); it = gen.begin();
EXPECT_EQ(0, std::get<0>(*it)); EXPECT_EQ(0, std::get<0>(*it));
EXPECT_EQ("A", std::get<1>(*it).str()); EXPECT_EQ("A", std::get<1>(*it).str());
...@@ -577,7 +528,6 @@ TEST(CombineTest, NonDefaultConstructAssign) { ...@@ -577,7 +528,6 @@ TEST(CombineTest, NonDefaultConstructAssign) {
EXPECT_TRUE(it == gen.end()); EXPECT_TRUE(it == gen.end());
} }
# endif // GTEST_HAS_COMBINE
// Tests that an generator produces correct sequence after being // Tests that an generator produces correct sequence after being
// assigned from another generator. // assigned from another generator.
...@@ -612,7 +562,7 @@ class TestGenerationEnvironment : public ::testing::Environment { ...@@ -612,7 +562,7 @@ class TestGenerationEnvironment : public ::testing::Environment {
void TearDownExecuted() { tear_down_count_++; } void TearDownExecuted() { tear_down_count_++; }
void TestBodyExecuted() { test_body_count_++; } void TestBodyExecuted() { test_body_count_++; }
virtual void TearDown() { void TearDown() override {
// If all MultipleTestGenerationTest tests have been de-selected // If all MultipleTestGenerationTest tests have been de-selected
// by the filter flag, the following checks make no sense. // by the filter flag, the following checks make no sense.
bool perform_check = false; bool perform_check = false;
...@@ -669,11 +619,11 @@ class TestGenerationTest : public TestWithParam<int> { ...@@ -669,11 +619,11 @@ class TestGenerationTest : public TestWithParam<int> {
Environment::Instance()->FixtureConstructorExecuted(); Environment::Instance()->FixtureConstructorExecuted();
current_parameter_ = GetParam(); current_parameter_ = GetParam();
} }
virtual void SetUp() { void SetUp() override {
Environment::Instance()->SetUpExecuted(); Environment::Instance()->SetUpExecuted();
EXPECT_EQ(current_parameter_, GetParam()); EXPECT_EQ(current_parameter_, GetParam());
} }
virtual void TearDown() { void TearDown() override {
Environment::Instance()->TearDownExecuted(); Environment::Instance()->TearDownExecuted();
EXPECT_EQ(current_parameter_, GetParam()); EXPECT_EQ(current_parameter_, GetParam());
} }
...@@ -1081,6 +1031,18 @@ TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { ...@@ -1081,6 +1031,18 @@ TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5)); INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5));
// Tests param generator working with Enums
enum MyEnums {
ENUM1 = 1,
ENUM2 = 3,
ENUM3 = 8,
};
class MyEnumTest : public testing::TestWithParam<MyEnums> {};
TEST_P(MyEnumTest, ChecksParamMoreThanZero) { EXPECT_GE(10, GetParam()); }
INSTANTIATE_TEST_CASE_P(MyEnumTests, MyEnumTest,
::testing::Values(ENUM1, ENUM2, 0));
int main(int argc, char **argv) { int main(int argc, char **argv) {
// Used in TestGenerationTest test case. // Used in TestGenerationTest test case.
......
...@@ -37,6 +37,7 @@ ...@@ -37,6 +37,7 @@
#endif // GTEST_OS_MAC #endif // GTEST_OS_MAC
#include <list> #include <list>
#include <memory>
#include <utility> // For std::pair and std::make_pair. #include <utility> // For std::pair and std::make_pair.
#include <vector> #include <vector>
...@@ -218,14 +219,6 @@ TEST(IteratorTraitsTest, WorksForPointerToConst) { ...@@ -218,14 +219,6 @@ TEST(IteratorTraitsTest, WorksForPointerToConst) {
IteratorTraits<const void* const*>::value_type>(); IteratorTraits<const void* const*>::value_type>();
} }
// Tests that the element_type typedef is available in scoped_ptr and refers
// to the parameter type.
TEST(ScopedPtrTest, DefinesElementType) {
StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>();
}
// FIXME: Implement THE REST of scoped_ptr tests.
TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
if (AlwaysFalse()) if (AlwaysFalse())
GTEST_CHECK_(false) << "This should never be executed; " GTEST_CHECK_(false) << "This should never be executed; "
...@@ -1095,7 +1088,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) { ...@@ -1095,7 +1088,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType; typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
const int kCycleCount = 20; const int kCycleCount = 20;
const int kThreadCount = 7; const int kThreadCount = 7;
scoped_ptr<ThreadType> counting_threads[kThreadCount]; std::unique_ptr<ThreadType> counting_threads[kThreadCount];
Notification threads_can_start; Notification threads_can_start;
// Creates and runs kThreadCount threads that increment locked_counter // Creates and runs kThreadCount threads that increment locked_counter
// kCycleCount times each. // kCycleCount times each.
......
...@@ -37,29 +37,20 @@ ...@@ -37,29 +37,20 @@
#include <string.h> #include <string.h>
#include <algorithm> #include <algorithm>
#include <deque> #include <deque>
#include <forward_list>
#include <list> #include <list>
#include <map> #include <map>
#include <set> #include <set>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "gtest/gtest-printers.h" #include "gtest/gtest-printers.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_HAS_UNORDERED_MAP_
# include <unordered_map> // NOLINT
#endif // GTEST_HAS_UNORDERED_MAP_
#if GTEST_HAS_UNORDERED_SET_
# include <unordered_set> // NOLINT
#endif // GTEST_HAS_UNORDERED_SET_
#if GTEST_HAS_STD_FORWARD_LIST_
# include <forward_list> // NOLINT
#endif // GTEST_HAS_STD_FORWARD_LIST_
// Some user-defined types for testing the universal value printer. // Some user-defined types for testing the universal value printer.
// An anonymous enum type. // An anonymous enum type.
...@@ -192,8 +183,14 @@ class PathLike { ...@@ -192,8 +183,14 @@ class PathLike {
public: public:
struct iterator { struct iterator {
typedef PathLike value_type; typedef PathLike value_type;
iterator& operator++();
PathLike& operator*();
}; };
using value_type = char;
using const_iterator = iterator;
PathLike() {} PathLike() {}
iterator begin() const { return iterator(); } iterator begin() const { return iterator(); }
...@@ -228,9 +225,7 @@ using ::testing::internal::Strings; ...@@ -228,9 +225,7 @@ using ::testing::internal::Strings;
using ::testing::internal::UniversalPrint; using ::testing::internal::UniversalPrint;
using ::testing::internal::UniversalPrinter; using ::testing::internal::UniversalPrinter;
using ::testing::internal::UniversalTersePrint; using ::testing::internal::UniversalTersePrint;
#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
using ::testing::internal::UniversalTersePrintTupleFieldsToStrings; using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
#endif
// Prints a value to a string using the universal value printer. This // Prints a value to a string using the universal value printer. This
// is a helper for testing UniversalPrinter<T>::Print() for various types. // is a helper for testing UniversalPrinter<T>::Print() for various types.
...@@ -816,7 +811,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) { ...@@ -816,7 +811,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) {
EXPECT_EQ("{ 1, 3 }", Print(non_empty)); EXPECT_EQ("{ 1, 3 }", Print(non_empty));
} }
#if GTEST_HAS_UNORDERED_MAP_
TEST(PrintStlContainerTest, OneElementHashMap) { TEST(PrintStlContainerTest, OneElementHashMap) {
::std::unordered_map<int, char> map1; ::std::unordered_map<int, char> map1;
...@@ -836,9 +830,7 @@ TEST(PrintStlContainerTest, HashMultiMap) { ...@@ -836,9 +830,7 @@ TEST(PrintStlContainerTest, HashMultiMap) {
<< " where Print(map1) returns \"" << result << "\"."; << " where Print(map1) returns \"" << result << "\".";
} }
#endif // GTEST_HAS_UNORDERED_MAP_
#if GTEST_HAS_UNORDERED_SET_
TEST(PrintStlContainerTest, HashSet) { TEST(PrintStlContainerTest, HashSet) {
::std::unordered_set<int> set1; ::std::unordered_set<int> set1;
...@@ -875,7 +867,6 @@ TEST(PrintStlContainerTest, HashMultiSet) { ...@@ -875,7 +867,6 @@ TEST(PrintStlContainerTest, HashMultiSet) {
EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
} }
#endif // GTEST_HAS_UNORDERED_SET_
TEST(PrintStlContainerTest, List) { TEST(PrintStlContainerTest, List) {
const std::string a[] = {"hello", "world"}; const std::string a[] = {"hello", "world"};
...@@ -917,14 +908,12 @@ TEST(PrintStlContainerTest, MultiSet) { ...@@ -917,14 +908,12 @@ TEST(PrintStlContainerTest, MultiSet) {
EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
} }
#if GTEST_HAS_STD_FORWARD_LIST_
TEST(PrintStlContainerTest, SinglyLinkedList) { TEST(PrintStlContainerTest, SinglyLinkedList) {
int a[] = { 9, 2, 8 }; int a[] = { 9, 2, 8 };
const std::forward_list<int> ints(a, a + 3); const std::forward_list<int> ints(a, a + 3);
EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
} }
#endif // GTEST_HAS_STD_FORWARD_LIST_
TEST(PrintStlContainerTest, Pair) { TEST(PrintStlContainerTest, Pair) {
pair<const bool, int> p(true, 5); pair<const bool, int> p(true, 5);
...@@ -991,67 +980,6 @@ TEST(PrintStlContainerTest, ConstIterator) { ...@@ -991,67 +980,6 @@ TEST(PrintStlContainerTest, ConstIterator) {
EXPECT_EQ("1-byte object <00>", Print(it)); EXPECT_EQ("1-byte object <00>", Print(it));
} }
#if GTEST_HAS_TR1_TUPLE
// Tests printing ::std::tr1::tuples.
// Tuples of various arities.
TEST(PrintTr1TupleTest, VariousSizes) {
::std::tr1::tuple<> t0;
EXPECT_EQ("()", Print(t0));
::std::tr1::tuple<int> t1(5);
EXPECT_EQ("(5)", Print(t1));
::std::tr1::tuple<char, bool> t2('a', true);
EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
::std::tr1::tuple<bool, int, int> t3(false, 2, 3);
EXPECT_EQ("(false, 2, 3)", Print(t3));
::std::tr1::tuple<bool, int, int, int> t4(false, 2, 3, 4);
EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
::std::tr1::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5));
::std::tr1::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6));
::std::tr1::tuple<bool, int, int, int, bool, int, int> t7(
false, 2, 3, 4, true, 6, 7);
EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7));
::std::tr1::tuple<bool, int, int, int, bool, int, int, bool> t8(
false, 2, 3, 4, true, 6, 7, true);
EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8));
::std::tr1::tuple<bool, int, int, int, bool, int, int, bool, int> t9(
false, 2, 3, 4, true, 6, 7, true, 9);
EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9));
const char* const str = "8";
// VC++ 2010's implementation of tuple of C++0x is deficient, requiring
// an explicit type cast of NULL to be used.
::std::tr1::tuple<bool, char, short, testing::internal::Int32, // NOLINT
testing::internal::Int64, float, double, const char*, void*,
std::string>
t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
ImplicitCast_<void*>(NULL), "10");
EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
" pointing to \"8\", NULL, \"10\")",
Print(t10));
}
// Nested tuples.
TEST(PrintTr1TupleTest, NestedTuple) {
::std::tr1::tuple< ::std::tr1::tuple<int, bool>, char> nested(
::std::tr1::make_tuple(5, true), 'a');
EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
}
#endif // GTEST_HAS_TR1_TUPLE
#if GTEST_HAS_STD_TUPLE_
// Tests printing ::std::tuples. // Tests printing ::std::tuples.
// Tuples of various arities. // Tuples of various arities.
...@@ -1071,32 +999,12 @@ TEST(PrintStdTupleTest, VariousSizes) { ...@@ -1071,32 +999,12 @@ TEST(PrintStdTupleTest, VariousSizes) {
::std::tuple<bool, int, int, int> t4(false, 2, 3, 4); ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
::std::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5));
::std::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6));
::std::tuple<bool, int, int, int, bool, int, int> t7(
false, 2, 3, 4, true, 6, 7);
EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7));
::std::tuple<bool, int, int, int, bool, int, int, bool> t8(
false, 2, 3, 4, true, 6, 7, true);
EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8));
::std::tuple<bool, int, int, int, bool, int, int, bool, int> t9(
false, 2, 3, 4, true, 6, 7, true, 9);
EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9));
const char* const str = "8"; const char* const str = "8";
// VC++ 2010's implementation of tuple of C++0x is deficient, requiring
// an explicit type cast of NULL to be used.
::std::tuple<bool, char, short, testing::internal::Int32, // NOLINT ::std::tuple<bool, char, short, testing::internal::Int32, // NOLINT
testing::internal::Int64, float, double, const char*, void*, testing::internal::Int64, float, double, const char*, void*,
std::string> std::string>
t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
ImplicitCast_<void*>(NULL), "10"); nullptr, "10");
EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
" pointing to \"8\", NULL, \"10\")", " pointing to \"8\", NULL, \"10\")",
Print(t10)); Print(t10));
...@@ -1109,8 +1017,6 @@ TEST(PrintStdTupleTest, NestedTuple) { ...@@ -1109,8 +1017,6 @@ TEST(PrintStdTupleTest, NestedTuple) {
EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
} }
#endif // GTEST_HAS_TR1_TUPLE
TEST(PrintNullptrT, Basic) { TEST(PrintNullptrT, Basic) {
EXPECT_EQ("(nullptr)", Print(nullptr)); EXPECT_EQ("(nullptr)", Print(nullptr));
} }
...@@ -1662,42 +1568,6 @@ TEST(UniversalPrintTest, WorksForCharArray) { ...@@ -1662,42 +1568,6 @@ TEST(UniversalPrintTest, WorksForCharArray) {
EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str()); EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
} }
#if GTEST_HAS_TR1_TUPLE
TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsEmptyTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings(
::std::tr1::make_tuple());
EXPECT_EQ(0u, result.size());
}
TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsOneTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings(
::std::tr1::make_tuple(1));
ASSERT_EQ(1u, result.size());
EXPECT_EQ("1", result[0]);
}
TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTwoTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings(
::std::tr1::make_tuple(1, 'a'));
ASSERT_EQ(2u, result.size());
EXPECT_EQ("1", result[0]);
EXPECT_EQ("'a' (97, 0x61)", result[1]);
}
TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTersely) {
const int n = 1;
Strings result = UniversalTersePrintTupleFieldsToStrings(
::std::tr1::tuple<const int&, const char*>(n, "a"));
ASSERT_EQ(2u, result.size());
EXPECT_EQ("1", result[0]);
EXPECT_EQ("\"a\"", result[1]);
}
#endif // GTEST_HAS_TR1_TUPLE
#if GTEST_HAS_STD_TUPLE_
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) { TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple()); Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
EXPECT_EQ(0u, result.size()); EXPECT_EQ(0u, result.size());
...@@ -1727,8 +1597,6 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) { ...@@ -1727,8 +1597,6 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
EXPECT_EQ("\"a\"", result[1]); EXPECT_EQ("\"a\"", result[1]);
} }
#endif // GTEST_HAS_STD_TUPLE_
#if GTEST_HAS_ABSL #if GTEST_HAS_ABSL
TEST(PrintOptionalTest, Basic) { TEST(PrintOptionalTest, Basic) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment