--- /dev/null
+// Copyright 2008, Google Inc.\r
+// All rights reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+//\r
+// Author: mheule@google.com (Markus Heule)\r
+//\r
+// Google C++ Testing Framework (Google Test)\r
+//\r
+// Sometimes it's desirable to build Google Test by compiling a single file.\r
+// This file serves this purpose.\r
+\r
+// This line ensures that gtest.h can be compiled on its own, even\r
+// when it's fused.\r
+#include "gtest/gtest.h"\r
+\r
+// The following lines pull in the real gtest *.cc files.\r
+// Copyright 2005, Google Inc.\r
+// All rights reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+//\r
+// Author: wan@google.com (Zhanyong Wan)\r
+//\r
+// The Google C++ Testing Framework (Google Test)\r
+\r
+// Copyright 2007, Google Inc.\r
+// All rights reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+//\r
+// Author: wan@google.com (Zhanyong Wan)\r
+//\r
+// Utilities for testing Google Test itself and code that uses Google Test\r
+// (e.g. frameworks built on top of Google Test).\r
+\r
+#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_\r
+#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_\r
+\r
+\r
+namespace testing {\r
+\r
+// This helper class can be used to mock out Google Test failure reporting\r
+// so that we can test Google Test or code that builds on Google Test.\r
+//\r
+// An object of this class appends a TestPartResult object to the\r
+// TestPartResultArray object given in the constructor whenever a Google Test\r
+// failure is reported. It can either intercept only failures that are\r
+// generated in the same thread that created this object or it can intercept\r
+// all generated failures. The scope of this mock object can be controlled with\r
+// the second argument to the two arguments constructor.\r
+class GTEST_API_ ScopedFakeTestPartResultReporter\r
+ : public TestPartResultReporterInterface {\r
+ public:\r
+ // The two possible mocking modes of this object.\r
+ enum InterceptMode {\r
+ INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.\r
+ INTERCEPT_ALL_THREADS // Intercepts all failures.\r
+ };\r
+\r
+ // The c'tor sets this object as the test part result reporter used\r
+ // by Google Test. The 'result' parameter specifies where to report the\r
+ // results. This reporter will only catch failures generated in the current\r
+ // thread. DEPRECATED\r
+ explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);\r
+\r
+ // Same as above, but you can choose the interception scope of this object.\r
+ ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,\r
+ TestPartResultArray* result);\r
+\r
+ // The d'tor restores the previous test part result reporter.\r
+ virtual ~ScopedFakeTestPartResultReporter();\r
+\r
+ // Appends the TestPartResult object to the TestPartResultArray\r
+ // received in the constructor.\r
+ //\r
+ // This method is from the TestPartResultReporterInterface\r
+ // interface.\r
+ virtual void ReportTestPartResult(const TestPartResult& result);\r
+ private:\r
+ void Init();\r
+\r
+ const InterceptMode intercept_mode_;\r
+ TestPartResultReporterInterface* old_reporter_;\r
+ TestPartResultArray* const result_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);\r
+};\r
+\r
+namespace internal {\r
+\r
+// A helper class for implementing EXPECT_FATAL_FAILURE() and\r
+// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given\r
+// TestPartResultArray contains exactly one failure that has the given\r
+// type and contains the given substring. If that's not the case, a\r
+// non-fatal failure will be generated.\r
+class GTEST_API_ SingleFailureChecker {\r
+ public:\r
+ // The constructor remembers the arguments.\r
+ SingleFailureChecker(const TestPartResultArray* results,\r
+ TestPartResult::Type type,\r
+ const string& substr);\r
+ ~SingleFailureChecker();\r
+ private:\r
+ const TestPartResultArray* const results_;\r
+ const TestPartResult::Type type_;\r
+ const string substr_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);\r
+};\r
+\r
+} // namespace internal\r
+\r
+} // namespace testing\r
+\r
+// A set of macros for testing Google Test assertions or code that's expected\r
+// to generate Google Test fatal failures. It verifies that the given\r
+// statement will cause exactly one fatal Google Test failure with 'substr'\r
+// being part of the failure message.\r
+//\r
+// There are two different versions of this macro. EXPECT_FATAL_FAILURE only\r
+// affects and considers failures generated in the current thread and\r
+// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.\r
+//\r
+// The verification of the assertion is done correctly even when the statement\r
+// throws an exception or aborts the current function.\r
+//\r
+// Known restrictions:\r
+// - 'statement' cannot reference local non-static variables or\r
+// non-static members of the current object.\r
+// - 'statement' cannot return a value.\r
+// - You cannot stream a failure message to this macro.\r
+//\r
+// Note that even though the implementations of the following two\r
+// macros are much alike, we cannot refactor them to use a common\r
+// helper macro, due to some peculiarity in how the preprocessor\r
+// works. The AcceptsMacroThatExpandsToUnprotectedComma test in\r
+// gtest_unittest.cc will fail to compile if we do that.\r
+#define EXPECT_FATAL_FAILURE(statement, substr) \\r
+ do { \\r
+ class GTestExpectFatalFailureHelper {\\r
+ public:\\r
+ static void Execute() { statement; }\\r
+ };\\r
+ ::testing::TestPartResultArray gtest_failures;\\r
+ ::testing::internal::SingleFailureChecker gtest_checker(\\r
+ >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\\r
+ {\\r
+ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\\r
+ ::testing::ScopedFakeTestPartResultReporter:: \\r
+ INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\\r
+ GTestExpectFatalFailureHelper::Execute();\\r
+ }\\r
+ } while (::testing::internal::AlwaysFalse())\r
+\r
+#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \\r
+ do { \\r
+ class GTestExpectFatalFailureHelper {\\r
+ public:\\r
+ static void Execute() { statement; }\\r
+ };\\r
+ ::testing::TestPartResultArray gtest_failures;\\r
+ ::testing::internal::SingleFailureChecker gtest_checker(\\r
+ >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\\r
+ {\\r
+ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\\r
+ ::testing::ScopedFakeTestPartResultReporter:: \\r
+ INTERCEPT_ALL_THREADS, >est_failures);\\r
+ GTestExpectFatalFailureHelper::Execute();\\r
+ }\\r
+ } while (::testing::internal::AlwaysFalse())\r
+\r
+// A macro for testing Google Test assertions or code that's expected to\r
+// generate Google Test non-fatal failures. It asserts that the given\r
+// statement will cause exactly one non-fatal Google Test failure with 'substr'\r
+// being part of the failure message.\r
+//\r
+// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only\r
+// affects and considers failures generated in the current thread and\r
+// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.\r
+//\r
+// 'statement' is allowed to reference local variables and members of\r
+// the current object.\r
+//\r
+// The verification of the assertion is done correctly even when the statement\r
+// throws an exception or aborts the current function.\r
+//\r
+// Known restrictions:\r
+// - You cannot stream a failure message to this macro.\r
+//\r
+// Note that even though the implementations of the following two\r
+// macros are much alike, we cannot refactor them to use a common\r
+// helper macro, due to some peculiarity in how the preprocessor\r
+// works. If we do that, the code won't compile when the user gives\r
+// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that\r
+// expands to code containing an unprotected comma. The\r
+// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc\r
+// catches that.\r
+//\r
+// For the same reason, we have to write\r
+// if (::testing::internal::AlwaysTrue()) { statement; }\r
+// instead of\r
+// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)\r
+// to avoid an MSVC warning on unreachable code.\r
+#define EXPECT_NONFATAL_FAILURE(statement, substr) \\r
+ do {\\r
+ ::testing::TestPartResultArray gtest_failures;\\r
+ ::testing::internal::SingleFailureChecker gtest_checker(\\r
+ >est_failures, ::testing::TestPartResult::kNonFatalFailure, \\r
+ (substr));\\r
+ {\\r
+ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\\r
+ ::testing::ScopedFakeTestPartResultReporter:: \\r
+ INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\\r
+ if (::testing::internal::AlwaysTrue()) { statement; }\\r
+ }\\r
+ } while (::testing::internal::AlwaysFalse())\r
+\r
+#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \\r
+ do {\\r
+ ::testing::TestPartResultArray gtest_failures;\\r
+ ::testing::internal::SingleFailureChecker gtest_checker(\\r
+ >est_failures, ::testing::TestPartResult::kNonFatalFailure, \\r
+ (substr));\\r
+ {\\r
+ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\\r
+ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \\r
+ >est_failures);\\r
+ if (::testing::internal::AlwaysTrue()) { statement; }\\r
+ }\\r
+ } while (::testing::internal::AlwaysFalse())\r
+\r
+#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_\r
+\r
+#include <ctype.h>\r
+#include <math.h>\r
+#include <stdarg.h>\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <time.h>\r
+#include <wchar.h>\r
+#include <wctype.h>\r
+\r
+#include <algorithm>\r
+#include <iomanip>\r
+#include <limits>\r
+#include <list>\r
+#include <map>\r
+#include <ostream> // NOLINT\r
+#include <sstream>\r
+#include <vector>\r
+\r
+#if GTEST_OS_LINUX\r
+\r
+// TODO(kenton@google.com): Use autoconf to detect availability of\r
+// gettimeofday().\r
+# define GTEST_HAS_GETTIMEOFDAY_ 1\r
+\r
+# include <fcntl.h> // NOLINT\r
+# include <limits.h> // NOLINT\r
+# include <sched.h> // NOLINT\r
+// Declares vsnprintf(). This header is not available on Windows.\r
+# include <strings.h> // NOLINT\r
+# include <sys/mman.h> // NOLINT\r
+# include <sys/time.h> // NOLINT\r
+# include <unistd.h> // NOLINT\r
+# include <string>\r
+\r
+#elif GTEST_OS_SYMBIAN\r
+# define GTEST_HAS_GETTIMEOFDAY_ 1\r
+# include <sys/time.h> // NOLINT\r
+\r
+#elif GTEST_OS_ZOS\r
+# define GTEST_HAS_GETTIMEOFDAY_ 1\r
+# include <sys/time.h> // NOLINT\r
+\r
+// On z/OS we additionally need strings.h for strcasecmp.\r
+# include <strings.h> // NOLINT\r
+\r
+#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.\r
+\r
+# include <windows.h> // NOLINT\r
+# undef min\r
+\r
+#elif GTEST_OS_WINDOWS // We are on Windows proper.\r
+\r
+# include <io.h> // NOLINT\r
+# include <sys/timeb.h> // NOLINT\r
+# include <sys/types.h> // NOLINT\r
+# include <sys/stat.h> // NOLINT\r
+\r
+# if GTEST_OS_WINDOWS_MINGW\r
+// MinGW has gettimeofday() but not _ftime64().\r
+// TODO(kenton@google.com): Use autoconf to detect availability of\r
+// gettimeofday().\r
+// TODO(kenton@google.com): There are other ways to get the time on\r
+// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW\r
+// supports these. consider using them instead.\r
+# define GTEST_HAS_GETTIMEOFDAY_ 1\r
+# include <sys/time.h> // NOLINT\r
+# endif // GTEST_OS_WINDOWS_MINGW\r
+\r
+// cpplint thinks that the header is already included, so we want to\r
+// silence it.\r
+# include <windows.h> // NOLINT\r
+# undef min\r
+\r
+#else\r
+\r
+// Assume other platforms have gettimeofday().\r
+// TODO(kenton@google.com): Use autoconf to detect availability of\r
+// gettimeofday().\r
+# define GTEST_HAS_GETTIMEOFDAY_ 1\r
+\r
+// cpplint thinks that the header is already included, so we want to\r
+// silence it.\r
+# include <sys/time.h> // NOLINT\r
+# include <unistd.h> // NOLINT\r
+\r
+#endif // GTEST_OS_LINUX\r
+\r
+#if GTEST_HAS_EXCEPTIONS\r
+# include <stdexcept>\r
+#endif\r
+\r
+#if GTEST_CAN_STREAM_RESULTS_\r
+# include <arpa/inet.h> // NOLINT\r
+# include <netdb.h> // NOLINT\r
+# include <sys/socket.h> // NOLINT\r
+# include <sys/types.h> // NOLINT\r
+#endif\r
+\r
+// Indicates that this translation unit is part of Google Test's\r
+// implementation. It must come before gtest-internal-inl.h is\r
+// included, or there will be a compiler error. This trick is to\r
+// prevent a user from accidentally including gtest-internal-inl.h in\r
+// his code.\r
+#define GTEST_IMPLEMENTATION_ 1\r
+// Copyright 2005, Google Inc.\r
+// All rights reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+// Utility functions and classes used by the Google C++ testing framework.\r
+//\r
+// Author: wan@google.com (Zhanyong Wan)\r
+//\r
+// This file contains purely Google Test's internal implementation. Please\r
+// DO NOT #INCLUDE IT IN A USER PROGRAM.\r
+\r
+#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_\r
+#define GTEST_SRC_GTEST_INTERNAL_INL_H_\r
+\r
+// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is\r
+// part of Google Test's implementation; otherwise it's undefined.\r
+#if !GTEST_IMPLEMENTATION_\r
+// If this file is included from the user's code, just say no.\r
+# error "gtest-internal-inl.h is part of Google Test's internal implementation."\r
+# error "It must not be included except by Google Test itself."\r
+#endif // GTEST_IMPLEMENTATION_\r
+\r
+#ifndef _WIN32_WCE\r
+# include <errno.h>\r
+#endif // !_WIN32_WCE\r
+#include <stddef.h>\r
+#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.\r
+#include <string.h> // For memmove.\r
+\r
+#include <algorithm>\r
+#include <string>\r
+#include <vector>\r
+\r
+\r
+#if GTEST_CAN_STREAM_RESULTS_\r
+# include <arpa/inet.h> // NOLINT\r
+# include <netdb.h> // NOLINT\r
+#endif\r
+\r
+#if GTEST_OS_WINDOWS\r
+# include <windows.h> // NOLINT\r
+#endif // GTEST_OS_WINDOWS\r
+\r
+\r
+namespace testing {\r
+\r
+// Declares the flags.\r
+//\r
+// We don't want the users to modify this flag in the code, but want\r
+// Google Test's own unit tests to be able to access it. Therefore we\r
+// declare it here as opposed to in gtest.h.\r
+GTEST_DECLARE_bool_(death_test_use_fork);\r
+\r
+namespace internal {\r
+\r
+// The value of GetTestTypeId() as seen from within the Google Test\r
+// library. This is solely for testing GetTestTypeId().\r
+GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;\r
+\r
+// Names of the flags (needed for parsing Google Test flags).\r
+const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";\r
+const char kBreakOnFailureFlag[] = "break_on_failure";\r
+const char kCatchExceptionsFlag[] = "catch_exceptions";\r
+const char kColorFlag[] = "color";\r
+const char kFilterFlag[] = "filter";\r
+const char kListTestsFlag[] = "list_tests";\r
+const char kOutputFlag[] = "output";\r
+const char kPrintTimeFlag[] = "print_time";\r
+const char kRandomSeedFlag[] = "random_seed";\r
+const char kRepeatFlag[] = "repeat";\r
+const char kShuffleFlag[] = "shuffle";\r
+const char kStackTraceDepthFlag[] = "stack_trace_depth";\r
+const char kStreamResultToFlag[] = "stream_result_to";\r
+const char kThrowOnFailureFlag[] = "throw_on_failure";\r
+const char kFlagfileFlag[] = "flagfile";\r
+\r
+// A valid random seed must be in [1, kMaxRandomSeed].\r
+const int kMaxRandomSeed = 99999;\r
+\r
+// g_help_flag is true iff the --help flag or an equivalent form is\r
+// specified on the command line.\r
+GTEST_API_ extern bool g_help_flag;\r
+\r
+// Returns the current time in milliseconds.\r
+GTEST_API_ TimeInMillis GetTimeInMillis();\r
+\r
+// Returns true iff Google Test should use colors in the output.\r
+GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);\r
+\r
+// Formats the given time in milliseconds as seconds.\r
+GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);\r
+\r
+// Converts the given time in milliseconds to a date string in the ISO 8601\r
+// format, without the timezone information. N.B.: due to the use the\r
+// non-reentrant localtime() function, this function is not thread safe. Do\r
+// not use it in any code that can be called from multiple threads.\r
+GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);\r
+\r
+// Parses a string for an Int32 flag, in the form of "--flag=value".\r
+//\r
+// On success, stores the value of the flag in *value, and returns\r
+// true. On failure, returns false without changing *value.\r
+GTEST_API_ bool ParseInt32Flag(\r
+ const char* str, const char* flag, Int32* value);\r
+\r
+// Returns a random seed in range [1, kMaxRandomSeed] based on the\r
+// given --gtest_random_seed flag value.\r
+inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {\r
+ const unsigned int raw_seed = (random_seed_flag == 0) ?\r
+ static_cast<unsigned int>(GetTimeInMillis()) :\r
+ static_cast<unsigned int>(random_seed_flag);\r
+\r
+ // Normalizes the actual seed to range [1, kMaxRandomSeed] such that\r
+ // it's easy to type.\r
+ const int normalized_seed =\r
+ static_cast<int>((raw_seed - 1U) %\r
+ static_cast<unsigned int>(kMaxRandomSeed)) + 1;\r
+ return normalized_seed;\r
+}\r
+\r
+// Returns the first valid random seed after 'seed'. The behavior is\r
+// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is\r
+// considered to be 1.\r
+inline int GetNextRandomSeed(int seed) {\r
+ GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)\r
+ << "Invalid random seed " << seed << " - must be in [1, "\r
+ << kMaxRandomSeed << "].";\r
+ const int next_seed = seed + 1;\r
+ return (next_seed > kMaxRandomSeed) ? 1 : next_seed;\r
+}\r
+\r
+// This class saves the values of all Google Test flags in its c'tor, and\r
+// restores them in its d'tor.\r
+class GTestFlagSaver {\r
+ public:\r
+ // The c'tor.\r
+ GTestFlagSaver() {\r
+ also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);\r
+ break_on_failure_ = GTEST_FLAG(break_on_failure);\r
+ catch_exceptions_ = GTEST_FLAG(catch_exceptions);\r
+ color_ = GTEST_FLAG(color);\r
+ death_test_style_ = GTEST_FLAG(death_test_style);\r
+ death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);\r
+ filter_ = GTEST_FLAG(filter);\r
+ internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);\r
+ list_tests_ = GTEST_FLAG(list_tests);\r
+ output_ = GTEST_FLAG(output);\r
+ print_time_ = GTEST_FLAG(print_time);\r
+ random_seed_ = GTEST_FLAG(random_seed);\r
+ repeat_ = GTEST_FLAG(repeat);\r
+ shuffle_ = GTEST_FLAG(shuffle);\r
+ stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);\r
+ stream_result_to_ = GTEST_FLAG(stream_result_to);\r
+ throw_on_failure_ = GTEST_FLAG(throw_on_failure);\r
+ }\r
+\r
+ // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.\r
+ ~GTestFlagSaver() {\r
+ GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;\r
+ GTEST_FLAG(break_on_failure) = break_on_failure_;\r
+ GTEST_FLAG(catch_exceptions) = catch_exceptions_;\r
+ GTEST_FLAG(color) = color_;\r
+ GTEST_FLAG(death_test_style) = death_test_style_;\r
+ GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;\r
+ GTEST_FLAG(filter) = filter_;\r
+ GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;\r
+ GTEST_FLAG(list_tests) = list_tests_;\r
+ GTEST_FLAG(output) = output_;\r
+ GTEST_FLAG(print_time) = print_time_;\r
+ GTEST_FLAG(random_seed) = random_seed_;\r
+ GTEST_FLAG(repeat) = repeat_;\r
+ GTEST_FLAG(shuffle) = shuffle_;\r
+ GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;\r
+ GTEST_FLAG(stream_result_to) = stream_result_to_;\r
+ GTEST_FLAG(throw_on_failure) = throw_on_failure_;\r
+ }\r
+\r
+ private:\r
+ // Fields for saving the original values of flags.\r
+ bool also_run_disabled_tests_;\r
+ bool break_on_failure_;\r
+ bool catch_exceptions_;\r
+ std::string color_;\r
+ std::string death_test_style_;\r
+ bool death_test_use_fork_;\r
+ std::string filter_;\r
+ std::string internal_run_death_test_;\r
+ bool list_tests_;\r
+ std::string output_;\r
+ bool print_time_;\r
+ internal::Int32 random_seed_;\r
+ internal::Int32 repeat_;\r
+ bool shuffle_;\r
+ internal::Int32 stack_trace_depth_;\r
+ std::string stream_result_to_;\r
+ bool throw_on_failure_;\r
+} GTEST_ATTRIBUTE_UNUSED_;\r
+\r
+// Converts a Unicode code point to a narrow string in UTF-8 encoding.\r
+// code_point parameter is of type UInt32 because wchar_t may not be\r
+// wide enough to contain a code point.\r
+// If the code_point is not a valid Unicode code point\r
+// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted\r
+// to "(Invalid Unicode 0xXXXXXXXX)".\r
+GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);\r
+\r
+// Converts a wide string to a narrow string in UTF-8 encoding.\r
+// The wide string is assumed to have the following encoding:\r
+// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)\r
+// UTF-32 if sizeof(wchar_t) == 4 (on Linux)\r
+// Parameter str points to a null-terminated wide string.\r
+// Parameter num_chars may additionally limit the number\r
+// of wchar_t characters processed. -1 is used when the entire string\r
+// should be processed.\r
+// If the string contains code points that are not valid Unicode code points\r
+// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output\r
+// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding\r
+// and contains invalid UTF-16 surrogate pairs, values in those pairs\r
+// will be encoded as individual Unicode characters from Basic Normal Plane.\r
+GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);\r
+\r
+// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file\r
+// if the variable is present. If a file already exists at this location, this\r
+// function will write over it. If the variable is present, but the file cannot\r
+// be created, prints an error and exits.\r
+void WriteToShardStatusFileIfNeeded();\r
+\r
+// Checks whether sharding is enabled by examining the relevant\r
+// environment variable values. If the variables are present,\r
+// but inconsistent (e.g., shard_index >= total_shards), prints\r
+// an error and exits. If in_subprocess_for_death_test, sharding is\r
+// disabled because it must only be applied to the original test\r
+// process. Otherwise, we could filter out death tests we intended to execute.\r
+GTEST_API_ bool ShouldShard(const char* total_shards_str,\r
+ const char* shard_index_str,\r
+ bool in_subprocess_for_death_test);\r
+\r
+// Parses the environment variable var as an Int32. If it is unset,\r
+// returns default_val. If it is not an Int32, prints an error and\r
+// and aborts.\r
+GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);\r
+\r
+// Given the total number of shards, the shard index, and the test id,\r
+// returns true iff the test should be run on this shard. The test id is\r
+// some arbitrary but unique non-negative integer assigned to each test\r
+// method. Assumes that 0 <= shard_index < total_shards.\r
+GTEST_API_ bool ShouldRunTestOnShard(\r
+ int total_shards, int shard_index, int test_id);\r
+\r
+// STL container utilities.\r
+\r
+// Returns the number of elements in the given container that satisfy\r
+// the given predicate.\r
+template <class Container, typename Predicate>\r
+inline int CountIf(const Container& c, Predicate predicate) {\r
+ // Implemented as an explicit loop since std::count_if() in libCstd on\r
+ // Solaris has a non-standard signature.\r
+ int count = 0;\r
+ for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {\r
+ if (predicate(*it))\r
+ ++count;\r
+ }\r
+ return count;\r
+}\r
+\r
+// Applies a function/functor to each element in the container.\r
+template <class Container, typename Functor>\r
+void ForEach(const Container& c, Functor functor) {\r
+ std::for_each(c.begin(), c.end(), functor);\r
+}\r
+\r
+// Returns the i-th element of the vector, or default_value if i is not\r
+// in range [0, v.size()).\r
+template <typename E>\r
+inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {\r
+ return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];\r
+}\r
+\r
+// Performs an in-place shuffle of a range of the vector's elements.\r
+// 'begin' and 'end' are element indices as an STL-style range;\r
+// i.e. [begin, end) are shuffled, where 'end' == size() means to\r
+// shuffle to the end of the vector.\r
+template <typename E>\r
+void ShuffleRange(internal::Random* random, int begin, int end,\r
+ std::vector<E>* v) {\r
+ const int size = static_cast<int>(v->size());\r
+ GTEST_CHECK_(0 <= begin && begin <= size)\r
+ << "Invalid shuffle range start " << begin << ": must be in range [0, "\r
+ << size << "].";\r
+ GTEST_CHECK_(begin <= end && end <= size)\r
+ << "Invalid shuffle range finish " << end << ": must be in range ["\r
+ << begin << ", " << size << "].";\r
+\r
+ // Fisher-Yates shuffle, from\r
+ // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\r
+ for (int range_width = end - begin; range_width >= 2; range_width--) {\r
+ const int last_in_range = begin + range_width - 1;\r
+ const int selected = begin + random->Generate(range_width);\r
+ std::swap((*v)[selected], (*v)[last_in_range]);\r
+ }\r
+}\r
+\r
+// Performs an in-place shuffle of the vector's elements.\r
+template <typename E>\r
+inline void Shuffle(internal::Random* random, std::vector<E>* v) {\r
+ ShuffleRange(random, 0, static_cast<int>(v->size()), v);\r
+}\r
+\r
+// A function for deleting an object. Handy for being used as a\r
+// functor.\r
+template <typename T>\r
+static void Delete(T* x) {\r
+ delete x;\r
+}\r
+\r
+// A predicate that checks the key of a TestProperty against a known key.\r
+//\r
+// TestPropertyKeyIs is copyable.\r
+class TestPropertyKeyIs {\r
+ public:\r
+ // Constructor.\r
+ //\r
+ // TestPropertyKeyIs has NO default constructor.\r
+ explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}\r
+\r
+ // Returns true iff the test name of test property matches on key_.\r
+ bool operator()(const TestProperty& test_property) const {\r
+ return test_property.key() == key_;\r
+ }\r
+\r
+ private:\r
+ std::string key_;\r
+};\r
+\r
+// Class UnitTestOptions.\r
+//\r
+// This class contains functions for processing options the user\r
+// specifies when running the tests. It has only static members.\r
+//\r
+// In most cases, the user can specify an option using either an\r
+// environment variable or a command line flag. E.g. you can set the\r
+// test filter using either GTEST_FILTER or --gtest_filter. If both\r
+// the variable and the flag are present, the latter overrides the\r
+// former.\r
+class GTEST_API_ UnitTestOptions {\r
+ public:\r
+ // Functions for processing the gtest_output flag.\r
+\r
+ // Returns the output format, or "" for normal printed output.\r
+ static std::string GetOutputFormat();\r
+\r
+ // Returns the absolute path of the requested output file, or the\r
+ // default (test_detail.xml in the original working directory) if\r
+ // none was explicitly specified.\r
+ static std::string GetAbsolutePathToOutputFile();\r
+\r
+ // Functions for processing the gtest_filter flag.\r
+\r
+ // Returns true iff the wildcard pattern matches the string. The\r
+ // first ':' or '\0' character in pattern marks the end of it.\r
+ //\r
+ // This recursive algorithm isn't very efficient, but is clear and\r
+ // works well enough for matching test names, which are short.\r
+ static bool PatternMatchesString(const char *pattern, const char *str);\r
+\r
+ // Returns true iff the user-specified filter matches the test case\r
+ // name and the test name.\r
+ static bool FilterMatchesTest(const std::string &test_case_name,\r
+ const std::string &test_name);\r
+\r
+#if GTEST_OS_WINDOWS\r
+ // Function for supporting the gtest_catch_exception flag.\r
+\r
+ // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the\r
+ // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.\r
+ // This function is useful as an __except condition.\r
+ static int GTestShouldProcessSEH(DWORD exception_code);\r
+#endif // GTEST_OS_WINDOWS\r
+\r
+ // Returns true if "name" matches the ':' separated list of glob-style\r
+ // filters in "filter".\r
+ static bool MatchesFilter(const std::string& name, const char* filter);\r
+};\r
+\r
+// Returns the current application's name, removing directory path if that\r
+// is present. Used by UnitTestOptions::GetOutputFile.\r
+GTEST_API_ FilePath GetCurrentExecutableName();\r
+\r
+// The role interface for getting the OS stack trace as a string.\r
+class OsStackTraceGetterInterface {\r
+ public:\r
+ OsStackTraceGetterInterface() {}\r
+ virtual ~OsStackTraceGetterInterface() {}\r
+\r
+ // Returns the current OS stack trace as an std::string. Parameters:\r
+ //\r
+ // max_depth - the maximum number of stack frames to be included\r
+ // in the trace.\r
+ // skip_count - the number of top frames to be skipped; doesn't count\r
+ // against max_depth.\r
+ virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;\r
+\r
+ // UponLeavingGTest() should be called immediately before Google Test calls\r
+ // user code. It saves some information about the current stack that\r
+ // CurrentStackTrace() will use to find and hide Google Test stack frames.\r
+ virtual void UponLeavingGTest() = 0;\r
+\r
+ // This string is inserted in place of stack frames that are part of\r
+ // Google Test's implementation.\r
+ static const char* const kElidedFramesMarker;\r
+\r
+ private:\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);\r
+};\r
+\r
+// A working implementation of the OsStackTraceGetterInterface interface.\r
+class OsStackTraceGetter : public OsStackTraceGetterInterface {\r
+ public:\r
+ OsStackTraceGetter() {}\r
+\r
+ virtual string CurrentStackTrace(int max_depth, int skip_count);\r
+ virtual void UponLeavingGTest();\r
+\r
+ private:\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);\r
+};\r
+\r
+// Information about a Google Test trace point.\r
+struct TraceInfo {\r
+ const char* file;\r
+ int line;\r
+ std::string message;\r
+};\r
+\r
+// This is the default global test part result reporter used in UnitTestImpl.\r
+// This class should only be used by UnitTestImpl.\r
+class DefaultGlobalTestPartResultReporter\r
+ : public TestPartResultReporterInterface {\r
+ public:\r
+ explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);\r
+ // Implements the TestPartResultReporterInterface. Reports the test part\r
+ // result in the current test.\r
+ virtual void ReportTestPartResult(const TestPartResult& result);\r
+\r
+ private:\r
+ UnitTestImpl* const unit_test_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);\r
+};\r
+\r
+// This is the default per thread test part result reporter used in\r
+// UnitTestImpl. This class should only be used by UnitTestImpl.\r
+class DefaultPerThreadTestPartResultReporter\r
+ : public TestPartResultReporterInterface {\r
+ public:\r
+ explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);\r
+ // Implements the TestPartResultReporterInterface. The implementation just\r
+ // delegates to the current global test part result reporter of *unit_test_.\r
+ virtual void ReportTestPartResult(const TestPartResult& result);\r
+\r
+ private:\r
+ UnitTestImpl* const unit_test_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);\r
+};\r
+\r
+// The private implementation of the UnitTest class. We don't protect\r
+// the methods under a mutex, as this class is not accessible by a\r
+// user and the UnitTest class that delegates work to this class does\r
+// proper locking.\r
+class GTEST_API_ UnitTestImpl {\r
+ public:\r
+ explicit UnitTestImpl(UnitTest* parent);\r
+ virtual ~UnitTestImpl();\r
+\r
+ // There are two different ways to register your own TestPartResultReporter.\r
+ // You can register your own repoter to listen either only for test results\r
+ // from the current thread or for results from all threads.\r
+ // By default, each per-thread test result repoter just passes a new\r
+ // TestPartResult to the global test result reporter, which registers the\r
+ // test part result for the currently running test.\r
+\r
+ // Returns the global test part result reporter.\r
+ TestPartResultReporterInterface* GetGlobalTestPartResultReporter();\r
+\r
+ // Sets the global test part result reporter.\r
+ void SetGlobalTestPartResultReporter(\r
+ TestPartResultReporterInterface* reporter);\r
+\r
+ // Returns the test part result reporter for the current thread.\r
+ TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();\r
+\r
+ // Sets the test part result reporter for the current thread.\r
+ void SetTestPartResultReporterForCurrentThread(\r
+ TestPartResultReporterInterface* reporter);\r
+\r
+ // Gets the number of successful test cases.\r
+ int successful_test_case_count() const;\r
+\r
+ // Gets the number of failed test cases.\r
+ int failed_test_case_count() const;\r
+\r
+ // Gets the number of all test cases.\r
+ int total_test_case_count() const;\r
+\r
+ // Gets the number of all test cases that contain at least one test\r
+ // that should run.\r
+ int test_case_to_run_count() const;\r
+\r
+ // Gets the number of successful tests.\r
+ int successful_test_count() const;\r
+\r
+ // Gets the number of failed tests.\r
+ int failed_test_count() const;\r
+\r
+ // Gets the number of disabled tests that will be reported in the XML report.\r
+ int reportable_disabled_test_count() const;\r
+\r
+ // Gets the number of disabled tests.\r
+ int disabled_test_count() const;\r
+\r
+ // Gets the number of tests to be printed in the XML report.\r
+ int reportable_test_count() const;\r
+\r
+ // Gets the number of all tests.\r
+ int total_test_count() const;\r
+\r
+ // Gets the number of tests that should run.\r
+ int test_to_run_count() const;\r
+\r
+ // Gets the time of the test program start, in ms from the start of the\r
+ // UNIX epoch.\r
+ TimeInMillis start_timestamp() const { return start_timestamp_; }\r
+\r
+ // Gets the elapsed time, in milliseconds.\r
+ TimeInMillis elapsed_time() const { return elapsed_time_; }\r
+\r
+ // Returns true iff the unit test passed (i.e. all test cases passed).\r
+ bool Passed() const { return !Failed(); }\r
+\r
+ // Returns true iff the unit test failed (i.e. some test case failed\r
+ // or something outside of all tests failed).\r
+ bool Failed() const {\r
+ return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();\r
+ }\r
+\r
+ // Gets the i-th test case among all the test cases. i can range from 0 to\r
+ // total_test_case_count() - 1. If i is not in that range, returns NULL.\r
+ const TestCase* GetTestCase(int i) const {\r
+ const int index = GetElementOr(test_case_indices_, i, -1);\r
+ return index < 0 ? NULL : test_cases_[i];\r
+ }\r
+\r
+ // Gets the i-th test case among all the test cases. i can range from 0 to\r
+ // total_test_case_count() - 1. If i is not in that range, returns NULL.\r
+ TestCase* GetMutableTestCase(int i) {\r
+ const int index = GetElementOr(test_case_indices_, i, -1);\r
+ return index < 0 ? NULL : test_cases_[index];\r
+ }\r
+\r
+ // Provides access to the event listener list.\r
+ TestEventListeners* listeners() { return &listeners_; }\r
+\r
+ // Returns the TestResult for the test that's currently running, or\r
+ // the TestResult for the ad hoc test if no test is running.\r
+ TestResult* current_test_result();\r
+\r
+ // Returns the TestResult for the ad hoc test.\r
+ const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }\r
+\r
+ // Sets the OS stack trace getter.\r
+ //\r
+ // Does nothing if the input and the current OS stack trace getter\r
+ // are the same; otherwise, deletes the old getter and makes the\r
+ // input the current getter.\r
+ void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);\r
+\r
+ // Returns the current OS stack trace getter if it is not NULL;\r
+ // otherwise, creates an OsStackTraceGetter, makes it the current\r
+ // getter, and returns it.\r
+ OsStackTraceGetterInterface* os_stack_trace_getter();\r
+\r
+ // Returns the current OS stack trace as an std::string.\r
+ //\r
+ // The maximum number of stack frames to be included is specified by\r
+ // the gtest_stack_trace_depth flag. The skip_count parameter\r
+ // specifies the number of top frames to be skipped, which doesn't\r
+ // count against the number of frames to be included.\r
+ //\r
+ // For example, if Foo() calls Bar(), which in turn calls\r
+ // CurrentOsStackTraceExceptTop(1), Foo() will be included in the\r
+ // trace but Bar() and CurrentOsStackTraceExceptTop() won't.\r
+ std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;\r
+\r
+ // Finds and returns a TestCase with the given name. If one doesn't\r
+ // exist, creates one and returns it.\r
+ //\r
+ // Arguments:\r
+ //\r
+ // test_case_name: name of the test case\r
+ // type_param: the name of the test's type parameter, or NULL if\r
+ // this is not a typed or a type-parameterized test.\r
+ // set_up_tc: pointer to the function that sets up the test case\r
+ // tear_down_tc: pointer to the function that tears down the test case\r
+ TestCase* GetTestCase(const char* test_case_name,\r
+ const char* type_param,\r
+ Test::SetUpTestCaseFunc set_up_tc,\r
+ Test::TearDownTestCaseFunc tear_down_tc);\r
+\r
+ // Adds a TestInfo to the unit test.\r
+ //\r
+ // Arguments:\r
+ //\r
+ // set_up_tc: pointer to the function that sets up the test case\r
+ // tear_down_tc: pointer to the function that tears down the test case\r
+ // test_info: the TestInfo object\r
+ void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,\r
+ Test::TearDownTestCaseFunc tear_down_tc,\r
+ TestInfo* test_info) {\r
+ // In order to support thread-safe death tests, we need to\r
+ // remember the original working directory when the test program\r
+ // was first invoked. We cannot do this in RUN_ALL_TESTS(), as\r
+ // the user may have changed the current directory before calling\r
+ // RUN_ALL_TESTS(). Therefore we capture the current directory in\r
+ // AddTestInfo(), which is called to register a TEST or TEST_F\r
+ // before main() is reached.\r
+ if (original_working_dir_.IsEmpty()) {\r
+ original_working_dir_.Set(FilePath::GetCurrentDir());\r
+ GTEST_CHECK_(!original_working_dir_.IsEmpty())\r
+ << "Failed to get the current working directory.";\r
+ }\r
+\r
+ GetTestCase(test_info->test_case_name(),\r
+ test_info->type_param(),\r
+ set_up_tc,\r
+ tear_down_tc)->AddTestInfo(test_info);\r
+ }\r
+\r
+#if GTEST_HAS_PARAM_TEST\r
+ // Returns ParameterizedTestCaseRegistry object used to keep track of\r
+ // value-parameterized tests and instantiate and register them.\r
+ internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {\r
+ return parameterized_test_registry_;\r
+ }\r
+#endif // GTEST_HAS_PARAM_TEST\r
+\r
+ // Sets the TestCase object for the test that's currently running.\r
+ void set_current_test_case(TestCase* a_current_test_case) {\r
+ current_test_case_ = a_current_test_case;\r
+ }\r
+\r
+ // Sets the TestInfo object for the test that's currently running. If\r
+ // current_test_info is NULL, the assertion results will be stored in\r
+ // ad_hoc_test_result_.\r
+ void set_current_test_info(TestInfo* a_current_test_info) {\r
+ current_test_info_ = a_current_test_info;\r
+ }\r
+\r
+ // Registers all parameterized tests defined using TEST_P and\r
+ // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter\r
+ // combination. This method can be called more then once; it has guards\r
+ // protecting from registering the tests more then once. If\r
+ // value-parameterized tests are disabled, RegisterParameterizedTests is\r
+ // present but does nothing.\r
+ void RegisterParameterizedTests();\r
+\r
+ // Runs all tests in this UnitTest object, prints the result, and\r
+ // returns true if all tests are successful. If any exception is\r
+ // thrown during a test, this test is considered to be failed, but\r
+ // the rest of the tests will still be run.\r
+ bool RunAllTests();\r
+\r
+ // Clears the results of all tests, except the ad hoc tests.\r
+ void ClearNonAdHocTestResult() {\r
+ ForEach(test_cases_, TestCase::ClearTestCaseResult);\r
+ }\r
+\r
+ // Clears the results of ad-hoc test assertions.\r
+ void ClearAdHocTestResult() {\r
+ ad_hoc_test_result_.Clear();\r
+ }\r
+\r
+ // Adds a TestProperty to the current TestResult object when invoked in a\r
+ // context of a test or a test case, or to the global property set. If the\r
+ // result already contains a property with the same key, the value will be\r
+ // updated.\r
+ void RecordProperty(const TestProperty& test_property);\r
+\r
+ enum ReactionToSharding {\r
+ HONOR_SHARDING_PROTOCOL,\r
+ IGNORE_SHARDING_PROTOCOL\r
+ };\r
+\r
+ // Matches the full name of each test against the user-specified\r
+ // filter to decide whether the test should run, then records the\r
+ // result in each TestCase and TestInfo object.\r
+ // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests\r
+ // based on sharding variables in the environment.\r
+ // Returns the number of tests that should run.\r
+ int FilterTests(ReactionToSharding shard_tests);\r
+\r
+ // Prints the names of the tests matching the user-specified filter flag.\r
+ void ListTestsMatchingFilter();\r
+\r
+ const TestCase* current_test_case() const { return current_test_case_; }\r
+ TestInfo* current_test_info() { return current_test_info_; }\r
+ const TestInfo* current_test_info() const { return current_test_info_; }\r
+\r
+ // Returns the vector of environments that need to be set-up/torn-down\r
+ // before/after the tests are run.\r
+ std::vector<Environment*>& environments() { return environments_; }\r
+\r
+ // Getters for the per-thread Google Test trace stack.\r
+ std::vector<TraceInfo>& gtest_trace_stack() {\r
+ return *(gtest_trace_stack_.pointer());\r
+ }\r
+ const std::vector<TraceInfo>& gtest_trace_stack() const {\r
+ return gtest_trace_stack_.get();\r
+ }\r
+\r
+#if GTEST_HAS_DEATH_TEST\r
+ void InitDeathTestSubprocessControlInfo() {\r
+ internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());\r
+ }\r
+ // Returns a pointer to the parsed --gtest_internal_run_death_test\r
+ // flag, or NULL if that flag was not specified.\r
+ // This information is useful only in a death test child process.\r
+ // Must not be called before a call to InitGoogleTest.\r
+ const InternalRunDeathTestFlag* internal_run_death_test_flag() const {\r
+ return internal_run_death_test_flag_.get();\r
+ }\r
+\r
+ // Returns a pointer to the current death test factory.\r
+ internal::DeathTestFactory* death_test_factory() {\r
+ return death_test_factory_.get();\r
+ }\r
+\r
+ void SuppressTestEventsIfInSubprocess();\r
+\r
+ friend class ReplaceDeathTestFactory;\r
+#endif // GTEST_HAS_DEATH_TEST\r
+\r
+ // Initializes the event listener performing XML output as specified by\r
+ // UnitTestOptions. Must not be called before InitGoogleTest.\r
+ void ConfigureXmlOutput();\r
+\r
+#if GTEST_CAN_STREAM_RESULTS_\r
+ // Initializes the event listener for streaming test results to a socket.\r
+ // Must not be called before InitGoogleTest.\r
+ void ConfigureStreamingOutput();\r
+#endif\r
+\r
+ // Performs initialization dependent upon flag values obtained in\r
+ // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to\r
+ // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest\r
+ // this function is also called from RunAllTests. Since this function can be\r
+ // called more than once, it has to be idempotent.\r
+ void PostFlagParsingInit();\r
+\r
+ // Gets the random seed used at the start of the current test iteration.\r
+ int random_seed() const { return random_seed_; }\r
+\r
+ // Gets the random number generator.\r
+ internal::Random* random() { return &random_; }\r
+\r
+ // Shuffles all test cases, and the tests within each test case,\r
+ // making sure that death tests are still run first.\r
+ void ShuffleTests();\r
+\r
+ // Restores the test cases and tests to their order before the first shuffle.\r
+ void UnshuffleTests();\r
+\r
+ // Returns the value of GTEST_FLAG(catch_exceptions) at the moment\r
+ // UnitTest::Run() starts.\r
+ bool catch_exceptions() const { return catch_exceptions_; }\r
+\r
+ private:\r
+ friend class ::testing::UnitTest;\r
+\r
+ // Used by UnitTest::Run() to capture the state of\r
+ // GTEST_FLAG(catch_exceptions) at the moment it starts.\r
+ void set_catch_exceptions(bool value) { catch_exceptions_ = value; }\r
+\r
+ // The UnitTest object that owns this implementation object.\r
+ UnitTest* const parent_;\r
+\r
+ // The working directory when the first TEST() or TEST_F() was\r
+ // executed.\r
+ internal::FilePath original_working_dir_;\r
+\r
+ // The default test part result reporters.\r
+ DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;\r
+ DefaultPerThreadTestPartResultReporter\r
+ default_per_thread_test_part_result_reporter_;\r
+\r
+ // Points to (but doesn't own) the global test part result reporter.\r
+ TestPartResultReporterInterface* global_test_part_result_repoter_;\r
+\r
+ // Protects read and write access to global_test_part_result_reporter_.\r
+ internal::Mutex global_test_part_result_reporter_mutex_;\r
+\r
+ // Points to (but doesn't own) the per-thread test part result reporter.\r
+ internal::ThreadLocal<TestPartResultReporterInterface*>\r
+ per_thread_test_part_result_reporter_;\r
+\r
+ // The vector of environments that need to be set-up/torn-down\r
+ // before/after the tests are run.\r
+ std::vector<Environment*> environments_;\r
+\r
+ // The vector of TestCases in their original order. It owns the\r
+ // elements in the vector.\r
+ std::vector<TestCase*> test_cases_;\r
+\r
+ // Provides a level of indirection for the test case list to allow\r
+ // easy shuffling and restoring the test case order. The i-th\r
+ // element of this vector is the index of the i-th test case in the\r
+ // shuffled order.\r
+ std::vector<int> test_case_indices_;\r
+\r
+#if GTEST_HAS_PARAM_TEST\r
+ // ParameterizedTestRegistry object used to register value-parameterized\r
+ // tests.\r
+ internal::ParameterizedTestCaseRegistry parameterized_test_registry_;\r
+\r
+ // Indicates whether RegisterParameterizedTests() has been called already.\r
+ bool parameterized_tests_registered_;\r
+#endif // GTEST_HAS_PARAM_TEST\r
+\r
+ // Index of the last death test case registered. Initially -1.\r
+ int last_death_test_case_;\r
+\r
+ // This points to the TestCase for the currently running test. It\r
+ // changes as Google Test goes through one test case after another.\r
+ // When no test is running, this is set to NULL and Google Test\r
+ // stores assertion results in ad_hoc_test_result_. Initially NULL.\r
+ TestCase* current_test_case_;\r
+\r
+ // This points to the TestInfo for the currently running test. It\r
+ // changes as Google Test goes through one test after another. When\r
+ // no test is running, this is set to NULL and Google Test stores\r
+ // assertion results in ad_hoc_test_result_. Initially NULL.\r
+ TestInfo* current_test_info_;\r
+\r
+ // Normally, a user only writes assertions inside a TEST or TEST_F,\r
+ // or inside a function called by a TEST or TEST_F. Since Google\r
+ // Test keeps track of which test is current running, it can\r
+ // associate such an assertion with the test it belongs to.\r
+ //\r
+ // If an assertion is encountered when no TEST or TEST_F is running,\r
+ // Google Test attributes the assertion result to an imaginary "ad hoc"\r
+ // test, and records the result in ad_hoc_test_result_.\r
+ TestResult ad_hoc_test_result_;\r
+\r
+ // The list of event listeners that can be used to track events inside\r
+ // Google Test.\r
+ TestEventListeners listeners_;\r
+\r
+ // The OS stack trace getter. Will be deleted when the UnitTest\r
+ // object is destructed. By default, an OsStackTraceGetter is used,\r
+ // but the user can set this field to use a custom getter if that is\r
+ // desired.\r
+ OsStackTraceGetterInterface* os_stack_trace_getter_;\r
+\r
+ // True iff PostFlagParsingInit() has been called.\r
+ bool post_flag_parse_init_performed_;\r
+\r
+ // The random number seed used at the beginning of the test run.\r
+ int random_seed_;\r
+\r
+ // Our random number generator.\r
+ internal::Random random_;\r
+\r
+ // The time of the test program start, in ms from the start of the\r
+ // UNIX epoch.\r
+ TimeInMillis start_timestamp_;\r
+\r
+ // How long the test took to run, in milliseconds.\r
+ TimeInMillis elapsed_time_;\r
+\r
+#if GTEST_HAS_DEATH_TEST\r
+ // The decomposed components of the gtest_internal_run_death_test flag,\r
+ // parsed when RUN_ALL_TESTS is called.\r
+ internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;\r
+ internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;\r
+#endif // GTEST_HAS_DEATH_TEST\r
+\r
+ // A per-thread stack of traces created by the SCOPED_TRACE() macro.\r
+ internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;\r
+\r
+ // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()\r
+ // starts.\r
+ bool catch_exceptions_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);\r
+}; // class UnitTestImpl\r
+\r
+// Convenience function for accessing the global UnitTest\r
+// implementation object.\r
+inline UnitTestImpl* GetUnitTestImpl() {\r
+ return UnitTest::GetInstance()->impl();\r
+}\r
+\r
+#if GTEST_USES_SIMPLE_RE\r
+\r
+// Internal helper functions for implementing the simple regular\r
+// expression matcher.\r
+GTEST_API_ bool IsInSet(char ch, const char* str);\r
+GTEST_API_ bool IsAsciiDigit(char ch);\r
+GTEST_API_ bool IsAsciiPunct(char ch);\r
+GTEST_API_ bool IsRepeat(char ch);\r
+GTEST_API_ bool IsAsciiWhiteSpace(char ch);\r
+GTEST_API_ bool IsAsciiWordChar(char ch);\r
+GTEST_API_ bool IsValidEscape(char ch);\r
+GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);\r
+GTEST_API_ bool ValidateRegex(const char* regex);\r
+GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);\r
+GTEST_API_ bool MatchRepetitionAndRegexAtHead(\r
+ bool escaped, char ch, char repeat, const char* regex, const char* str);\r
+GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);\r
+\r
+#endif // GTEST_USES_SIMPLE_RE\r
+\r
+// Parses the command line for Google Test flags, without initializing\r
+// other parts of Google Test.\r
+GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);\r
+GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);\r
+\r
+#if GTEST_HAS_DEATH_TEST\r
+\r
+// Returns the message describing the last system error, regardless of the\r
+// platform.\r
+GTEST_API_ std::string GetLastErrnoDescription();\r
+\r
+// Attempts to parse a string into a positive integer pointed to by the\r
+// number parameter. Returns true if that is possible.\r
+// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use\r
+// it here.\r
+template <typename Integer>\r
+bool ParseNaturalNumber(const ::std::string& str, Integer* number) {\r
+ // Fail fast if the given string does not begin with a digit;\r
+ // this bypasses strtoXXX's "optional leading whitespace and plus\r
+ // or minus sign" semantics, which are undesirable here.\r
+ if (str.empty() || !IsDigit(str[0])) {\r
+ return false;\r
+ }\r
+ errno = 0;\r
+\r
+ char* end;\r
+ // BiggestConvertible is the largest integer type that system-provided\r
+ // string-to-number conversion routines can return.\r
+\r
+# if GTEST_OS_WINDOWS && !defined(__GNUC__)\r
+\r
+ // MSVC and C++ Builder define __int64 instead of the standard long long.\r
+ typedef unsigned __int64 BiggestConvertible;\r
+ const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);\r
+\r
+# else\r
+\r
+ typedef unsigned long long BiggestConvertible; // NOLINT\r
+ const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);\r
+\r
+# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)\r
+\r
+ const bool parse_success = *end == '\0' && errno == 0;\r
+\r
+ // TODO(vladl@google.com): Convert this to compile time assertion when it is\r
+ // available.\r
+ GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));\r
+\r
+ const Integer result = static_cast<Integer>(parsed);\r
+ if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {\r
+ *number = result;\r
+ return true;\r
+ }\r
+ return false;\r
+}\r
+#endif // GTEST_HAS_DEATH_TEST\r
+\r
+// TestResult contains some private methods that should be hidden from\r
+// Google Test user but are required for testing. This class allow our tests\r
+// to access them.\r
+//\r
+// This class is supplied only for the purpose of testing Google Test's own\r
+// constructs. Do not use it in user tests, either directly or indirectly.\r
+class TestResultAccessor {\r
+ public:\r
+ static void RecordProperty(TestResult* test_result,\r
+ const std::string& xml_element,\r
+ const TestProperty& property) {\r
+ test_result->RecordProperty(xml_element, property);\r
+ }\r
+\r
+ static void ClearTestPartResults(TestResult* test_result) {\r
+ test_result->ClearTestPartResults();\r
+ }\r
+\r
+ static const std::vector<testing::TestPartResult>& test_part_results(\r
+ const TestResult& test_result) {\r
+ return test_result.test_part_results();\r
+ }\r
+};\r
+\r
+#if GTEST_CAN_STREAM_RESULTS_\r
+\r
+// Streams test results to the given port on the given host machine.\r
+class StreamingListener : public EmptyTestEventListener {\r
+ public:\r
+ // Abstract base class for writing strings to a socket.\r
+ class AbstractSocketWriter {\r
+ public:\r
+ virtual ~AbstractSocketWriter() {}\r
+\r
+ // Sends a string to the socket.\r
+ virtual void Send(const string& message) = 0;\r
+\r
+ // Closes the socket.\r
+ virtual void CloseConnection() {}\r
+\r
+ // Sends a string and a newline to the socket.\r
+ void SendLn(const string& message) {\r
+ Send(message + "\n");\r
+ }\r
+ };\r
+\r
+ // Concrete class for actually writing strings to a socket.\r
+ class SocketWriter : public AbstractSocketWriter {\r
+ public:\r
+ SocketWriter(const string& host, const string& port)\r
+ : sockfd_(-1), host_name_(host), port_num_(port) {\r
+ MakeConnection();\r
+ }\r
+\r
+ virtual ~SocketWriter() {\r
+ if (sockfd_ != -1)\r
+ CloseConnection();\r
+ }\r
+\r
+ // Sends a string to the socket.\r
+ virtual void Send(const string& message) {\r
+ GTEST_CHECK_(sockfd_ != -1)\r
+ << "Send() can be called only when there is a connection.";\r
+\r
+ const int len = static_cast<int>(message.length());\r
+ if (write(sockfd_, message.c_str(), len) != len) {\r
+ GTEST_LOG_(WARNING)\r
+ << "stream_result_to: failed to stream to "\r
+ << host_name_ << ":" << port_num_;\r
+ }\r
+ }\r
+\r
+ private:\r
+ // Creates a client socket and connects to the server.\r
+ void MakeConnection();\r
+\r
+ // Closes the socket.\r
+ void CloseConnection() {\r
+ GTEST_CHECK_(sockfd_ != -1)\r
+ << "CloseConnection() can be called only when there is a connection.";\r
+\r
+ close(sockfd_);\r
+ sockfd_ = -1;\r
+ }\r
+\r
+ int sockfd_; // socket file descriptor\r
+ const string host_name_;\r
+ const string port_num_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);\r
+ }; // class SocketWriter\r
+\r
+ // Escapes '=', '&', '%', and '\n' characters in str as "%xx".\r
+ static string UrlEncode(const char* str);\r
+\r
+ StreamingListener(const string& host, const string& port)\r
+ : socket_writer_(new SocketWriter(host, port)) { Start(); }\r
+\r
+ explicit StreamingListener(AbstractSocketWriter* socket_writer)\r
+ : socket_writer_(socket_writer) { Start(); }\r
+\r
+ void OnTestProgramStart(const UnitTest& /* unit_test */) {\r
+ SendLn("event=TestProgramStart");\r
+ }\r
+\r
+ void OnTestProgramEnd(const UnitTest& unit_test) {\r
+ // Note that Google Test current only report elapsed time for each\r
+ // test iteration, not for the entire test program.\r
+ SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));\r
+\r
+ // Notify the streaming server to stop.\r
+ socket_writer_->CloseConnection();\r
+ }\r
+\r
+ void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {\r
+ SendLn("event=TestIterationStart&iteration=" +\r
+ StreamableToString(iteration));\r
+ }\r
+\r
+ void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {\r
+ SendLn("event=TestIterationEnd&passed=" +\r
+ FormatBool(unit_test.Passed()) + "&elapsed_time=" +\r
+ StreamableToString(unit_test.elapsed_time()) + "ms");\r
+ }\r
+\r
+ void OnTestCaseStart(const TestCase& test_case) {\r
+ SendLn(std::string("event=TestCaseStart&name=") + test_case.name());\r
+ }\r
+\r
+ void OnTestCaseEnd(const TestCase& test_case) {\r
+ SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())\r
+ + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())\r
+ + "ms");\r
+ }\r
+\r
+ void OnTestStart(const TestInfo& test_info) {\r
+ SendLn(std::string("event=TestStart&name=") + test_info.name());\r
+ }\r
+\r
+ void OnTestEnd(const TestInfo& test_info) {\r
+ SendLn("event=TestEnd&passed=" +\r
+ FormatBool((test_info.result())->Passed()) +\r
+ "&elapsed_time=" +\r
+ StreamableToString((test_info.result())->elapsed_time()) + "ms");\r
+ }\r
+\r
+ void OnTestPartResult(const TestPartResult& test_part_result) {\r
+ const char* file_name = test_part_result.file_name();\r
+ if (file_name == NULL)\r
+ file_name = "";\r
+ SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +\r
+ "&line=" + StreamableToString(test_part_result.line_number()) +\r
+ "&message=" + UrlEncode(test_part_result.message()));\r
+ }\r
+\r
+ private:\r
+ // Sends the given message and a newline to the socket.\r
+ void SendLn(const string& message) { socket_writer_->SendLn(message); }\r
+\r
+ // Called at the start of streaming to notify the receiver what\r
+ // protocol we are using.\r
+ void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }\r
+\r
+ string FormatBool(bool value) { return value ? "1" : "0"; }\r
+\r
+ const scoped_ptr<AbstractSocketWriter> socket_writer_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);\r
+}; // class StreamingListener\r
+\r
+#endif // GTEST_CAN_STREAM_RESULTS_\r
+\r
+} // namespace internal\r
+} // namespace testing\r
+\r
+#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_\r
+#undef GTEST_IMPLEMENTATION_\r
+\r
+#if GTEST_OS_WINDOWS\r
+# define vsnprintf _vsnprintf\r
+#endif // GTEST_OS_WINDOWS\r
+\r
+namespace testing {\r
+\r
+using internal::CountIf;\r
+using internal::ForEach;\r
+using internal::GetElementOr;\r
+using internal::Shuffle;\r
+\r
+// Constants.\r
+\r
+// A test whose test case name or test name matches this filter is\r
+// disabled and not run.\r
+static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";\r
+\r
+// A test case whose name matches this filter is considered a death\r
+// test case and will be run before test cases whose name doesn't\r
+// match this filter.\r
+static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";\r
+\r
+// A test filter that matches everything.\r
+static const char kUniversalFilter[] = "*";\r
+\r
+// The default output file for XML output.\r
+static const char kDefaultOutputFile[] = "test_detail.xml";\r
+\r
+// The environment variable name for the test shard index.\r
+static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";\r
+// The environment variable name for the total number of test shards.\r
+static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";\r
+// The environment variable name for the test shard status file.\r
+static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";\r
+\r
+namespace internal {\r
+\r
+// The text used in failure messages to indicate the start of the\r
+// stack trace.\r
+const char kStackTraceMarker[] = "\nStack trace:\n";\r
+\r
+// g_help_flag is true iff the --help flag or an equivalent form is\r
+// specified on the command line.\r
+bool g_help_flag = false;\r
+\r
+} // namespace internal\r
+\r
+static const char* GetDefaultFilter() {\r
+#ifdef GTEST_TEST_FILTER_ENV_VAR_\r
+ const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_);\r
+ if (testbridge_test_only != NULL) {\r
+ return testbridge_test_only;\r
+ }\r
+#endif // GTEST_TEST_FILTER_ENV_VAR_\r
+ return kUniversalFilter;\r
+}\r
+\r
+GTEST_DEFINE_bool_(\r
+ also_run_disabled_tests,\r
+ internal::BoolFromGTestEnv("also_run_disabled_tests", false),\r
+ "Run disabled tests too, in addition to the tests normally being run.");\r
+\r
+GTEST_DEFINE_bool_(\r
+ break_on_failure,\r
+ internal::BoolFromGTestEnv("break_on_failure", false),\r
+ "True iff a failed assertion should be a debugger break-point.");\r
+\r
+GTEST_DEFINE_bool_(\r
+ catch_exceptions,\r
+ internal::BoolFromGTestEnv("catch_exceptions", true),\r
+ "True iff " GTEST_NAME_\r
+ " should catch exceptions and treat them as test failures.");\r
+\r
+GTEST_DEFINE_string_(\r
+ color,\r
+ internal::StringFromGTestEnv("color", "auto"),\r
+ "Whether to use colors in the output. Valid values: yes, no, "\r
+ "and auto. 'auto' means to use colors if the output is "\r
+ "being sent to a terminal and the TERM environment variable "\r
+ "is set to a terminal type that supports colors.");\r
+\r
+GTEST_DEFINE_string_(\r
+ filter,\r
+ internal::StringFromGTestEnv("filter", GetDefaultFilter()),\r
+ "A colon-separated list of glob (not regex) patterns "\r
+ "for filtering the tests to run, optionally followed by a "\r
+ "'-' and a : separated list of negative patterns (tests to "\r
+ "exclude). A test is run if it matches one of the positive "\r
+ "patterns and does not match any of the negative patterns.");\r
+\r
+GTEST_DEFINE_bool_(list_tests, false,\r
+ "List all tests without running them.");\r
+\r
+GTEST_DEFINE_string_(\r
+ output,\r
+ internal::StringFromGTestEnv("output", ""),\r
+ "A format (currently must be \"xml\"), optionally followed "\r
+ "by a colon and an output file name or directory. A directory "\r
+ "is indicated by a trailing pathname separator. "\r
+ "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "\r
+ "If a directory is specified, output files will be created "\r
+ "within that directory, with file-names based on the test "\r
+ "executable's name and, if necessary, made unique by adding "\r
+ "digits.");\r
+\r
+GTEST_DEFINE_bool_(\r
+ print_time,\r
+ internal::BoolFromGTestEnv("print_time", true),\r
+ "True iff " GTEST_NAME_\r
+ " should display elapsed time in text output.");\r
+\r
+GTEST_DEFINE_int32_(\r
+ random_seed,\r
+ internal::Int32FromGTestEnv("random_seed", 0),\r
+ "Random number seed to use when shuffling test orders. Must be in range "\r
+ "[1, 99999], or 0 to use a seed based on the current time.");\r
+\r
+GTEST_DEFINE_int32_(\r
+ repeat,\r
+ internal::Int32FromGTestEnv("repeat", 1),\r
+ "How many times to repeat each test. Specify a negative number "\r
+ "for repeating forever. Useful for shaking out flaky tests.");\r
+\r
+GTEST_DEFINE_bool_(\r
+ show_internal_stack_frames, false,\r
+ "True iff " GTEST_NAME_ " should include internal stack frames when "\r
+ "printing test failure stack traces.");\r
+\r
+GTEST_DEFINE_bool_(\r
+ shuffle,\r
+ internal::BoolFromGTestEnv("shuffle", false),\r
+ "True iff " GTEST_NAME_\r
+ " should randomize tests' order on every run.");\r
+\r
+GTEST_DEFINE_int32_(\r
+ stack_trace_depth,\r
+ internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),\r
+ "The maximum number of stack frames to print when an "\r
+ "assertion fails. The valid range is 0 through 100, inclusive.");\r
+\r
+GTEST_DEFINE_string_(\r
+ stream_result_to,\r
+ internal::StringFromGTestEnv("stream_result_to", ""),\r
+ "This flag specifies the host name and the port number on which to stream "\r
+ "test results. Example: \"localhost:555\". The flag is effective only on "\r
+ "Linux.");\r
+\r
+GTEST_DEFINE_bool_(\r
+ throw_on_failure,\r
+ internal::BoolFromGTestEnv("throw_on_failure", false),\r
+ "When this flag is specified, a failed assertion will throw an exception "\r
+ "if exceptions are enabled or exit the program with a non-zero code "\r
+ "otherwise.");\r
+\r
+#if GTEST_USE_OWN_FLAGFILE_FLAG_\r
+GTEST_DEFINE_string_(\r
+ flagfile,\r
+ internal::StringFromGTestEnv("flagfile", ""),\r
+ "This flag specifies the flagfile to read command-line flags from.");\r
+#endif // GTEST_USE_OWN_FLAGFILE_FLAG_\r
+\r
+namespace internal {\r
+\r
+// Generates a random number from [0, range), using a Linear\r
+// Congruential Generator (LCG). Crashes if 'range' is 0 or greater\r
+// than kMaxRange.\r
+UInt32 Random::Generate(UInt32 range) {\r
+ // These constants are the same as are used in glibc's rand(3).\r
+ state_ = (1103515245U*state_ + 12345U) % kMaxRange;\r
+\r
+ GTEST_CHECK_(range > 0)\r
+ << "Cannot generate a number in the range [0, 0).";\r
+ GTEST_CHECK_(range <= kMaxRange)\r
+ << "Generation of a number in [0, " << range << ") was requested, "\r
+ << "but this can only generate numbers in [0, " << kMaxRange << ").";\r
+\r
+ // Converting via modulus introduces a bit of downward bias, but\r
+ // it's simple, and a linear congruential generator isn't too good\r
+ // to begin with.\r
+ return state_ % range;\r
+}\r
+\r
+// GTestIsInitialized() returns true iff the user has initialized\r
+// Google Test. Useful for catching the user mistake of not initializing\r
+// Google Test before calling RUN_ALL_TESTS().\r
+static bool GTestIsInitialized() { return GetArgvs().size() > 0; }\r
+\r
+// Iterates over a vector of TestCases, keeping a running sum of the\r
+// results of calling a given int-returning method on each.\r
+// Returns the sum.\r
+static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,\r
+ int (TestCase::*method)() const) {\r
+ int sum = 0;\r
+ for (size_t i = 0; i < case_list.size(); i++) {\r
+ sum += (case_list[i]->*method)();\r
+ }\r
+ return sum;\r
+}\r
+\r
+// Returns true iff the test case passed.\r
+static bool TestCasePassed(const TestCase* test_case) {\r
+ return test_case->should_run() && test_case->Passed();\r
+}\r
+\r
+// Returns true iff the test case failed.\r
+static bool TestCaseFailed(const TestCase* test_case) {\r
+ return test_case->should_run() && test_case->Failed();\r
+}\r
+\r
+// Returns true iff test_case contains at least one test that should\r
+// run.\r
+static bool ShouldRunTestCase(const TestCase* test_case) {\r
+ return test_case->should_run();\r
+}\r
+\r
+// AssertHelper constructor.\r
+AssertHelper::AssertHelper(TestPartResult::Type type,\r
+ const char* file,\r
+ int line,\r
+ const char* message)\r
+ : data_(new AssertHelperData(type, file, line, message)) {\r
+}\r
+\r
+AssertHelper::~AssertHelper() {\r
+ delete data_;\r
+}\r
+\r
+// Message assignment, for assertion streaming support.\r
+void AssertHelper::operator=(const Message& message) const {\r
+ UnitTest::GetInstance()->\r
+ AddTestPartResult(data_->type, data_->file, data_->line,\r
+ AppendUserMessage(data_->message, message),\r
+ UnitTest::GetInstance()->impl()\r
+ ->CurrentOsStackTraceExceptTop(1)\r
+ // Skips the stack frame for this function itself.\r
+ ); // NOLINT\r
+}\r
+\r
+// Mutex for linked pointers.\r
+GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);\r
+\r
+// A copy of all command line arguments. Set by InitGoogleTest().\r
+::std::vector<testing::internal::string> g_argvs;\r
+\r
+const ::std::vector<testing::internal::string>& GetArgvs() {\r
+#if defined(GTEST_CUSTOM_GET_ARGVS_)\r
+ return GTEST_CUSTOM_GET_ARGVS_();\r
+#else // defined(GTEST_CUSTOM_GET_ARGVS_)\r
+ return g_argvs;\r
+#endif // defined(GTEST_CUSTOM_GET_ARGVS_)\r
+}\r
+\r
+// Returns the current application's name, removing directory path if that\r
+// is present.\r
+FilePath GetCurrentExecutableName() {\r
+ FilePath result;\r
+\r
+#if GTEST_OS_WINDOWS\r
+ result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));\r
+#else\r
+ result.Set(FilePath(GetArgvs()[0]));\r
+#endif // GTEST_OS_WINDOWS\r
+\r
+ return result.RemoveDirectoryName();\r
+}\r
+\r
+// Functions for processing the gtest_output flag.\r
+\r
+// Returns the output format, or "" for normal printed output.\r
+std::string UnitTestOptions::GetOutputFormat() {\r
+ const char* const gtest_output_flag = GTEST_FLAG(output).c_str();\r
+ if (gtest_output_flag == NULL) return std::string("");\r
+\r
+ const char* const colon = strchr(gtest_output_flag, ':');\r
+ return (colon == NULL) ?\r
+ std::string(gtest_output_flag) :\r
+ std::string(gtest_output_flag, colon - gtest_output_flag);\r
+}\r
+\r
+// Returns the name of the requested output file, or the default if none\r
+// was explicitly specified.\r
+std::string UnitTestOptions::GetAbsolutePathToOutputFile() {\r
+ const char* const gtest_output_flag = GTEST_FLAG(output).c_str();\r
+ if (gtest_output_flag == NULL)\r
+ return "";\r
+\r
+ const char* const colon = strchr(gtest_output_flag, ':');\r
+ if (colon == NULL)\r
+ return internal::FilePath::ConcatPaths(\r
+ internal::FilePath(\r
+ UnitTest::GetInstance()->original_working_dir()),\r
+ internal::FilePath(kDefaultOutputFile)).string();\r
+\r
+ internal::FilePath output_name(colon + 1);\r
+ if (!output_name.IsAbsolutePath())\r
+ // TODO(wan@google.com): on Windows \some\path is not an absolute\r
+ // path (as its meaning depends on the current drive), yet the\r
+ // following logic for turning it into an absolute path is wrong.\r
+ // Fix it.\r
+ output_name = internal::FilePath::ConcatPaths(\r
+ internal::FilePath(UnitTest::GetInstance()->original_working_dir()),\r
+ internal::FilePath(colon + 1));\r
+\r
+ if (!output_name.IsDirectory())\r
+ return output_name.string();\r
+\r
+ internal::FilePath result(internal::FilePath::GenerateUniqueFileName(\r
+ output_name, internal::GetCurrentExecutableName(),\r
+ GetOutputFormat().c_str()));\r
+ return result.string();\r
+}\r
+\r
+// Returns true iff the wildcard pattern matches the string. The\r
+// first ':' or '\0' character in pattern marks the end of it.\r
+//\r
+// This recursive algorithm isn't very efficient, but is clear and\r
+// works well enough for matching test names, which are short.\r
+bool UnitTestOptions::PatternMatchesString(const char *pattern,\r
+ const char *str) {\r
+ switch (*pattern) {\r
+ case '\0':\r
+ case ':': // Either ':' or '\0' marks the end of the pattern.\r
+ return *str == '\0';\r
+ case '?': // Matches any single character.\r
+ return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);\r
+ case '*': // Matches any string (possibly empty) of characters.\r
+ return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||\r
+ PatternMatchesString(pattern + 1, str);\r
+ default: // Non-special character. Matches itself.\r
+ return *pattern == *str &&\r
+ PatternMatchesString(pattern + 1, str + 1);\r
+ }\r
+}\r
+\r
+bool UnitTestOptions::MatchesFilter(\r
+ const std::string& name, const char* filter) {\r
+ const char *cur_pattern = filter;\r
+ for (;;) {\r
+ if (PatternMatchesString(cur_pattern, name.c_str())) {\r
+ return true;\r
+ }\r
+\r
+ // Finds the next pattern in the filter.\r
+ cur_pattern = strchr(cur_pattern, ':');\r
+\r
+ // Returns if no more pattern can be found.\r
+ if (cur_pattern == NULL) {\r
+ return false;\r
+ }\r
+\r
+ // Skips the pattern separater (the ':' character).\r
+ cur_pattern++;\r
+ }\r
+}\r
+\r
+// Returns true iff the user-specified filter matches the test case\r
+// name and the test name.\r
+bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,\r
+ const std::string &test_name) {\r
+ const std::string& full_name = test_case_name + "." + test_name.c_str();\r
+\r
+ // Split --gtest_filter at '-', if there is one, to separate into\r
+ // positive filter and negative filter portions\r
+ const char* const p = GTEST_FLAG(filter).c_str();\r
+ const char* const dash = strchr(p, '-');\r
+ std::string positive;\r
+ std::string negative;\r
+ if (dash == NULL) {\r
+ positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter\r
+ negative = "";\r
+ } else {\r
+ positive = std::string(p, dash); // Everything up to the dash\r
+ negative = std::string(dash + 1); // Everything after the dash\r
+ if (positive.empty()) {\r
+ // Treat '-test1' as the same as '*-test1'\r
+ positive = kUniversalFilter;\r
+ }\r
+ }\r
+\r
+ // A filter is a colon-separated list of patterns. It matches a\r
+ // test if any pattern in it matches the test.\r
+ return (MatchesFilter(full_name, positive.c_str()) &&\r
+ !MatchesFilter(full_name, negative.c_str()));\r
+}\r
+\r
+#if GTEST_HAS_SEH\r
+// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the\r
+// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.\r
+// This function is useful as an __except condition.\r
+int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {\r
+ // Google Test should handle a SEH exception if:\r
+ // 1. the user wants it to, AND\r
+ // 2. this is not a breakpoint exception, AND\r
+ // 3. this is not a C++ exception (VC++ implements them via SEH,\r
+ // apparently).\r
+ //\r
+ // SEH exception code for C++ exceptions.\r
+ // (see http://support.microsoft.com/kb/185294 for more information).\r
+ const DWORD kCxxExceptionCode = 0xe06d7363;\r
+\r
+ bool should_handle = true;\r
+\r
+ if (!GTEST_FLAG(catch_exceptions))\r
+ should_handle = false;\r
+ else if (exception_code == EXCEPTION_BREAKPOINT)\r
+ should_handle = false;\r
+ else if (exception_code == kCxxExceptionCode)\r
+ should_handle = false;\r
+\r
+ return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;\r
+}\r
+#endif // GTEST_HAS_SEH\r
+\r
+} // namespace internal\r
+\r
+// The c'tor sets this object as the test part result reporter used by\r
+// Google Test. The 'result' parameter specifies where to report the\r
+// results. Intercepts only failures from the current thread.\r
+ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(\r
+ TestPartResultArray* result)\r
+ : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),\r
+ result_(result) {\r
+ Init();\r
+}\r
+\r
+// The c'tor sets this object as the test part result reporter used by\r
+// Google Test. The 'result' parameter specifies where to report the\r
+// results.\r
+ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(\r
+ InterceptMode intercept_mode, TestPartResultArray* result)\r
+ : intercept_mode_(intercept_mode),\r
+ result_(result) {\r
+ Init();\r
+}\r
+\r
+void ScopedFakeTestPartResultReporter::Init() {\r
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\r
+ if (intercept_mode_ == INTERCEPT_ALL_THREADS) {\r
+ old_reporter_ = impl->GetGlobalTestPartResultReporter();\r
+ impl->SetGlobalTestPartResultReporter(this);\r
+ } else {\r
+ old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();\r
+ impl->SetTestPartResultReporterForCurrentThread(this);\r
+ }\r
+}\r
+\r
+// The d'tor restores the test part result reporter used by Google Test\r
+// before.\r
+ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {\r
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\r
+ if (intercept_mode_ == INTERCEPT_ALL_THREADS) {\r
+ impl->SetGlobalTestPartResultReporter(old_reporter_);\r
+ } else {\r
+ impl->SetTestPartResultReporterForCurrentThread(old_reporter_);\r
+ }\r
+}\r
+\r
+// Increments the test part result count and remembers the result.\r
+// This method is from the TestPartResultReporterInterface interface.\r
+void ScopedFakeTestPartResultReporter::ReportTestPartResult(\r
+ const TestPartResult& result) {\r
+ result_->Append(result);\r
+}\r
+\r
+namespace internal {\r
+\r
+// Returns the type ID of ::testing::Test. We should always call this\r
+// instead of GetTypeId< ::testing::Test>() to get the type ID of\r
+// testing::Test. This is to work around a suspected linker bug when\r
+// using Google Test as a framework on Mac OS X. The bug causes\r
+// GetTypeId< ::testing::Test>() to return different values depending\r
+// on whether the call is from the Google Test framework itself or\r
+// from user test code. GetTestTypeId() is guaranteed to always\r
+// return the same value, as it always calls GetTypeId<>() from the\r
+// gtest.cc, which is within the Google Test framework.\r
+TypeId GetTestTypeId() {\r
+ return GetTypeId<Test>();\r
+}\r
+\r
+// The value of GetTestTypeId() as seen from within the Google Test\r
+// library. This is solely for testing GetTestTypeId().\r
+extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();\r
+\r
+// This predicate-formatter checks that 'results' contains a test part\r
+// failure of the given type and that the failure message contains the\r
+// given substring.\r
+AssertionResult HasOneFailure(const char* /* results_expr */,\r
+ const char* /* type_expr */,\r
+ const char* /* substr_expr */,\r
+ const TestPartResultArray& results,\r
+ TestPartResult::Type type,\r
+ const string& substr) {\r
+ const std::string expected(type == TestPartResult::kFatalFailure ?\r
+ "1 fatal failure" :\r
+ "1 non-fatal failure");\r
+ Message msg;\r
+ if (results.size() != 1) {\r
+ msg << "Expected: " << expected << "\n"\r
+ << " Actual: " << results.size() << " failures";\r
+ for (int i = 0; i < results.size(); i++) {\r
+ msg << "\n" << results.GetTestPartResult(i);\r
+ }\r
+ return AssertionFailure() << msg;\r
+ }\r
+\r
+ const TestPartResult& r = results.GetTestPartResult(0);\r
+ if (r.type() != type) {\r
+ return AssertionFailure() << "Expected: " << expected << "\n"\r
+ << " Actual:\n"\r
+ << r;\r
+ }\r
+\r
+ if (strstr(r.message(), substr.c_str()) == NULL) {\r
+ return AssertionFailure() << "Expected: " << expected << " containing \""\r
+ << substr << "\"\n"\r
+ << " Actual:\n"\r
+ << r;\r
+ }\r
+\r
+ return AssertionSuccess();\r
+}\r
+\r
+// The constructor of SingleFailureChecker remembers where to look up\r
+// test part results, what type of failure we expect, and what\r
+// substring the failure message should contain.\r
+SingleFailureChecker:: SingleFailureChecker(\r
+ const TestPartResultArray* results,\r
+ TestPartResult::Type type,\r
+ const string& substr)\r
+ : results_(results),\r
+ type_(type),\r
+ substr_(substr) {}\r
+\r
+// The destructor of SingleFailureChecker verifies that the given\r
+// TestPartResultArray contains exactly one failure that has the given\r
+// type and contains the given substring. If that's not the case, a\r
+// non-fatal failure will be generated.\r
+SingleFailureChecker::~SingleFailureChecker() {\r
+ EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);\r
+}\r
+\r
+DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(\r
+ UnitTestImpl* unit_test) : unit_test_(unit_test) {}\r
+\r
+void DefaultGlobalTestPartResultReporter::ReportTestPartResult(\r
+ const TestPartResult& result) {\r
+ unit_test_->current_test_result()->AddTestPartResult(result);\r
+ unit_test_->listeners()->repeater()->OnTestPartResult(result);\r
+}\r
+\r
+DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(\r
+ UnitTestImpl* unit_test) : unit_test_(unit_test) {}\r
+\r
+void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(\r
+ const TestPartResult& result) {\r
+ unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);\r
+}\r
+\r
+// Returns the global test part result reporter.\r
+TestPartResultReporterInterface*\r
+UnitTestImpl::GetGlobalTestPartResultReporter() {\r
+ internal::MutexLock lock(&global_test_part_result_reporter_mutex_);\r
+ return global_test_part_result_repoter_;\r
+}\r
+\r
+// Sets the global test part result reporter.\r
+void UnitTestImpl::SetGlobalTestPartResultReporter(\r
+ TestPartResultReporterInterface* reporter) {\r
+ internal::MutexLock lock(&global_test_part_result_reporter_mutex_);\r
+ global_test_part_result_repoter_ = reporter;\r
+}\r
+\r
+// Returns the test part result reporter for the current thread.\r
+TestPartResultReporterInterface*\r
+UnitTestImpl::GetTestPartResultReporterForCurrentThread() {\r
+ return per_thread_test_part_result_reporter_.get();\r
+}\r
+\r
+// Sets the test part result reporter for the current thread.\r
+void UnitTestImpl::SetTestPartResultReporterForCurrentThread(\r
+ TestPartResultReporterInterface* reporter) {\r
+ per_thread_test_part_result_reporter_.set(reporter);\r
+}\r
+\r
+// Gets the number of successful test cases.\r
+int UnitTestImpl::successful_test_case_count() const {\r
+ return CountIf(test_cases_, TestCasePassed);\r
+}\r
+\r
+// Gets the number of failed test cases.\r
+int UnitTestImpl::failed_test_case_count() const {\r
+ return CountIf(test_cases_, TestCaseFailed);\r
+}\r
+\r
+// Gets the number of all test cases.\r
+int UnitTestImpl::total_test_case_count() const {\r
+ return static_cast<int>(test_cases_.size());\r
+}\r
+\r
+// Gets the number of all test cases that contain at least one test\r
+// that should run.\r
+int UnitTestImpl::test_case_to_run_count() const {\r
+ return CountIf(test_cases_, ShouldRunTestCase);\r
+}\r
+\r
+// Gets the number of successful tests.\r
+int UnitTestImpl::successful_test_count() const {\r
+ return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);\r
+}\r
+\r
+// Gets the number of failed tests.\r
+int UnitTestImpl::failed_test_count() const {\r
+ return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);\r
+}\r
+\r
+// Gets the number of disabled tests that will be reported in the XML report.\r
+int UnitTestImpl::reportable_disabled_test_count() const {\r
+ return SumOverTestCaseList(test_cases_,\r
+ &TestCase::reportable_disabled_test_count);\r
+}\r
+\r
+// Gets the number of disabled tests.\r
+int UnitTestImpl::disabled_test_count() const {\r
+ return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);\r
+}\r
+\r
+// Gets the number of tests to be printed in the XML report.\r
+int UnitTestImpl::reportable_test_count() const {\r
+ return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);\r
+}\r
+\r
+// Gets the number of all tests.\r
+int UnitTestImpl::total_test_count() const {\r
+ return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);\r
+}\r
+\r
+// Gets the number of tests that should run.\r
+int UnitTestImpl::test_to_run_count() const {\r
+ return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);\r
+}\r
+\r
+// Returns the current OS stack trace as an std::string.\r
+//\r
+// The maximum number of stack frames to be included is specified by\r
+// the gtest_stack_trace_depth flag. The skip_count parameter\r
+// specifies the number of top frames to be skipped, which doesn't\r
+// count against the number of frames to be included.\r
+//\r
+// For example, if Foo() calls Bar(), which in turn calls\r
+// CurrentOsStackTraceExceptTop(1), Foo() will be included in the\r
+// trace but Bar() and CurrentOsStackTraceExceptTop() won't.\r
+std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {\r
+ return os_stack_trace_getter()->CurrentStackTrace(\r
+ static_cast<int>(GTEST_FLAG(stack_trace_depth)),\r
+ skip_count + 1\r
+ // Skips the user-specified number of frames plus this function\r
+ // itself.\r
+ ); // NOLINT\r
+}\r
+\r
+// Returns the current time in milliseconds.\r
+TimeInMillis GetTimeInMillis() {\r
+#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)\r
+ // Difference between 1970-01-01 and 1601-01-01 in milliseconds.\r
+ // http://analogous.blogspot.com/2005/04/epoch.html\r
+ const TimeInMillis kJavaEpochToWinFileTimeDelta =\r
+ static_cast<TimeInMillis>(116444736UL) * 100000UL;\r
+ const DWORD kTenthMicrosInMilliSecond = 10000;\r
+\r
+ SYSTEMTIME now_systime;\r
+ FILETIME now_filetime;\r
+ ULARGE_INTEGER now_int64;\r
+ // TODO(kenton@google.com): Shouldn't this just use\r
+ // GetSystemTimeAsFileTime()?\r
+ GetSystemTime(&now_systime);\r
+ if (SystemTimeToFileTime(&now_systime, &now_filetime)) {\r
+ now_int64.LowPart = now_filetime.dwLowDateTime;\r
+ now_int64.HighPart = now_filetime.dwHighDateTime;\r
+ now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -\r
+ kJavaEpochToWinFileTimeDelta;\r
+ return now_int64.QuadPart;\r
+ }\r
+ return 0;\r
+#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_\r
+ __timeb64 now;\r
+\r
+ // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996\r
+ // (deprecated function) there.\r
+ // TODO(kenton@google.com): Use GetTickCount()? Or use\r
+ // SystemTimeToFileTime()\r
+ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)\r
+ _ftime64(&now);\r
+ GTEST_DISABLE_MSC_WARNINGS_POP_()\r
+\r
+ return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;\r
+#elif GTEST_HAS_GETTIMEOFDAY_\r
+ struct timeval now;\r
+ gettimeofday(&now, NULL);\r
+ return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;\r
+#else\r
+# error "Don't know how to get the current time on your system."\r
+#endif\r
+}\r
+\r
+// Utilities\r
+\r
+// class String.\r
+\r
+#if GTEST_OS_WINDOWS_MOBILE\r
+// Creates a UTF-16 wide string from the given ANSI string, allocating\r
+// memory using new. The caller is responsible for deleting the return\r
+// value using delete[]. Returns the wide string, or NULL if the\r
+// input is NULL.\r
+LPCWSTR String::AnsiToUtf16(const char* ansi) {\r
+ if (!ansi) return NULL;\r
+ const int length = strlen(ansi);\r
+ const int unicode_length =\r
+ MultiByteToWideChar(CP_ACP, 0, ansi, length,\r
+ NULL, 0);\r
+ WCHAR* unicode = new WCHAR[unicode_length + 1];\r
+ MultiByteToWideChar(CP_ACP, 0, ansi, length,\r
+ unicode, unicode_length);\r
+ unicode[unicode_length] = 0;\r
+ return unicode;\r
+}\r
+\r
+// Creates an ANSI string from the given wide string, allocating\r
+// memory using new. The caller is responsible for deleting the return\r
+// value using delete[]. Returns the ANSI string, or NULL if the\r
+// input is NULL.\r
+const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {\r
+ if (!utf16_str) return NULL;\r
+ const int ansi_length =\r
+ WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,\r
+ NULL, 0, NULL, NULL);\r
+ char* ansi = new char[ansi_length + 1];\r
+ WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,\r
+ ansi, ansi_length, NULL, NULL);\r
+ ansi[ansi_length] = 0;\r
+ return ansi;\r
+}\r
+\r
+#endif // GTEST_OS_WINDOWS_MOBILE\r
+\r
+// Compares two C strings. Returns true iff they have the same content.\r
+//\r
+// Unlike strcmp(), this function can handle NULL argument(s). A NULL\r
+// C string is considered different to any non-NULL C string,\r
+// including the empty string.\r
+bool String::CStringEquals(const char * lhs, const char * rhs) {\r
+ if ( lhs == NULL ) return rhs == NULL;\r
+\r
+ if ( rhs == NULL ) return false;\r
+\r
+ return strcmp(lhs, rhs) == 0;\r
+}\r
+\r
+#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING\r
+\r
+// Converts an array of wide chars to a narrow string using the UTF-8\r
+// encoding, and streams the result to the given Message object.\r
+static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,\r
+ Message* msg) {\r
+ for (size_t i = 0; i != length; ) { // NOLINT\r
+ if (wstr[i] != L'\0') {\r
+ *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));\r
+ while (i != length && wstr[i] != L'\0')\r
+ i++;\r
+ } else {\r
+ *msg << '\0';\r
+ i++;\r
+ }\r
+ }\r
+}\r
+\r
+#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING\r
+\r
+void SplitString(const ::std::string& str, char delimiter,\r
+ ::std::vector< ::std::string>* dest) {\r
+ ::std::vector< ::std::string> parsed;\r
+ ::std::string::size_type pos = 0;\r
+ while (::testing::internal::AlwaysTrue()) {\r
+ const ::std::string::size_type colon = str.find(delimiter, pos);\r
+ if (colon == ::std::string::npos) {\r
+ parsed.push_back(str.substr(pos));\r
+ break;\r
+ } else {\r
+ parsed.push_back(str.substr(pos, colon - pos));\r
+ pos = colon + 1;\r
+ }\r
+ }\r
+ dest->swap(parsed);\r
+}\r
+\r
+} // namespace internal\r
+\r
+// Constructs an empty Message.\r
+// We allocate the stringstream separately because otherwise each use of\r
+// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's\r
+// stack frame leading to huge stack frames in some cases; gcc does not reuse\r
+// the stack space.\r
+Message::Message() : ss_(new ::std::stringstream) {\r
+ // By default, we want there to be enough precision when printing\r
+ // a double to a Message.\r
+ *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);\r
+}\r
+\r
+// These two overloads allow streaming a wide C string to a Message\r
+// using the UTF-8 encoding.\r
+Message& Message::operator <<(const wchar_t* wide_c_str) {\r
+ return *this << internal::String::ShowWideCString(wide_c_str);\r
+}\r
+Message& Message::operator <<(wchar_t* wide_c_str) {\r
+ return *this << internal::String::ShowWideCString(wide_c_str);\r
+}\r
+\r
+#if GTEST_HAS_STD_WSTRING\r
+// Converts the given wide string to a narrow string using the UTF-8\r
+// encoding, and streams the result to this Message object.\r
+Message& Message::operator <<(const ::std::wstring& wstr) {\r
+ internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);\r
+ return *this;\r
+}\r
+#endif // GTEST_HAS_STD_WSTRING\r
+\r
+#if GTEST_HAS_GLOBAL_WSTRING\r
+// Converts the given wide string to a narrow string using the UTF-8\r
+// encoding, and streams the result to this Message object.\r
+Message& Message::operator <<(const ::wstring& wstr) {\r
+ internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);\r
+ return *this;\r
+}\r
+#endif // GTEST_HAS_GLOBAL_WSTRING\r
+\r
+// Gets the text streamed to this object so far as an std::string.\r
+// Each '\0' character in the buffer is replaced with "\\0".\r
+std::string Message::GetString() const {\r
+ return internal::StringStreamToString(ss_.get());\r
+}\r
+\r
+// AssertionResult constructors.\r
+// Used in EXPECT_TRUE/FALSE(assertion_result).\r
+AssertionResult::AssertionResult(const AssertionResult& other)\r
+ : success_(other.success_),\r
+ message_(other.message_.get() != NULL ?\r
+ new ::std::string(*other.message_) :\r
+ static_cast< ::std::string*>(NULL)) {\r
+}\r
+\r
+// Swaps two AssertionResults.\r
+void AssertionResult::swap(AssertionResult& other) {\r
+ using std::swap;\r
+ swap(success_, other.success_);\r
+ swap(message_, other.message_);\r
+}\r
+\r
+// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.\r
+AssertionResult AssertionResult::operator!() const {\r
+ AssertionResult negation(!success_);\r
+ if (message_.get() != NULL)\r
+ negation << *message_;\r
+ return negation;\r
+}\r
+\r
+// Makes a successful assertion result.\r
+AssertionResult AssertionSuccess() {\r
+ return AssertionResult(true);\r
+}\r
+\r
+// Makes a failed assertion result.\r
+AssertionResult AssertionFailure() {\r
+ return AssertionResult(false);\r
+}\r
+\r
+// Makes a failed assertion result with the given failure message.\r
+// Deprecated; use AssertionFailure() << message.\r
+AssertionResult AssertionFailure(const Message& message) {\r
+ return AssertionFailure() << message;\r
+}\r
+\r
+namespace internal {\r
+\r
+namespace edit_distance {\r
+std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,\r
+ const std::vector<size_t>& right) {\r
+ std::vector<std::vector<double> > costs(\r
+ left.size() + 1, std::vector<double>(right.size() + 1));\r
+ std::vector<std::vector<EditType> > best_move(\r
+ left.size() + 1, std::vector<EditType>(right.size() + 1));\r
+\r
+ // Populate for empty right.\r
+ for (size_t l_i = 0; l_i < costs.size(); ++l_i) {\r
+ costs[l_i][0] = static_cast<double>(l_i);\r
+ best_move[l_i][0] = kRemove;\r
+ }\r
+ // Populate for empty left.\r
+ for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {\r
+ costs[0][r_i] = static_cast<double>(r_i);\r
+ best_move[0][r_i] = kAdd;\r
+ }\r
+\r
+ for (size_t l_i = 0; l_i < left.size(); ++l_i) {\r
+ for (size_t r_i = 0; r_i < right.size(); ++r_i) {\r
+ if (left[l_i] == right[r_i]) {\r
+ // Found a match. Consume it.\r
+ costs[l_i + 1][r_i + 1] = costs[l_i][r_i];\r
+ best_move[l_i + 1][r_i + 1] = kMatch;\r
+ continue;\r
+ }\r
+\r
+ const double add = costs[l_i + 1][r_i];\r
+ const double remove = costs[l_i][r_i + 1];\r
+ const double replace = costs[l_i][r_i];\r
+ if (add < remove && add < replace) {\r
+ costs[l_i + 1][r_i + 1] = add + 1;\r
+ best_move[l_i + 1][r_i + 1] = kAdd;\r
+ } else if (remove < add && remove < replace) {\r
+ costs[l_i + 1][r_i + 1] = remove + 1;\r
+ best_move[l_i + 1][r_i + 1] = kRemove;\r
+ } else {\r
+ // We make replace a little more expensive than add/remove to lower\r
+ // their priority.\r
+ costs[l_i + 1][r_i + 1] = replace + 1.00001;\r
+ best_move[l_i + 1][r_i + 1] = kReplace;\r
+ }\r
+ }\r
+ }\r
+\r
+ // Reconstruct the best path. We do it in reverse order.\r
+ std::vector<EditType> best_path;\r
+ for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {\r
+ EditType move = best_move[l_i][r_i];\r
+ best_path.push_back(move);\r
+ l_i -= move != kAdd;\r
+ r_i -= move != kRemove;\r
+ }\r
+ std::reverse(best_path.begin(), best_path.end());\r
+ return best_path;\r
+}\r
+\r
+namespace {\r
+\r
+// Helper class to convert string into ids with deduplication.\r
+class InternalStrings {\r
+ public:\r
+ size_t GetId(const std::string& str) {\r
+ IdMap::iterator it = ids_.find(str);\r
+ if (it != ids_.end()) return it->second;\r
+ size_t id = ids_.size();\r
+ return ids_[str] = id;\r
+ }\r
+\r
+ private:\r
+ typedef std::map<std::string, size_t> IdMap;\r
+ IdMap ids_;\r
+};\r
+\r
+} // namespace\r
+\r
+std::vector<EditType> CalculateOptimalEdits(\r
+ const std::vector<std::string>& left,\r
+ const std::vector<std::string>& right) {\r
+ std::vector<size_t> left_ids, right_ids;\r
+ {\r
+ InternalStrings intern_table;\r
+ for (size_t i = 0; i < left.size(); ++i) {\r
+ left_ids.push_back(intern_table.GetId(left[i]));\r
+ }\r
+ for (size_t i = 0; i < right.size(); ++i) {\r
+ right_ids.push_back(intern_table.GetId(right[i]));\r
+ }\r
+ }\r
+ return CalculateOptimalEdits(left_ids, right_ids);\r
+}\r
+\r
+namespace {\r
+\r
+// Helper class that holds the state for one hunk and prints it out to the\r
+// stream.\r
+// It reorders adds/removes when possible to group all removes before all\r
+// adds. It also adds the hunk header before printint into the stream.\r
+class Hunk {\r
+ public:\r
+ Hunk(size_t left_start, size_t right_start)\r
+ : left_start_(left_start),\r
+ right_start_(right_start),\r
+ adds_(),\r
+ removes_(),\r
+ common_() {}\r
+\r
+ void PushLine(char edit, const char* line) {\r
+ switch (edit) {\r
+ case ' ':\r
+ ++common_;\r
+ FlushEdits();\r
+ hunk_.push_back(std::make_pair(' ', line));\r
+ break;\r
+ case '-':\r
+ ++removes_;\r
+ hunk_removes_.push_back(std::make_pair('-', line));\r
+ break;\r
+ case '+':\r
+ ++adds_;\r
+ hunk_adds_.push_back(std::make_pair('+', line));\r
+ break;\r
+ }\r
+ }\r
+\r
+ void PrintTo(std::ostream* os) {\r
+ PrintHeader(os);\r
+ FlushEdits();\r
+ for (std::list<std::pair<char, const char*> >::const_iterator it =\r
+ hunk_.begin();\r
+ it != hunk_.end(); ++it) {\r
+ *os << it->first << it->second << "\n";\r
+ }\r
+ }\r
+\r
+ bool has_edits() const { return adds_ || removes_; }\r
+\r
+ private:\r
+ void FlushEdits() {\r
+ hunk_.splice(hunk_.end(), hunk_removes_);\r
+ hunk_.splice(hunk_.end(), hunk_adds_);\r
+ }\r
+\r
+ // Print a unified diff header for one hunk.\r
+ // The format is\r
+ // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"\r
+ // where the left/right parts are ommitted if unnecessary.\r
+ void PrintHeader(std::ostream* ss) const {\r
+ *ss << "@@ ";\r
+ if (removes_) {\r
+ *ss << "-" << left_start_ << "," << (removes_ + common_);\r
+ }\r
+ if (removes_ && adds_) {\r
+ *ss << " ";\r
+ }\r
+ if (adds_) {\r
+ *ss << "+" << right_start_ << "," << (adds_ + common_);\r
+ }\r
+ *ss << " @@\n";\r
+ }\r
+\r
+ size_t left_start_, right_start_;\r
+ size_t adds_, removes_, common_;\r
+ std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;\r
+};\r
+\r
+} // namespace\r
+\r
+// Create a list of diff hunks in Unified diff format.\r
+// Each hunk has a header generated by PrintHeader above plus a body with\r
+// lines prefixed with ' ' for no change, '-' for deletion and '+' for\r
+// addition.\r
+// 'context' represents the desired unchanged prefix/suffix around the diff.\r
+// If two hunks are close enough that their contexts overlap, then they are\r
+// joined into one hunk.\r
+std::string CreateUnifiedDiff(const std::vector<std::string>& left,\r
+ const std::vector<std::string>& right,\r
+ size_t context) {\r
+ const std::vector<EditType> edits = CalculateOptimalEdits(left, right);\r
+\r
+ size_t l_i = 0, r_i = 0, edit_i = 0;\r
+ std::stringstream ss;\r
+ while (edit_i < edits.size()) {\r
+ // Find first edit.\r
+ while (edit_i < edits.size() && edits[edit_i] == kMatch) {\r
+ ++l_i;\r
+ ++r_i;\r
+ ++edit_i;\r
+ }\r
+\r
+ // Find the first line to include in the hunk.\r
+ const size_t prefix_context = std::min(l_i, context);\r
+ Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);\r
+ for (size_t i = prefix_context; i > 0; --i) {\r
+ hunk.PushLine(' ', left[l_i - i].c_str());\r
+ }\r
+\r
+ // Iterate the edits until we found enough suffix for the hunk or the input\r
+ // is over.\r
+ size_t n_suffix = 0;\r
+ for (; edit_i < edits.size(); ++edit_i) {\r
+ if (n_suffix >= context) {\r
+ // Continue only if the next hunk is very close.\r
+ std::vector<EditType>::const_iterator it = edits.begin() + edit_i;\r
+ while (it != edits.end() && *it == kMatch) ++it;\r
+ if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {\r
+ // There is no next edit or it is too far away.\r
+ break;\r
+ }\r
+ }\r
+\r
+ EditType edit = edits[edit_i];\r
+ // Reset count when a non match is found.\r
+ n_suffix = edit == kMatch ? n_suffix + 1 : 0;\r
+\r
+ if (edit == kMatch || edit == kRemove || edit == kReplace) {\r
+ hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());\r
+ }\r
+ if (edit == kAdd || edit == kReplace) {\r
+ hunk.PushLine('+', right[r_i].c_str());\r
+ }\r
+\r
+ // Advance indices, depending on edit type.\r
+ l_i += edit != kAdd;\r
+ r_i += edit != kRemove;\r
+ }\r
+\r
+ if (!hunk.has_edits()) {\r
+ // We are done. We don't want this hunk.\r
+ break;\r
+ }\r
+\r
+ hunk.PrintTo(&ss);\r
+ }\r
+ return ss.str();\r
+}\r
+\r
+} // namespace edit_distance\r
+\r
+namespace {\r
+\r
+// The string representation of the values received in EqFailure() are already\r
+// escaped. Split them on escaped '\n' boundaries. Leave all other escaped\r
+// characters the same.\r
+std::vector<std::string> SplitEscapedString(const std::string& str) {\r
+ std::vector<std::string> lines;\r
+ size_t start = 0, end = str.size();\r
+ if (end > 2 && str[0] == '"' && str[end - 1] == '"') {\r
+ ++start;\r
+ --end;\r
+ }\r
+ bool escaped = false;\r
+ for (size_t i = start; i + 1 < end; ++i) {\r
+ if (escaped) {\r
+ escaped = false;\r
+ if (str[i] == 'n') {\r
+ lines.push_back(str.substr(start, i - start - 1));\r
+ start = i + 1;\r
+ }\r
+ } else {\r
+ escaped = str[i] == '\\';\r
+ }\r
+ }\r
+ lines.push_back(str.substr(start, end - start));\r
+ return lines;\r
+}\r
+\r
+} // namespace\r
+\r
+// Constructs and returns the message for an equality assertion\r
+// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.\r
+//\r
+// The first four parameters are the expressions used in the assertion\r
+// and their values, as strings. For example, for ASSERT_EQ(foo, bar)\r
+// where foo is 5 and bar is 6, we have:\r
+//\r
+// expected_expression: "foo"\r
+// actual_expression: "bar"\r
+// expected_value: "5"\r
+// actual_value: "6"\r
+//\r
+// The ignoring_case parameter is true iff the assertion is a\r
+// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will\r
+// be inserted into the message.\r
+AssertionResult EqFailure(const char* expected_expression,\r
+ const char* actual_expression,\r
+ const std::string& expected_value,\r
+ const std::string& actual_value,\r
+ bool ignoring_case) {\r
+ Message msg;\r
+ msg << "Value of: " << actual_expression;\r
+ if (actual_value != actual_expression) {\r
+ msg << "\n Actual: " << actual_value;\r
+ }\r
+\r
+ msg << "\nExpected: " << expected_expression;\r
+ if (ignoring_case) {\r
+ msg << " (ignoring case)";\r
+ }\r
+ if (expected_value != expected_expression) {\r
+ msg << "\nWhich is: " << expected_value;\r
+ }\r
+\r
+ if (!expected_value.empty() && !actual_value.empty()) {\r
+ const std::vector<std::string> expected_lines =\r
+ SplitEscapedString(expected_value);\r
+ const std::vector<std::string> actual_lines =\r
+ SplitEscapedString(actual_value);\r
+ if (expected_lines.size() > 1 || actual_lines.size() > 1) {\r
+ msg << "\nWith diff:\n"\r
+ << edit_distance::CreateUnifiedDiff(expected_lines, actual_lines);\r
+ }\r
+ }\r
+\r
+ return AssertionFailure() << msg;\r
+}\r
+\r
+// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.\r
+std::string GetBoolAssertionFailureMessage(\r
+ const AssertionResult& assertion_result,\r
+ const char* expression_text,\r
+ const char* actual_predicate_value,\r
+ const char* expected_predicate_value) {\r
+ const char* actual_message = assertion_result.message();\r
+ Message msg;\r
+ msg << "Value of: " << expression_text\r
+ << "\n Actual: " << actual_predicate_value;\r
+ if (actual_message[0] != '\0')\r
+ msg << " (" << actual_message << ")";\r
+ msg << "\nExpected: " << expected_predicate_value;\r
+ return msg.GetString();\r
+}\r
+\r
+// Helper function for implementing ASSERT_NEAR.\r
+AssertionResult DoubleNearPredFormat(const char* expr1,\r
+ const char* expr2,\r
+ const char* abs_error_expr,\r
+ double val1,\r
+ double val2,\r
+ double abs_error) {\r
+ const double diff = fabs(val1 - val2);\r
+ if (diff <= abs_error) return AssertionSuccess();\r
+\r
+ // TODO(wan): do not print the value of an expression if it's\r
+ // already a literal.\r
+ return AssertionFailure()\r
+ << "The difference between " << expr1 << " and " << expr2\r
+ << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"\r
+ << expr1 << " evaluates to " << val1 << ",\n"\r
+ << expr2 << " evaluates to " << val2 << ", and\n"\r
+ << abs_error_expr << " evaluates to " << abs_error << ".";\r
+}\r
+\r
+\r
+// Helper template for implementing FloatLE() and DoubleLE().\r
+template <typename RawType>\r
+AssertionResult FloatingPointLE(const char* expr1,\r
+ const char* expr2,\r
+ RawType val1,\r
+ RawType val2) {\r
+ // Returns success if val1 is less than val2,\r
+ if (val1 < val2) {\r
+ return AssertionSuccess();\r
+ }\r
+\r
+ // or if val1 is almost equal to val2.\r
+ const FloatingPoint<RawType> lhs(val1), rhs(val2);\r
+ if (lhs.AlmostEquals(rhs)) {\r
+ return AssertionSuccess();\r
+ }\r
+\r
+ // Note that the above two checks will both fail if either val1 or\r
+ // val2 is NaN, as the IEEE floating-point standard requires that\r
+ // any predicate involving a NaN must return false.\r
+\r
+ ::std::stringstream val1_ss;\r
+ val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)\r
+ << val1;\r
+\r
+ ::std::stringstream val2_ss;\r
+ val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)\r
+ << val2;\r
+\r
+ return AssertionFailure()\r
+ << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"\r
+ << " Actual: " << StringStreamToString(&val1_ss) << " vs "\r
+ << StringStreamToString(&val2_ss);\r
+}\r
+\r
+} // namespace internal\r
+\r
+// Asserts that val1 is less than, or almost equal to, val2. Fails\r
+// otherwise. In particular, it fails if either val1 or val2 is NaN.\r
+AssertionResult FloatLE(const char* expr1, const char* expr2,\r
+ float val1, float val2) {\r
+ return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);\r
+}\r
+\r
+// Asserts that val1 is less than, or almost equal to, val2. Fails\r
+// otherwise. In particular, it fails if either val1 or val2 is NaN.\r
+AssertionResult DoubleLE(const char* expr1, const char* expr2,\r
+ double val1, double val2) {\r
+ return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);\r
+}\r
+\r
+namespace internal {\r
+\r
+// The helper function for {ASSERT|EXPECT}_EQ with int or enum\r
+// arguments.\r
+AssertionResult CmpHelperEQ(const char* expected_expression,\r
+ const char* actual_expression,\r
+ BiggestInt expected,\r
+ BiggestInt actual) {\r
+ if (expected == actual) {\r
+ return AssertionSuccess();\r
+ }\r
+\r
+ return EqFailure(expected_expression,\r
+ actual_expression,\r
+ FormatForComparisonFailureMessage(expected, actual),\r
+ FormatForComparisonFailureMessage(actual, expected),\r
+ false);\r
+}\r
+\r
+// A macro for implementing the helper functions needed to implement\r
+// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here\r
+// just to avoid copy-and-paste of similar code.\r
+#define GTEST_IMPL_CMP_HELPER_(op_name, op)\\r
+AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \\r
+ BiggestInt val1, BiggestInt val2) {\\r
+ if (val1 op val2) {\\r
+ return AssertionSuccess();\\r
+ } else {\\r
+ return AssertionFailure() \\r
+ << "Expected: (" << expr1 << ") " #op " (" << expr2\\r
+ << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\\r
+ << " vs " << FormatForComparisonFailureMessage(val2, val1);\\r
+ }\\r
+}\r
+\r
+// Implements the helper function for {ASSERT|EXPECT}_NE with int or\r
+// enum arguments.\r
+GTEST_IMPL_CMP_HELPER_(NE, !=)\r
+// Implements the helper function for {ASSERT|EXPECT}_LE with int or\r
+// enum arguments.\r
+GTEST_IMPL_CMP_HELPER_(LE, <=)\r
+// Implements the helper function for {ASSERT|EXPECT}_LT with int or\r
+// enum arguments.\r
+GTEST_IMPL_CMP_HELPER_(LT, < )\r
+// Implements the helper function for {ASSERT|EXPECT}_GE with int or\r
+// enum arguments.\r
+GTEST_IMPL_CMP_HELPER_(GE, >=)\r
+// Implements the helper function for {ASSERT|EXPECT}_GT with int or\r
+// enum arguments.\r
+GTEST_IMPL_CMP_HELPER_(GT, > )\r
+\r
+#undef GTEST_IMPL_CMP_HELPER_\r
+\r
+// The helper function for {ASSERT|EXPECT}_STREQ.\r
+AssertionResult CmpHelperSTREQ(const char* expected_expression,\r
+ const char* actual_expression,\r
+ const char* expected,\r
+ const char* actual) {\r
+ if (String::CStringEquals(expected, actual)) {\r
+ return AssertionSuccess();\r
+ }\r
+\r
+ return EqFailure(expected_expression,\r
+ actual_expression,\r
+ PrintToString(expected),\r
+ PrintToString(actual),\r
+ false);\r
+}\r
+\r
+// The helper function for {ASSERT|EXPECT}_STRCASEEQ.\r
+AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,\r
+ const char* actual_expression,\r
+ const char* expected,\r
+ const char* actual) {\r
+ if (String::CaseInsensitiveCStringEquals(expected, actual)) {\r
+ return AssertionSuccess();\r
+ }\r
+\r
+ return EqFailure(expected_expression,\r
+ actual_expression,\r
+ PrintToString(expected),\r
+ PrintToString(actual),\r
+ true);\r
+}\r
+\r
+// The helper function for {ASSERT|EXPECT}_STRNE.\r
+AssertionResult CmpHelperSTRNE(const char* s1_expression,\r
+ const char* s2_expression,\r
+ const char* s1,\r
+ const char* s2) {\r
+ if (!String::CStringEquals(s1, s2)) {\r
+ return AssertionSuccess();\r
+ } else {\r
+ return AssertionFailure() << "Expected: (" << s1_expression << ") != ("\r
+ << s2_expression << "), actual: \""\r
+ << s1 << "\" vs \"" << s2 << "\"";\r
+ }\r
+}\r
+\r
+// The helper function for {ASSERT|EXPECT}_STRCASENE.\r
+AssertionResult CmpHelperSTRCASENE(const char* s1_expression,\r
+ const char* s2_expression,\r
+ const char* s1,\r
+ const char* s2) {\r
+ if (!String::CaseInsensitiveCStringEquals(s1, s2)) {\r
+ return AssertionSuccess();\r
+ } else {\r
+ return AssertionFailure()\r
+ << "Expected: (" << s1_expression << ") != ("\r
+ << s2_expression << ") (ignoring case), actual: \""\r
+ << s1 << "\" vs \"" << s2 << "\"";\r
+ }\r
+}\r
+\r
+} // namespace internal\r
+\r
+namespace {\r
+\r
+// Helper functions for implementing IsSubString() and IsNotSubstring().\r
+\r
+// This group of overloaded functions return true iff needle is a\r
+// substring of haystack. NULL is considered a substring of itself\r
+// only.\r
+\r
+bool IsSubstringPred(const char* needle, const char* haystack) {\r
+ if (needle == NULL || haystack == NULL)\r
+ return needle == haystack;\r
+\r
+ return strstr(haystack, needle) != NULL;\r
+}\r
+\r
+bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {\r
+ if (needle == NULL || haystack == NULL)\r
+ return needle == haystack;\r
+\r
+ return wcsstr(haystack, needle) != NULL;\r
+}\r
+\r
+// StringType here can be either ::std::string or ::std::wstring.\r
+template <typename StringType>\r
+bool IsSubstringPred(const StringType& needle,\r
+ const StringType& haystack) {\r
+ return haystack.find(needle) != StringType::npos;\r
+}\r
+\r
+// This function implements either IsSubstring() or IsNotSubstring(),\r
+// depending on the value of the expected_to_be_substring parameter.\r
+// StringType here can be const char*, const wchar_t*, ::std::string,\r
+// or ::std::wstring.\r
+template <typename StringType>\r
+AssertionResult IsSubstringImpl(\r
+ bool expected_to_be_substring,\r
+ const char* needle_expr, const char* haystack_expr,\r
+ const StringType& needle, const StringType& haystack) {\r
+ if (IsSubstringPred(needle, haystack) == expected_to_be_substring)\r
+ return AssertionSuccess();\r
+\r
+ const bool is_wide_string = sizeof(needle[0]) > 1;\r
+ const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";\r
+ return AssertionFailure()\r
+ << "Value of: " << needle_expr << "\n"\r
+ << " Actual: " << begin_string_quote << needle << "\"\n"\r
+ << "Expected: " << (expected_to_be_substring ? "" : "not ")\r
+ << "a substring of " << haystack_expr << "\n"\r
+ << "Which is: " << begin_string_quote << haystack << "\"";\r
+}\r
+\r
+} // namespace\r
+\r
+// IsSubstring() and IsNotSubstring() check whether needle is a\r
+// substring of haystack (NULL is considered a substring of itself\r
+// only), and return an appropriate error message when they fail.\r
+\r
+AssertionResult IsSubstring(\r
+ const char* needle_expr, const char* haystack_expr,\r
+ const char* needle, const char* haystack) {\r
+ return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\r
+}\r
+\r
+AssertionResult IsSubstring(\r
+ const char* needle_expr, const char* haystack_expr,\r
+ const wchar_t* needle, const wchar_t* haystack) {\r
+ return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\r
+}\r
+\r
+AssertionResult IsNotSubstring(\r
+ const char* needle_expr, const char* haystack_expr,\r
+ const char* needle, const char* haystack) {\r
+ return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\r
+}\r
+\r
+AssertionResult IsNotSubstring(\r
+ const char* needle_expr, const char* haystack_expr,\r
+ const wchar_t* needle, const wchar_t* haystack) {\r
+ return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\r
+}\r
+\r
+AssertionResult IsSubstring(\r
+ const char* needle_expr, const char* haystack_expr,\r
+ const ::std::string& needle, const ::std::string& haystack) {\r
+ return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\r
+}\r
+\r
+AssertionResult IsNotSubstring(\r
+ const char* needle_expr, const char* haystack_expr,\r
+ const ::std::string& needle, const ::std::string& haystack) {\r
+ return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\r
+}\r
+\r
+#if GTEST_HAS_STD_WSTRING\r
+AssertionResult IsSubstring(\r
+ const char* needle_expr, const char* haystack_expr,\r
+ const ::std::wstring& needle, const ::std::wstring& haystack) {\r
+ return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\r
+}\r
+\r
+AssertionResult IsNotSubstring(\r
+ const char* needle_expr, const char* haystack_expr,\r
+ const ::std::wstring& needle, const ::std::wstring& haystack) {\r
+ return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\r
+}\r
+#endif // GTEST_HAS_STD_WSTRING\r
+\r
+namespace internal {\r
+\r
+#if GTEST_OS_WINDOWS\r
+\r
+namespace {\r
+\r
+// Helper function for IsHRESULT{SuccessFailure} predicates\r
+AssertionResult HRESULTFailureHelper(const char* expr,\r
+ const char* expected,\r
+ long hr) { // NOLINT\r
+# if GTEST_OS_WINDOWS_MOBILE\r
+\r
+ // Windows CE doesn't support FormatMessage.\r
+ const char error_text[] = "";\r
+\r
+# else\r
+\r
+ // Looks up the human-readable system message for the HRESULT code\r
+ // and since we're not passing any params to FormatMessage, we don't\r
+ // want inserts expanded.\r
+ const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |\r
+ FORMAT_MESSAGE_IGNORE_INSERTS;\r
+ const DWORD kBufSize = 4096;\r
+ // Gets the system's human readable message string for this HRESULT.\r
+ char error_text[kBufSize] = { '\0' };\r
+ DWORD message_length = ::FormatMessageA(kFlags,\r
+ 0, // no source, we're asking system\r
+ hr, // the error\r
+ 0, // no line width restrictions\r
+ error_text, // output buffer\r
+ kBufSize, // buf size\r
+ NULL); // no arguments for inserts\r
+ // Trims tailing white space (FormatMessage leaves a trailing CR-LF)\r
+ for (; message_length && IsSpace(error_text[message_length - 1]);\r
+ --message_length) {\r
+ error_text[message_length - 1] = '\0';\r
+ }\r
+\r
+# endif // GTEST_OS_WINDOWS_MOBILE\r
+\r
+ const std::string error_hex("0x" + String::FormatHexInt(hr));\r
+ return ::testing::AssertionFailure()\r
+ << "Expected: " << expr << " " << expected << ".\n"\r
+ << " Actual: " << error_hex << " " << error_text << "\n";\r
+}\r
+\r
+} // namespace\r
+\r
+AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT\r
+ if (SUCCEEDED(hr)) {\r
+ return AssertionSuccess();\r
+ }\r
+ return HRESULTFailureHelper(expr, "succeeds", hr);\r
+}\r
+\r
+AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT\r
+ if (FAILED(hr)) {\r
+ return AssertionSuccess();\r
+ }\r
+ return HRESULTFailureHelper(expr, "fails", hr);\r
+}\r
+\r
+#endif // GTEST_OS_WINDOWS\r
+\r
+// Utility functions for encoding Unicode text (wide strings) in\r
+// UTF-8.\r
+\r
+// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8\r
+// like this:\r
+//\r
+// Code-point length Encoding\r
+// 0 - 7 bits 0xxxxxxx\r
+// 8 - 11 bits 110xxxxx 10xxxxxx\r
+// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx\r
+// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\r
+\r
+// The maximum code-point a one-byte UTF-8 sequence can represent.\r
+const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;\r
+\r
+// The maximum code-point a two-byte UTF-8 sequence can represent.\r
+const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;\r
+\r
+// The maximum code-point a three-byte UTF-8 sequence can represent.\r
+const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;\r
+\r
+// The maximum code-point a four-byte UTF-8 sequence can represent.\r
+const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;\r
+\r
+// Chops off the n lowest bits from a bit pattern. Returns the n\r
+// lowest bits. As a side effect, the original bit pattern will be\r
+// shifted to the right by n bits.\r
+inline UInt32 ChopLowBits(UInt32* bits, int n) {\r
+ const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);\r
+ *bits >>= n;\r
+ return low_bits;\r
+}\r
+\r
+// Converts a Unicode code point to a narrow string in UTF-8 encoding.\r
+// code_point parameter is of type UInt32 because wchar_t may not be\r
+// wide enough to contain a code point.\r
+// If the code_point is not a valid Unicode code point\r
+// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted\r
+// to "(Invalid Unicode 0xXXXXXXXX)".\r
+std::string CodePointToUtf8(UInt32 code_point) {\r
+ if (code_point > kMaxCodePoint4) {\r
+ return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";\r
+ }\r
+\r
+ char str[5]; // Big enough for the largest valid code point.\r
+ if (code_point <= kMaxCodePoint1) {\r
+ str[1] = '\0';\r
+ str[0] = static_cast<char>(code_point); // 0xxxxxxx\r
+ } else if (code_point <= kMaxCodePoint2) {\r
+ str[2] = '\0';\r
+ str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\r
+ str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx\r
+ } else if (code_point <= kMaxCodePoint3) {\r
+ str[3] = '\0';\r
+ str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\r
+ str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\r
+ str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx\r
+ } else { // code_point <= kMaxCodePoint4\r
+ str[4] = '\0';\r
+ str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\r
+ str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\r
+ str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\r
+ str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx\r
+ }\r
+ return str;\r
+}\r
+\r
+// The following two functions only make sense if the the system\r
+// uses UTF-16 for wide string encoding. All supported systems\r
+// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.\r
+\r
+// Determines if the arguments constitute UTF-16 surrogate pair\r
+// and thus should be combined into a single Unicode code point\r
+// using CreateCodePointFromUtf16SurrogatePair.\r
+inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {\r
+ return sizeof(wchar_t) == 2 &&\r
+ (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;\r
+}\r
+\r
+// Creates a Unicode code point from UTF16 surrogate pair.\r
+inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,\r
+ wchar_t second) {\r
+ const UInt32 mask = (1 << 10) - 1;\r
+ return (sizeof(wchar_t) == 2) ?\r
+ (((first & mask) << 10) | (second & mask)) + 0x10000 :\r
+ // This function should not be called when the condition is\r
+ // false, but we provide a sensible default in case it is.\r
+ static_cast<UInt32>(first);\r
+}\r
+\r
+// Converts a wide string to a narrow string in UTF-8 encoding.\r
+// The wide string is assumed to have the following encoding:\r
+// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)\r
+// UTF-32 if sizeof(wchar_t) == 4 (on Linux)\r
+// Parameter str points to a null-terminated wide string.\r
+// Parameter num_chars may additionally limit the number\r
+// of wchar_t characters processed. -1 is used when the entire string\r
+// should be processed.\r
+// If the string contains code points that are not valid Unicode code points\r
+// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output\r
+// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding\r
+// and contains invalid UTF-16 surrogate pairs, values in those pairs\r
+// will be encoded as individual Unicode characters from Basic Normal Plane.\r
+std::string WideStringToUtf8(const wchar_t* str, int num_chars) {\r
+ if (num_chars == -1)\r
+ num_chars = static_cast<int>(wcslen(str));\r
+\r
+ ::std::stringstream stream;\r
+ for (int i = 0; i < num_chars; ++i) {\r
+ UInt32 unicode_code_point;\r
+\r
+ if (str[i] == L'\0') {\r
+ break;\r
+ } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {\r
+ unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],\r
+ str[i + 1]);\r
+ i++;\r
+ } else {\r
+ unicode_code_point = static_cast<UInt32>(str[i]);\r
+ }\r
+\r
+ stream << CodePointToUtf8(unicode_code_point);\r
+ }\r
+ return StringStreamToString(&stream);\r
+}\r
+\r
+// Converts a wide C string to an std::string using the UTF-8 encoding.\r
+// NULL will be converted to "(null)".\r
+std::string String::ShowWideCString(const wchar_t * wide_c_str) {\r
+ if (wide_c_str == NULL) return "(null)";\r
+\r
+ return internal::WideStringToUtf8(wide_c_str, -1);\r
+}\r
+\r
+// Compares two wide C strings. Returns true iff they have the same\r
+// content.\r
+//\r
+// Unlike wcscmp(), this function can handle NULL argument(s). A NULL\r
+// C string is considered different to any non-NULL C string,\r
+// including the empty string.\r
+bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {\r
+ if (lhs == NULL) return rhs == NULL;\r
+\r
+ if (rhs == NULL) return false;\r
+\r
+ return wcscmp(lhs, rhs) == 0;\r
+}\r
+\r
+// Helper function for *_STREQ on wide strings.\r
+AssertionResult CmpHelperSTREQ(const char* expected_expression,\r
+ const char* actual_expression,\r
+ const wchar_t* expected,\r
+ const wchar_t* actual) {\r
+ if (String::WideCStringEquals(expected, actual)) {\r
+ return AssertionSuccess();\r
+ }\r
+\r
+ return EqFailure(expected_expression,\r
+ actual_expression,\r
+ PrintToString(expected),\r
+ PrintToString(actual),\r
+ false);\r
+}\r
+\r
+// Helper function for *_STRNE on wide strings.\r
+AssertionResult CmpHelperSTRNE(const char* s1_expression,\r
+ const char* s2_expression,\r
+ const wchar_t* s1,\r
+ const wchar_t* s2) {\r
+ if (!String::WideCStringEquals(s1, s2)) {\r
+ return AssertionSuccess();\r
+ }\r
+\r
+ return AssertionFailure() << "Expected: (" << s1_expression << ") != ("\r
+ << s2_expression << "), actual: "\r
+ << PrintToString(s1)\r
+ << " vs " << PrintToString(s2);\r
+}\r
+\r
+// Compares two C strings, ignoring case. Returns true iff they have\r
+// the same content.\r
+//\r
+// Unlike strcasecmp(), this function can handle NULL argument(s). A\r
+// NULL C string is considered different to any non-NULL C string,\r
+// including the empty string.\r
+bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {\r
+ if (lhs == NULL)\r
+ return rhs == NULL;\r
+ if (rhs == NULL)\r
+ return false;\r
+ return posix::StrCaseCmp(lhs, rhs) == 0;\r
+}\r
+\r
+ // Compares two wide C strings, ignoring case. Returns true iff they\r
+ // have the same content.\r
+ //\r
+ // Unlike wcscasecmp(), this function can handle NULL argument(s).\r
+ // A NULL C string is considered different to any non-NULL wide C string,\r
+ // including the empty string.\r
+ // NB: The implementations on different platforms slightly differ.\r
+ // On windows, this method uses _wcsicmp which compares according to LC_CTYPE\r
+ // environment variable. On GNU platform this method uses wcscasecmp\r
+ // which compares according to LC_CTYPE category of the current locale.\r
+ // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the\r
+ // current locale.\r
+bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,\r
+ const wchar_t* rhs) {\r
+ if (lhs == NULL) return rhs == NULL;\r
+\r
+ if (rhs == NULL) return false;\r
+\r
+#if GTEST_OS_WINDOWS\r
+ return _wcsicmp(lhs, rhs) == 0;\r
+#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID\r
+ return wcscasecmp(lhs, rhs) == 0;\r
+#else\r
+ // Android, Mac OS X and Cygwin don't define wcscasecmp.\r
+ // Other unknown OSes may not define it either.\r
+ wint_t left, right;\r
+ do {\r
+ left = towlower(*lhs++);\r
+ right = towlower(*rhs++);\r
+ } while (left && left == right);\r
+ return left == right;\r
+#endif // OS selector\r
+}\r
+\r
+// Returns true iff str ends with the given suffix, ignoring case.\r
+// Any string is considered to end with an empty suffix.\r
+bool String::EndsWithCaseInsensitive(\r
+ const std::string& str, const std::string& suffix) {\r
+ const size_t str_len = str.length();\r
+ const size_t suffix_len = suffix.length();\r
+ return (str_len >= suffix_len) &&\r
+ CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,\r
+ suffix.c_str());\r
+}\r
+\r
+// Formats an int value as "%02d".\r
+std::string String::FormatIntWidth2(int value) {\r
+ std::stringstream ss;\r
+ ss << std::setfill('0') << std::setw(2) << value;\r
+ return ss.str();\r
+}\r
+\r
+// Formats an int value as "%X".\r
+std::string String::FormatHexInt(int value) {\r
+ std::stringstream ss;\r
+ ss << std::hex << std::uppercase << value;\r
+ return ss.str();\r
+}\r
+\r
+// Formats a byte as "%02X".\r
+std::string String::FormatByte(unsigned char value) {\r
+ std::stringstream ss;\r
+ ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase\r
+ << static_cast<unsigned int>(value);\r
+ return ss.str();\r
+}\r
+\r
+// Converts the buffer in a stringstream to an std::string, converting NUL\r
+// bytes to "\\0" along the way.\r
+std::string StringStreamToString(::std::stringstream* ss) {\r
+ const ::std::string& str = ss->str();\r
+ const char* const start = str.c_str();\r
+ const char* const end = start + str.length();\r
+\r
+ std::string result;\r
+ result.reserve(2 * (end - start));\r
+ for (const char* ch = start; ch != end; ++ch) {\r
+ if (*ch == '\0') {\r
+ result += "\\0"; // Replaces NUL with "\\0";\r
+ } else {\r
+ result += *ch;\r
+ }\r
+ }\r
+\r
+ return result;\r
+}\r
+\r
+// Appends the user-supplied message to the Google-Test-generated message.\r
+std::string AppendUserMessage(const std::string& gtest_msg,\r
+ const Message& user_msg) {\r
+ // Appends the user message if it's non-empty.\r
+ const std::string user_msg_string = user_msg.GetString();\r
+ if (user_msg_string.empty()) {\r
+ return gtest_msg;\r
+ }\r
+\r
+ return gtest_msg + "\n" + user_msg_string;\r
+}\r
+\r
+} // namespace internal\r
+\r
+// class TestResult\r
+\r
+// Creates an empty TestResult.\r
+TestResult::TestResult()\r
+ : death_test_count_(0),\r
+ elapsed_time_(0) {\r
+}\r
+\r
+// D'tor.\r
+TestResult::~TestResult() {\r
+}\r
+\r
+// Returns the i-th test part result among all the results. i can\r
+// range from 0 to total_part_count() - 1. If i is not in that range,\r
+// aborts the program.\r
+const TestPartResult& TestResult::GetTestPartResult(int i) const {\r
+ if (i < 0 || i >= total_part_count())\r
+ internal::posix::Abort();\r
+ return test_part_results_.at(i);\r
+}\r
+\r
+// Returns the i-th test property. i can range from 0 to\r
+// test_property_count() - 1. If i is not in that range, aborts the\r
+// program.\r
+const TestProperty& TestResult::GetTestProperty(int i) const {\r
+ if (i < 0 || i >= test_property_count())\r
+ internal::posix::Abort();\r
+ return test_properties_.at(i);\r
+}\r
+\r
+// Clears the test part results.\r
+void TestResult::ClearTestPartResults() {\r
+ test_part_results_.clear();\r
+}\r
+\r
+// Adds a test part result to the list.\r
+void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {\r
+ test_part_results_.push_back(test_part_result);\r
+}\r
+\r
+// Adds a test property to the list. If a property with the same key as the\r
+// supplied property is already represented, the value of this test_property\r
+// replaces the old value for that key.\r
+void TestResult::RecordProperty(const std::string& xml_element,\r
+ const TestProperty& test_property) {\r
+ if (!ValidateTestProperty(xml_element, test_property)) {\r
+ return;\r
+ }\r
+ internal::MutexLock lock(&test_properites_mutex_);\r
+ const std::vector<TestProperty>::iterator property_with_matching_key =\r
+ std::find_if(test_properties_.begin(), test_properties_.end(),\r
+ internal::TestPropertyKeyIs(test_property.key()));\r
+ if (property_with_matching_key == test_properties_.end()) {\r
+ test_properties_.push_back(test_property);\r
+ return;\r
+ }\r
+ property_with_matching_key->SetValue(test_property.value());\r
+}\r
+\r
+// The list of reserved attributes used in the <testsuites> element of XML\r
+// output.\r
+static const char* const kReservedTestSuitesAttributes[] = {\r
+ "disabled",\r
+ "errors",\r
+ "failures",\r
+ "name",\r
+ "random_seed",\r
+ "tests",\r
+ "time",\r
+ "timestamp"\r
+};\r
+\r
+// The list of reserved attributes used in the <testsuite> element of XML\r
+// output.\r
+static const char* const kReservedTestSuiteAttributes[] = {\r
+ "disabled",\r
+ "errors",\r
+ "failures",\r
+ "name",\r
+ "tests",\r
+ "time"\r
+};\r
+\r
+// The list of reserved attributes used in the <testcase> element of XML output.\r
+static const char* const kReservedTestCaseAttributes[] = {\r
+ "classname",\r
+ "name",\r
+ "status",\r
+ "time",\r
+ "type_param",\r
+ "value_param"\r
+};\r
+\r
+template <int kSize>\r
+std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {\r
+ return std::vector<std::string>(array, array + kSize);\r
+}\r
+\r
+static std::vector<std::string> GetReservedAttributesForElement(\r
+ const std::string& xml_element) {\r
+ if (xml_element == "testsuites") {\r
+ return ArrayAsVector(kReservedTestSuitesAttributes);\r
+ } else if (xml_element == "testsuite") {\r
+ return ArrayAsVector(kReservedTestSuiteAttributes);\r
+ } else if (xml_element == "testcase") {\r
+ return ArrayAsVector(kReservedTestCaseAttributes);\r
+ } else {\r
+ GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;\r
+ }\r
+ // This code is unreachable but some compilers may not realizes that.\r
+ return std::vector<std::string>();\r
+}\r
+\r
+static std::string FormatWordList(const std::vector<std::string>& words) {\r
+ Message word_list;\r
+ for (size_t i = 0; i < words.size(); ++i) {\r
+ if (i > 0 && words.size() > 2) {\r
+ word_list << ", ";\r
+ }\r
+ if (i == words.size() - 1) {\r
+ word_list << "and ";\r
+ }\r
+ word_list << "'" << words[i] << "'";\r
+ }\r
+ return word_list.GetString();\r
+}\r
+\r
+bool ValidateTestPropertyName(const std::string& property_name,\r
+ const std::vector<std::string>& reserved_names) {\r
+ if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=\r
+ reserved_names.end()) {\r
+ ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name\r
+ << " (" << FormatWordList(reserved_names)\r
+ << " are reserved by " << GTEST_NAME_ << ")";\r
+ return false;\r
+ }\r
+ return true;\r
+}\r
+\r
+// Adds a failure if the key is a reserved attribute of the element named\r
+// xml_element. Returns true if the property is valid.\r
+bool TestResult::ValidateTestProperty(const std::string& xml_element,\r
+ const TestProperty& test_property) {\r
+ return ValidateTestPropertyName(test_property.key(),\r
+ GetReservedAttributesForElement(xml_element));\r
+}\r
+\r
+// Clears the object.\r
+void TestResult::Clear() {\r
+ test_part_results_.clear();\r
+ test_properties_.clear();\r
+ death_test_count_ = 0;\r
+ elapsed_time_ = 0;\r
+}\r
+\r
+// Returns true iff the test failed.\r
+bool TestResult::Failed() const {\r
+ for (int i = 0; i < total_part_count(); ++i) {\r
+ if (GetTestPartResult(i).failed())\r
+ return true;\r
+ }\r
+ return false;\r
+}\r
+\r
+// Returns true iff the test part fatally failed.\r
+static bool TestPartFatallyFailed(const TestPartResult& result) {\r
+ return result.fatally_failed();\r
+}\r
+\r
+// Returns true iff the test fatally failed.\r
+bool TestResult::HasFatalFailure() const {\r
+ return CountIf(test_part_results_, TestPartFatallyFailed) > 0;\r
+}\r
+\r
+// Returns true iff the test part non-fatally failed.\r
+static bool TestPartNonfatallyFailed(const TestPartResult& result) {\r
+ return result.nonfatally_failed();\r
+}\r
+\r
+// Returns true iff the test has a non-fatal failure.\r
+bool TestResult::HasNonfatalFailure() const {\r
+ return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;\r
+}\r
+\r
+// Gets the number of all test parts. This is the sum of the number\r
+// of successful test parts and the number of failed test parts.\r
+int TestResult::total_part_count() const {\r
+ return static_cast<int>(test_part_results_.size());\r
+}\r
+\r
+// Returns the number of the test properties.\r
+int TestResult::test_property_count() const {\r
+ return static_cast<int>(test_properties_.size());\r
+}\r
+\r
+// class Test\r
+\r
+// Creates a Test object.\r
+\r
+// The c'tor saves the states of all flags.\r
+Test::Test()\r
+ : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {\r
+}\r
+\r
+// The d'tor restores the states of all flags. The actual work is\r
+// done by the d'tor of the gtest_flag_saver_ field, and thus not\r
+// visible here.\r
+Test::~Test() {\r
+}\r
+\r
+// Sets up the test fixture.\r
+//\r
+// A sub-class may override this.\r
+void Test::SetUp() {\r
+}\r
+\r
+// Tears down the test fixture.\r
+//\r
+// A sub-class may override this.\r
+void Test::TearDown() {\r
+}\r
+\r
+// Allows user supplied key value pairs to be recorded for later output.\r
+void Test::RecordProperty(const std::string& key, const std::string& value) {\r
+ UnitTest::GetInstance()->RecordProperty(key, value);\r
+}\r
+\r
+// Allows user supplied key value pairs to be recorded for later output.\r
+void Test::RecordProperty(const std::string& key, int value) {\r
+ Message value_message;\r
+ value_message << value;\r
+ RecordProperty(key, value_message.GetString().c_str());\r
+}\r
+\r
+namespace internal {\r
+\r
+void ReportFailureInUnknownLocation(TestPartResult::Type result_type,\r
+ const std::string& message) {\r
+ // This function is a friend of UnitTest and as such has access to\r
+ // AddTestPartResult.\r
+ UnitTest::GetInstance()->AddTestPartResult(\r
+ result_type,\r
+ NULL, // No info about the source file where the exception occurred.\r
+ -1, // We have no info on which line caused the exception.\r
+ message,\r
+ ""); // No stack trace, either.\r
+}\r
+\r
+} // namespace internal\r
+\r
+// Google Test requires all tests in the same test case to use the same test\r
+// fixture class. This function checks if the current test has the\r
+// same fixture class as the first test in the current test case. If\r
+// yes, it returns true; otherwise it generates a Google Test failure and\r
+// returns false.\r
+bool Test::HasSameFixtureClass() {\r
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\r
+ const TestCase* const test_case = impl->current_test_case();\r
+\r
+ // Info about the first test in the current test case.\r
+ const TestInfo* const first_test_info = test_case->test_info_list()[0];\r
+ const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;\r
+ const char* const first_test_name = first_test_info->name();\r
+\r
+ // Info about the current test.\r
+ const TestInfo* const this_test_info = impl->current_test_info();\r
+ const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;\r
+ const char* const this_test_name = this_test_info->name();\r
+\r
+ if (this_fixture_id != first_fixture_id) {\r
+ // Is the first test defined using TEST?\r
+ const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();\r
+ // Is this test defined using TEST?\r
+ const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();\r
+\r
+ if (first_is_TEST || this_is_TEST) {\r
+ // Both TEST and TEST_F appear in same test case, which is incorrect.\r
+ // Tell the user how to fix this.\r
+\r
+ // Gets the name of the TEST and the name of the TEST_F. Note\r
+ // that first_is_TEST and this_is_TEST cannot both be true, as\r
+ // the fixture IDs are different for the two tests.\r
+ const char* const TEST_name =\r
+ first_is_TEST ? first_test_name : this_test_name;\r
+ const char* const TEST_F_name =\r
+ first_is_TEST ? this_test_name : first_test_name;\r
+\r
+ ADD_FAILURE()\r
+ << "All tests in the same test case must use the same test fixture\n"\r
+ << "class, so mixing TEST_F and TEST in the same test case is\n"\r
+ << "illegal. In test case " << this_test_info->test_case_name()\r
+ << ",\n"\r
+ << "test " << TEST_F_name << " is defined using TEST_F but\n"\r
+ << "test " << TEST_name << " is defined using TEST. You probably\n"\r
+ << "want to change the TEST to TEST_F or move it to another test\n"\r
+ << "case.";\r
+ } else {\r
+ // Two fixture classes with the same name appear in two different\r
+ // namespaces, which is not allowed. Tell the user how to fix this.\r
+ ADD_FAILURE()\r
+ << "All tests in the same test case must use the same test fixture\n"\r
+ << "class. However, in test case "\r
+ << this_test_info->test_case_name() << ",\n"\r
+ << "you defined test " << first_test_name\r
+ << " and test " << this_test_name << "\n"\r
+ << "using two different test fixture classes. This can happen if\n"\r
+ << "the two classes are from different namespaces or translation\n"\r
+ << "units and have the same name. You should probably rename one\n"\r
+ << "of the classes to put the tests into different test cases.";\r
+ }\r
+ return false;\r
+ }\r
+\r
+ return true;\r
+}\r
+\r
+#if GTEST_HAS_SEH\r
+\r
+// Adds an "exception thrown" fatal failure to the current test. This\r
+// function returns its result via an output parameter pointer because VC++\r
+// prohibits creation of objects with destructors on stack in functions\r
+// using __try (see error C2712).\r
+static std::string* FormatSehExceptionMessage(DWORD exception_code,\r
+ const char* location) {\r
+ Message message;\r
+ message << "SEH exception with code 0x" << std::setbase(16) <<\r
+ exception_code << std::setbase(10) << " thrown in " << location << ".";\r
+\r
+ return new std::string(message.GetString());\r
+}\r
+\r
+#endif // GTEST_HAS_SEH\r
+\r
+namespace internal {\r
+\r
+#if GTEST_HAS_EXCEPTIONS\r
+\r
+// Adds an "exception thrown" fatal failure to the current test.\r
+static std::string FormatCxxExceptionMessage(const char* description,\r
+ const char* location) {\r
+ Message message;\r
+ if (description != NULL) {\r
+ message << "C++ exception with description \"" << description << "\"";\r
+ } else {\r
+ message << "Unknown C++ exception";\r
+ }\r
+ message << " thrown in " << location << ".";\r
+\r
+ return message.GetString();\r
+}\r
+\r
+static std::string PrintTestPartResultToString(\r
+ const TestPartResult& test_part_result);\r
+\r
+GoogleTestFailureException::GoogleTestFailureException(\r
+ const TestPartResult& failure)\r
+ : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}\r
+\r
+#endif // GTEST_HAS_EXCEPTIONS\r
+\r
+// We put these helper functions in the internal namespace as IBM's xlC\r
+// compiler rejects the code if they were declared static.\r
+\r
+// Runs the given method and handles SEH exceptions it throws, when\r
+// SEH is supported; returns the 0-value for type Result in case of an\r
+// SEH exception. (Microsoft compilers cannot handle SEH and C++\r
+// exceptions in the same function. Therefore, we provide a separate\r
+// wrapper function for handling SEH exceptions.)\r
+template <class T, typename Result>\r
+Result HandleSehExceptionsInMethodIfSupported(\r
+ T* object, Result (T::*method)(), const char* location) {\r
+#if GTEST_HAS_SEH\r
+ __try {\r
+ return (object->*method)();\r
+ } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT\r
+ GetExceptionCode())) {\r
+ // We create the exception message on the heap because VC++ prohibits\r
+ // creation of objects with destructors on stack in functions using __try\r
+ // (see error C2712).\r
+ std::string* exception_message = FormatSehExceptionMessage(\r
+ GetExceptionCode(), location);\r
+ internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,\r
+ *exception_message);\r
+ delete exception_message;\r
+ return static_cast<Result>(0);\r
+ }\r
+#else\r
+ (void)location;\r
+ return (object->*method)();\r
+#endif // GTEST_HAS_SEH\r
+}\r
+\r
+// Runs the given method and catches and reports C++ and/or SEH-style\r
+// exceptions, if they are supported; returns the 0-value for type\r
+// Result in case of an SEH exception.\r
+template <class T, typename Result>\r
+Result HandleExceptionsInMethodIfSupported(\r
+ T* object, Result (T::*method)(), const char* location) {\r
+ // NOTE: The user code can affect the way in which Google Test handles\r
+ // exceptions by setting GTEST_FLAG(catch_exceptions), but only before\r
+ // RUN_ALL_TESTS() starts. It is technically possible to check the flag\r
+ // after the exception is caught and either report or re-throw the\r
+ // exception based on the flag's value:\r
+ //\r
+ // try {\r
+ // // Perform the test method.\r
+ // } catch (...) {\r
+ // if (GTEST_FLAG(catch_exceptions))\r
+ // // Report the exception as failure.\r
+ // else\r
+ // throw; // Re-throws the original exception.\r
+ // }\r
+ //\r
+ // However, the purpose of this flag is to allow the program to drop into\r
+ // the debugger when the exception is thrown. On most platforms, once the\r
+ // control enters the catch block, the exception origin information is\r
+ // lost and the debugger will stop the program at the point of the\r
+ // re-throw in this function -- instead of at the point of the original\r
+ // throw statement in the code under test. For this reason, we perform\r
+ // the check early, sacrificing the ability to affect Google Test's\r
+ // exception handling in the method where the exception is thrown.\r
+ if (internal::GetUnitTestImpl()->catch_exceptions()) {\r
+#if GTEST_HAS_EXCEPTIONS\r
+ try {\r
+ return HandleSehExceptionsInMethodIfSupported(object, method, location);\r
+ } catch (const internal::GoogleTestFailureException&) { // NOLINT\r
+ // This exception type can only be thrown by a failed Google\r
+ // Test assertion with the intention of letting another testing\r
+ // framework catch it. Therefore we just re-throw it.\r
+ throw;\r
+ } catch (const std::exception& e) { // NOLINT\r
+ internal::ReportFailureInUnknownLocation(\r
+ TestPartResult::kFatalFailure,\r
+ FormatCxxExceptionMessage(e.what(), location));\r
+ } catch (...) { // NOLINT\r
+ internal::ReportFailureInUnknownLocation(\r
+ TestPartResult::kFatalFailure,\r
+ FormatCxxExceptionMessage(NULL, location));\r
+ }\r
+ return static_cast<Result>(0);\r
+#else\r
+ return HandleSehExceptionsInMethodIfSupported(object, method, location);\r
+#endif // GTEST_HAS_EXCEPTIONS\r
+ } else {\r
+ return (object->*method)();\r
+ }\r
+}\r
+\r
+} // namespace internal\r
+\r
+// Runs the test and updates the test result.\r
+void Test::Run() {\r
+ if (!HasSameFixtureClass()) return;\r
+\r
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\r
+ impl->os_stack_trace_getter()->UponLeavingGTest();\r
+ internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");\r
+ // We will run the test only if SetUp() was successful.\r
+ if (!HasFatalFailure()) {\r
+ impl->os_stack_trace_getter()->UponLeavingGTest();\r
+ internal::HandleExceptionsInMethodIfSupported(\r
+ this, &Test::TestBody, "the test body");\r
+ }\r
+\r
+ // However, we want to clean up as much as possible. Hence we will\r
+ // always call TearDown(), even if SetUp() or the test body has\r
+ // failed.\r
+ impl->os_stack_trace_getter()->UponLeavingGTest();\r
+ internal::HandleExceptionsInMethodIfSupported(\r
+ this, &Test::TearDown, "TearDown()");\r
+}\r
+\r
+// Returns true iff the current test has a fatal failure.\r
+bool Test::HasFatalFailure() {\r
+ return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();\r
+}\r
+\r
+// Returns true iff the current test has a non-fatal failure.\r
+bool Test::HasNonfatalFailure() {\r
+ return internal::GetUnitTestImpl()->current_test_result()->\r
+ HasNonfatalFailure();\r
+}\r
+\r
+// class TestInfo\r
+\r
+// Constructs a TestInfo object. It assumes ownership of the test factory\r
+// object.\r
+TestInfo::TestInfo(const std::string& a_test_case_name,\r
+ const std::string& a_name,\r
+ const char* a_type_param,\r
+ const char* a_value_param,\r
+ internal::CodeLocation a_code_location,\r
+ internal::TypeId fixture_class_id,\r
+ internal::TestFactoryBase* factory)\r
+ : test_case_name_(a_test_case_name),\r
+ name_(a_name),\r
+ type_param_(a_type_param ? new std::string(a_type_param) : NULL),\r
+ value_param_(a_value_param ? new std::string(a_value_param) : NULL),\r
+ location_(a_code_location),\r
+ fixture_class_id_(fixture_class_id),\r
+ should_run_(false),\r
+ is_disabled_(false),\r
+ matches_filter_(false),\r
+ factory_(factory),\r
+ result_() {}\r
+\r
+// Destructs a TestInfo object.\r
+TestInfo::~TestInfo() { delete factory_; }\r
+\r
+namespace internal {\r
+\r
+// Creates a new TestInfo object and registers it with Google Test;\r
+// returns the created object.\r
+//\r
+// Arguments:\r
+//\r
+// test_case_name: name of the test case\r
+// name: name of the test\r
+// type_param: the name of the test's type parameter, or NULL if\r
+// this is not a typed or a type-parameterized test.\r
+// value_param: text representation of the test's value parameter,\r
+// or NULL if this is not a value-parameterized test.\r
+// code_location: code location where the test is defined\r
+// fixture_class_id: ID of the test fixture class\r
+// set_up_tc: pointer to the function that sets up the test case\r
+// tear_down_tc: pointer to the function that tears down the test case\r
+// factory: pointer to the factory that creates a test object.\r
+// The newly created TestInfo instance will assume\r
+// ownership of the factory object.\r
+TestInfo* MakeAndRegisterTestInfo(\r
+ const char* test_case_name,\r
+ const char* name,\r
+ const char* type_param,\r
+ const char* value_param,\r
+ CodeLocation code_location,\r
+ TypeId fixture_class_id,\r
+ SetUpTestCaseFunc set_up_tc,\r
+ TearDownTestCaseFunc tear_down_tc,\r
+ TestFactoryBase* factory) {\r
+ TestInfo* const test_info =\r
+ new TestInfo(test_case_name, name, type_param, value_param,\r
+ code_location, fixture_class_id, factory);\r
+ GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);\r
+ return test_info;\r
+}\r
+\r
+#if GTEST_HAS_PARAM_TEST\r
+void ReportInvalidTestCaseType(const char* test_case_name,\r
+ CodeLocation code_location) {\r
+ Message errors;\r
+ errors\r
+ << "Attempted redefinition of test case " << test_case_name << ".\n"\r
+ << "All tests in the same test case must use the same test fixture\n"\r
+ << "class. However, in test case " << test_case_name << ", you tried\n"\r
+ << "to define a test using a fixture class different from the one\n"\r
+ << "used earlier. This can happen if the two fixture classes are\n"\r
+ << "from different namespaces and have the same name. You should\n"\r
+ << "probably rename one of the classes to put the tests into different\n"\r
+ << "test cases.";\r
+\r
+ fprintf(stderr, "%s %s",\r
+ FormatFileLocation(code_location.file.c_str(),\r
+ code_location.line).c_str(),\r
+ errors.GetString().c_str());\r
+}\r
+#endif // GTEST_HAS_PARAM_TEST\r
+\r
+} // namespace internal\r
+\r
+namespace {\r
+\r
+// A predicate that checks the test name of a TestInfo against a known\r
+// value.\r
+//\r
+// This is used for implementation of the TestCase class only. We put\r
+// it in the anonymous namespace to prevent polluting the outer\r
+// namespace.\r
+//\r
+// TestNameIs is copyable.\r
+class TestNameIs {\r
+ public:\r
+ // Constructor.\r
+ //\r
+ // TestNameIs has NO default constructor.\r
+ explicit TestNameIs(const char* name)\r
+ : name_(name) {}\r
+\r
+ // Returns true iff the test name of test_info matches name_.\r
+ bool operator()(const TestInfo * test_info) const {\r
+ return test_info && test_info->name() == name_;\r
+ }\r
+\r
+ private:\r
+ std::string name_;\r
+};\r
+\r
+} // namespace\r
+\r
+namespace internal {\r
+\r
+// This method expands all parameterized tests registered with macros TEST_P\r
+// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.\r
+// This will be done just once during the program runtime.\r
+void UnitTestImpl::RegisterParameterizedTests() {\r
+#if GTEST_HAS_PARAM_TEST\r
+ if (!parameterized_tests_registered_) {\r
+ parameterized_test_registry_.RegisterTests();\r
+ parameterized_tests_registered_ = true;\r
+ }\r
+#endif\r
+}\r
+\r
+} // namespace internal\r
+\r
+// Creates the test object, runs it, records its result, and then\r
+// deletes it.\r
+void TestInfo::Run() {\r
+ if (!should_run_) return;\r
+\r
+ // Tells UnitTest where to store test result.\r
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\r
+ impl->set_current_test_info(this);\r
+\r
+ TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\r
+\r
+ // Notifies the unit test event listeners that a test is about to start.\r
+ repeater->OnTestStart(*this);\r
+\r
+ const TimeInMillis start = internal::GetTimeInMillis();\r
+\r
+ impl->os_stack_trace_getter()->UponLeavingGTest();\r
+\r
+ // Creates the test object.\r
+ Test* const test = internal::HandleExceptionsInMethodIfSupported(\r
+ factory_, &internal::TestFactoryBase::CreateTest,\r
+ "the test fixture's constructor");\r
+\r
+ // Runs the test only if the test object was created and its\r
+ // constructor didn't generate a fatal failure.\r
+ if ((test != NULL) && !Test::HasFatalFailure()) {\r
+ // This doesn't throw as all user code that can throw are wrapped into\r
+ // exception handling code.\r
+ test->Run();\r
+ }\r
+\r
+ // Deletes the test object.\r
+ impl->os_stack_trace_getter()->UponLeavingGTest();\r
+ internal::HandleExceptionsInMethodIfSupported(\r
+ test, &Test::DeleteSelf_, "the test fixture's destructor");\r
+\r
+ result_.set_elapsed_time(internal::GetTimeInMillis() - start);\r
+\r
+ // Notifies the unit test event listener that a test has just finished.\r
+ repeater->OnTestEnd(*this);\r
+\r
+ // Tells UnitTest to stop associating assertion results to this\r
+ // test.\r
+ impl->set_current_test_info(NULL);\r
+}\r
+\r
+// class TestCase\r
+\r
+// Gets the number of successful tests in this test case.\r
+int TestCase::successful_test_count() const {\r
+ return CountIf(test_info_list_, TestPassed);\r
+}\r
+\r
+// Gets the number of failed tests in this test case.\r
+int TestCase::failed_test_count() const {\r
+ return CountIf(test_info_list_, TestFailed);\r
+}\r
+\r
+// Gets the number of disabled tests that will be reported in the XML report.\r
+int TestCase::reportable_disabled_test_count() const {\r
+ return CountIf(test_info_list_, TestReportableDisabled);\r
+}\r
+\r
+// Gets the number of disabled tests in this test case.\r
+int TestCase::disabled_test_count() const {\r
+ return CountIf(test_info_list_, TestDisabled);\r
+}\r
+\r
+// Gets the number of tests to be printed in the XML report.\r
+int TestCase::reportable_test_count() const {\r
+ return CountIf(test_info_list_, TestReportable);\r
+}\r
+\r
+// Get the number of tests in this test case that should run.\r
+int TestCase::test_to_run_count() const {\r
+ return CountIf(test_info_list_, ShouldRunTest);\r
+}\r
+\r
+// Gets the number of all tests.\r
+int TestCase::total_test_count() const {\r
+ return static_cast<int>(test_info_list_.size());\r
+}\r
+\r
+// Creates a TestCase with the given name.\r
+//\r
+// Arguments:\r
+//\r
+// name: name of the test case\r
+// a_type_param: the name of the test case's type parameter, or NULL if\r
+// this is not a typed or a type-parameterized test case.\r
+// set_up_tc: pointer to the function that sets up the test case\r
+// tear_down_tc: pointer to the function that tears down the test case\r
+TestCase::TestCase(const char* a_name, const char* a_type_param,\r
+ Test::SetUpTestCaseFunc set_up_tc,\r
+ Test::TearDownTestCaseFunc tear_down_tc)\r
+ : name_(a_name),\r
+ type_param_(a_type_param ? new std::string(a_type_param) : NULL),\r
+ set_up_tc_(set_up_tc),\r
+ tear_down_tc_(tear_down_tc),\r
+ should_run_(false),\r
+ elapsed_time_(0) {\r
+}\r
+\r
+// Destructor of TestCase.\r
+TestCase::~TestCase() {\r
+ // Deletes every Test in the collection.\r
+ ForEach(test_info_list_, internal::Delete<TestInfo>);\r
+}\r
+\r
+// Returns the i-th test among all the tests. i can range from 0 to\r
+// total_test_count() - 1. If i is not in that range, returns NULL.\r
+const TestInfo* TestCase::GetTestInfo(int i) const {\r
+ const int index = GetElementOr(test_indices_, i, -1);\r
+ return index < 0 ? NULL : test_info_list_[index];\r
+}\r
+\r
+// Returns the i-th test among all the tests. i can range from 0 to\r
+// total_test_count() - 1. If i is not in that range, returns NULL.\r
+TestInfo* TestCase::GetMutableTestInfo(int i) {\r
+ const int index = GetElementOr(test_indices_, i, -1);\r
+ return index < 0 ? NULL : test_info_list_[index];\r
+}\r
+\r
+// Adds a test to this test case. Will delete the test upon\r
+// destruction of the TestCase object.\r
+void TestCase::AddTestInfo(TestInfo * test_info) {\r
+ test_info_list_.push_back(test_info);\r
+ test_indices_.push_back(static_cast<int>(test_indices_.size()));\r
+}\r
+\r
+// Runs every test in this TestCase.\r
+void TestCase::Run() {\r
+ if (!should_run_) return;\r
+\r
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\r
+ impl->set_current_test_case(this);\r
+\r
+ TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\r
+\r
+ repeater->OnTestCaseStart(*this);\r
+ impl->os_stack_trace_getter()->UponLeavingGTest();\r
+ internal::HandleExceptionsInMethodIfSupported(\r
+ this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");\r
+\r
+ const internal::TimeInMillis start = internal::GetTimeInMillis();\r
+ for (int i = 0; i < total_test_count(); i++) {\r
+ GetMutableTestInfo(i)->Run();\r
+ }\r
+ elapsed_time_ = internal::GetTimeInMillis() - start;\r
+\r
+ impl->os_stack_trace_getter()->UponLeavingGTest();\r
+ internal::HandleExceptionsInMethodIfSupported(\r
+ this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");\r
+\r
+ repeater->OnTestCaseEnd(*this);\r
+ impl->set_current_test_case(NULL);\r
+}\r
+\r
+// Clears the results of all tests in this test case.\r
+void TestCase::ClearResult() {\r
+ ad_hoc_test_result_.Clear();\r
+ ForEach(test_info_list_, TestInfo::ClearTestResult);\r
+}\r
+\r
+// Shuffles the tests in this test case.\r
+void TestCase::ShuffleTests(internal::Random* random) {\r
+ Shuffle(random, &test_indices_);\r
+}\r
+\r
+// Restores the test order to before the first shuffle.\r
+void TestCase::UnshuffleTests() {\r
+ for (size_t i = 0; i < test_indices_.size(); i++) {\r
+ test_indices_[i] = static_cast<int>(i);\r
+ }\r
+}\r
+\r
+// Formats a countable noun. Depending on its quantity, either the\r
+// singular form or the plural form is used. e.g.\r
+//\r
+// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".\r
+// FormatCountableNoun(5, "book", "books") returns "5 books".\r
+static std::string FormatCountableNoun(int count,\r
+ const char * singular_form,\r
+ const char * plural_form) {\r
+ return internal::StreamableToString(count) + " " +\r
+ (count == 1 ? singular_form : plural_form);\r
+}\r
+\r
+// Formats the count of tests.\r
+static std::string FormatTestCount(int test_count) {\r
+ return FormatCountableNoun(test_count, "test", "tests");\r
+}\r
+\r
+// Formats the count of test cases.\r
+static std::string FormatTestCaseCount(int test_case_count) {\r
+ return FormatCountableNoun(test_case_count, "test case", "test cases");\r
+}\r
+\r
+// Converts a TestPartResult::Type enum to human-friendly string\r
+// representation. Both kNonFatalFailure and kFatalFailure are translated\r
+// to "Failure", as the user usually doesn't care about the difference\r
+// between the two when viewing the test result.\r
+static const char * TestPartResultTypeToString(TestPartResult::Type type) {\r
+ switch (type) {\r
+ case TestPartResult::kSuccess:\r
+ return "Success";\r
+\r
+ case TestPartResult::kNonFatalFailure:\r
+ case TestPartResult::kFatalFailure:\r
+#ifdef _MSC_VER\r
+ return "error: ";\r
+#else\r
+ return "Failure\n";\r
+#endif\r
+ default:\r
+ return "Unknown result type";\r
+ }\r
+}\r
+\r
+namespace internal {\r
+\r
+// Prints a TestPartResult to an std::string.\r
+static std::string PrintTestPartResultToString(\r
+ const TestPartResult& test_part_result) {\r
+ return (Message()\r
+ << internal::FormatFileLocation(test_part_result.file_name(),\r
+ test_part_result.line_number())\r
+ << " " << TestPartResultTypeToString(test_part_result.type())\r
+ << test_part_result.message()).GetString();\r
+}\r
+\r
+// Prints a TestPartResult.\r
+static void PrintTestPartResult(const TestPartResult& test_part_result) {\r
+ const std::string& result =\r
+ PrintTestPartResultToString(test_part_result);\r
+ printf("%s\n", result.c_str());\r
+ fflush(stdout);\r
+ // If the test program runs in Visual Studio or a debugger, the\r
+ // following statements add the test part result message to the Output\r
+ // window such that the user can double-click on it to jump to the\r
+ // corresponding source code location; otherwise they do nothing.\r
+#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\r
+ // We don't call OutputDebugString*() on Windows Mobile, as printing\r
+ // to stdout is done by OutputDebugString() there already - we don't\r
+ // want the same message printed twice.\r
+ ::OutputDebugStringA(result.c_str());\r
+ ::OutputDebugStringA("\n");\r
+#endif\r
+}\r
+\r
+// class PrettyUnitTestResultPrinter\r
+\r
+enum GTestColor {\r
+ COLOR_DEFAULT,\r
+ COLOR_RED,\r
+ COLOR_GREEN,\r
+ COLOR_YELLOW\r
+};\r
+\r
+#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \\r
+ !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\r
+\r
+// Returns the character attribute for the given color.\r
+WORD GetColorAttribute(GTestColor color) {\r
+ switch (color) {\r
+ case COLOR_RED: return FOREGROUND_RED;\r
+ case COLOR_GREEN: return FOREGROUND_GREEN;\r
+ case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;\r
+ default: return 0;\r
+ }\r
+}\r
+\r
+#else\r
+\r
+// Returns the ANSI color code for the given color. COLOR_DEFAULT is\r
+// an invalid input.\r
+const char* GetAnsiColorCode(GTestColor color) {\r
+ switch (color) {\r
+ case COLOR_RED: return "1";\r
+ case COLOR_GREEN: return "2";\r
+ case COLOR_YELLOW: return "3";\r
+ default: return NULL;\r
+ };\r
+}\r
+\r
+#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\r
+\r
+// Returns true iff Google Test should use colors in the output.\r
+bool ShouldUseColor(bool stdout_is_tty) {\r
+ const char* const gtest_color = GTEST_FLAG(color).c_str();\r
+\r
+ if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {\r
+#if GTEST_OS_WINDOWS\r
+ // On Windows the TERM variable is usually not set, but the\r
+ // console there does support colors.\r
+ return stdout_is_tty;\r
+#else\r
+ // On non-Windows platforms, we rely on the TERM variable.\r
+ const char* const term = posix::GetEnv("TERM");\r
+ const bool term_supports_color =\r
+ String::CStringEquals(term, "xterm") ||\r
+ String::CStringEquals(term, "xterm-color") ||\r
+ String::CStringEquals(term, "xterm-256color") ||\r
+ String::CStringEquals(term, "screen") ||\r
+ String::CStringEquals(term, "screen-256color") ||\r
+ String::CStringEquals(term, "rxvt-unicode") ||\r
+ String::CStringEquals(term, "rxvt-unicode-256color") ||\r
+ String::CStringEquals(term, "linux") ||\r
+ String::CStringEquals(term, "cygwin");\r
+ return stdout_is_tty && term_supports_color;\r
+#endif // GTEST_OS_WINDOWS\r
+ }\r
+\r
+ return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||\r
+ String::CaseInsensitiveCStringEquals(gtest_color, "true") ||\r
+ String::CaseInsensitiveCStringEquals(gtest_color, "t") ||\r
+ String::CStringEquals(gtest_color, "1");\r
+ // We take "yes", "true", "t", and "1" as meaning "yes". If the\r
+ // value is neither one of these nor "auto", we treat it as "no" to\r
+ // be conservative.\r
+}\r
+\r
+// Helpers for printing colored strings to stdout. Note that on Windows, we\r
+// cannot simply emit special characters and have the terminal change colors.\r
+// This routine must actually emit the characters rather than return a string\r
+// that would be colored when printed, as can be done on Linux.\r
+void ColoredPrintf(GTestColor color, const char* fmt, ...) {\r
+ va_list args;\r
+ va_start(args, fmt);\r
+\r
+#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \\r
+ GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT\r
+ const bool use_color = AlwaysFalse();\r
+#else\r
+ static const bool in_color_mode =\r
+ ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);\r
+ const bool use_color = in_color_mode && (color != COLOR_DEFAULT);\r
+#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS\r
+ // The '!= 0' comparison is necessary to satisfy MSVC 7.1.\r
+\r
+ if (!use_color) {\r
+ vprintf(fmt, args);\r
+ va_end(args);\r
+ return;\r
+ }\r
+\r
+#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \\r
+ !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\r
+ const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);\r
+\r
+ // Gets the current text color.\r
+ CONSOLE_SCREEN_BUFFER_INFO buffer_info;\r
+ GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);\r
+ const WORD old_color_attrs = buffer_info.wAttributes;\r
+\r
+ // We need to flush the stream buffers into the console before each\r
+ // SetConsoleTextAttribute call lest it affect the text that is already\r
+ // printed but has not yet reached the console.\r
+ fflush(stdout);\r
+ SetConsoleTextAttribute(stdout_handle,\r
+ GetColorAttribute(color) | FOREGROUND_INTENSITY);\r
+ vprintf(fmt, args);\r
+\r
+ fflush(stdout);\r
+ // Restores the text color.\r
+ SetConsoleTextAttribute(stdout_handle, old_color_attrs);\r
+#else\r
+ printf("\033[0;3%sm", GetAnsiColorCode(color));\r
+ vprintf(fmt, args);\r
+ printf("\033[m"); // Resets the terminal to default.\r
+#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\r
+ va_end(args);\r
+}\r
+\r
+// Text printed in Google Test's text output and --gunit_list_tests\r
+// output to label the type parameter and value parameter for a test.\r
+static const char kTypeParamLabel[] = "TypeParam";\r
+static const char kValueParamLabel[] = "GetParam()";\r
+\r
+void PrintFullTestCommentIfPresent(const TestInfo& test_info) {\r
+ const char* const type_param = test_info.type_param();\r
+ const char* const value_param = test_info.value_param();\r
+\r
+ if (type_param != NULL || value_param != NULL) {\r
+ printf(", where ");\r
+ if (type_param != NULL) {\r
+ printf("%s = %s", kTypeParamLabel, type_param);\r
+ if (value_param != NULL)\r
+ printf(" and ");\r
+ }\r
+ if (value_param != NULL) {\r
+ printf("%s = %s", kValueParamLabel, value_param);\r
+ }\r
+ }\r
+}\r
+\r
+// This class implements the TestEventListener interface.\r
+//\r
+// Class PrettyUnitTestResultPrinter is copyable.\r
+class PrettyUnitTestResultPrinter : public TestEventListener {\r
+ public:\r
+ PrettyUnitTestResultPrinter() {}\r
+ static void PrintTestName(const char * test_case, const char * test) {\r
+ printf("%s.%s", test_case, test);\r
+ }\r
+\r
+ // The following methods override what's in the TestEventListener class.\r
+ virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}\r
+ virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);\r
+ virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);\r
+ virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}\r
+ virtual void OnTestCaseStart(const TestCase& test_case);\r
+ virtual void OnTestStart(const TestInfo& test_info);\r
+ virtual void OnTestPartResult(const TestPartResult& result);\r
+ virtual void OnTestEnd(const TestInfo& test_info);\r
+ virtual void OnTestCaseEnd(const TestCase& test_case);\r
+ virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);\r
+ virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}\r
+ virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);\r
+ virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}\r
+\r
+ private:\r
+ static void PrintFailedTests(const UnitTest& unit_test);\r
+};\r
+\r
+ // Fired before each iteration of tests starts.\r
+void PrettyUnitTestResultPrinter::OnTestIterationStart(\r
+ const UnitTest& unit_test, int iteration) {\r
+ if (GTEST_FLAG(repeat) != 1)\r
+ printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);\r
+\r
+ const char* const filter = GTEST_FLAG(filter).c_str();\r
+\r
+ // Prints the filter if it's not *. This reminds the user that some\r
+ // tests may be skipped.\r
+ if (!String::CStringEquals(filter, kUniversalFilter)) {\r
+ ColoredPrintf(COLOR_YELLOW,\r
+ "Note: %s filter = %s\n", GTEST_NAME_, filter);\r
+ }\r
+\r
+ if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {\r
+ const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);\r
+ ColoredPrintf(COLOR_YELLOW,\r
+ "Note: This is test shard %d of %s.\n",\r
+ static_cast<int>(shard_index) + 1,\r
+ internal::posix::GetEnv(kTestTotalShards));\r
+ }\r
+\r
+ if (GTEST_FLAG(shuffle)) {\r
+ ColoredPrintf(COLOR_YELLOW,\r
+ "Note: Randomizing tests' orders with a seed of %d .\n",\r
+ unit_test.random_seed());\r
+ }\r
+\r
+ ColoredPrintf(COLOR_GREEN, "[==========] ");\r
+ printf("Running %s from %s.\n",\r
+ FormatTestCount(unit_test.test_to_run_count()).c_str(),\r
+ FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());\r
+ fflush(stdout);\r
+}\r
+\r
+void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(\r
+ const UnitTest& /*unit_test*/) {\r
+ ColoredPrintf(COLOR_GREEN, "[----------] ");\r
+ printf("Global test environment set-up.\n");\r
+ fflush(stdout);\r
+}\r
+\r
+void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {\r
+ const std::string counts =\r
+ FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");\r
+ ColoredPrintf(COLOR_GREEN, "[----------] ");\r
+ printf("%s from %s", counts.c_str(), test_case.name());\r
+ if (test_case.type_param() == NULL) {\r
+ printf("\n");\r
+ } else {\r
+ printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());\r
+ }\r
+ fflush(stdout);\r
+}\r
+\r
+void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {\r
+ ColoredPrintf(COLOR_GREEN, "[ RUN ] ");\r
+ PrintTestName(test_info.test_case_name(), test_info.name());\r
+ printf("\n");\r
+ fflush(stdout);\r
+}\r
+\r
+// Called after an assertion failure.\r
+void PrettyUnitTestResultPrinter::OnTestPartResult(\r
+ const TestPartResult& result) {\r
+ // If the test part succeeded, we don't need to do anything.\r
+ if (result.type() == TestPartResult::kSuccess)\r
+ return;\r
+\r
+ // Print failure message from the assertion (e.g. expected this and got that).\r
+ PrintTestPartResult(result);\r
+ fflush(stdout);\r
+}\r
+\r
+void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {\r
+ if (test_info.result()->Passed()) {\r
+ ColoredPrintf(COLOR_GREEN, "[ OK ] ");\r
+ } else {\r
+ ColoredPrintf(COLOR_RED, "[ FAILED ] ");\r
+ }\r
+ PrintTestName(test_info.test_case_name(), test_info.name());\r
+ if (test_info.result()->Failed())\r
+ PrintFullTestCommentIfPresent(test_info);\r
+\r
+ if (GTEST_FLAG(print_time)) {\r
+ printf(" (%s ms)\n", internal::StreamableToString(\r
+ test_info.result()->elapsed_time()).c_str());\r
+ } else {\r
+ printf("\n");\r
+ }\r
+ fflush(stdout);\r
+}\r
+\r
+void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {\r
+ if (!GTEST_FLAG(print_time)) return;\r
+\r
+ const std::string counts =\r
+ FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");\r
+ ColoredPrintf(COLOR_GREEN, "[----------] ");\r
+ printf("%s from %s (%s ms total)\n\n",\r
+ counts.c_str(), test_case.name(),\r
+ internal::StreamableToString(test_case.elapsed_time()).c_str());\r
+ fflush(stdout);\r
+}\r
+\r
+void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(\r
+ const UnitTest& /*unit_test*/) {\r
+ ColoredPrintf(COLOR_GREEN, "[----------] ");\r
+ printf("Global test environment tear-down\n");\r
+ fflush(stdout);\r
+}\r
+\r
+// Internal helper for printing the list of failed tests.\r
+void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {\r
+ const int failed_test_count = unit_test.failed_test_count();\r
+ if (failed_test_count == 0) {\r
+ return;\r
+ }\r
+\r
+ for (int i = 0; i < unit_test.total_test_case_count(); ++i) {\r
+ const TestCase& test_case = *unit_test.GetTestCase(i);\r
+ if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {\r
+ continue;\r
+ }\r
+ for (int j = 0; j < test_case.total_test_count(); ++j) {\r
+ const TestInfo& test_info = *test_case.GetTestInfo(j);\r
+ if (!test_info.should_run() || test_info.result()->Passed()) {\r
+ continue;\r
+ }\r
+ ColoredPrintf(COLOR_RED, "[ FAILED ] ");\r
+ printf("%s.%s", test_case.name(), test_info.name());\r
+ PrintFullTestCommentIfPresent(test_info);\r
+ printf("\n");\r
+ }\r
+ }\r
+}\r
+\r
+void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\r
+ int /*iteration*/) {\r
+ ColoredPrintf(COLOR_GREEN, "[==========] ");\r
+ printf("%s from %s ran.",\r
+ FormatTestCount(unit_test.test_to_run_count()).c_str(),\r
+ FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());\r
+ if (GTEST_FLAG(print_time)) {\r
+ printf(" (%s ms total)",\r
+ internal::StreamableToString(unit_test.elapsed_time()).c_str());\r
+ }\r
+ printf("\n");\r
+ ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");\r
+ printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());\r
+\r
+ int num_failures = unit_test.failed_test_count();\r
+ if (!unit_test.Passed()) {\r
+ const int failed_test_count = unit_test.failed_test_count();\r
+ ColoredPrintf(COLOR_RED, "[ FAILED ] ");\r
+ printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());\r
+ PrintFailedTests(unit_test);\r
+ printf("\n%2d FAILED %s\n", num_failures,\r
+ num_failures == 1 ? "TEST" : "TESTS");\r
+ }\r
+\r
+ int num_disabled = unit_test.reportable_disabled_test_count();\r
+ if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {\r
+ if (!num_failures) {\r
+ printf("\n"); // Add a spacer if no FAILURE banner is displayed.\r
+ }\r
+ ColoredPrintf(COLOR_YELLOW,\r
+ " YOU HAVE %d DISABLED %s\n\n",\r
+ num_disabled,\r
+ num_disabled == 1 ? "TEST" : "TESTS");\r
+ }\r
+ // Ensure that Google Test output is printed before, e.g., heapchecker output.\r
+ fflush(stdout);\r
+}\r
+\r
+// End PrettyUnitTestResultPrinter\r
+\r
+// class TestEventRepeater\r
+//\r
+// This class forwards events to other event listeners.\r
+class TestEventRepeater : public TestEventListener {\r
+ public:\r
+ TestEventRepeater() : forwarding_enabled_(true) {}\r
+ virtual ~TestEventRepeater();\r
+ void Append(TestEventListener *listener);\r
+ TestEventListener* Release(TestEventListener* listener);\r
+\r
+ // Controls whether events will be forwarded to listeners_. Set to false\r
+ // in death test child processes.\r
+ bool forwarding_enabled() const { return forwarding_enabled_; }\r
+ void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }\r
+\r
+ virtual void OnTestProgramStart(const UnitTest& unit_test);\r
+ virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);\r
+ virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);\r
+ virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);\r
+ virtual void OnTestCaseStart(const TestCase& test_case);\r
+ virtual void OnTestStart(const TestInfo& test_info);\r
+ virtual void OnTestPartResult(const TestPartResult& result);\r
+ virtual void OnTestEnd(const TestInfo& test_info);\r
+ virtual void OnTestCaseEnd(const TestCase& test_case);\r
+ virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);\r
+ virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);\r
+ virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);\r
+ virtual void OnTestProgramEnd(const UnitTest& unit_test);\r
+\r
+ private:\r
+ // Controls whether events will be forwarded to listeners_. Set to false\r
+ // in death test child processes.\r
+ bool forwarding_enabled_;\r
+ // The list of listeners that receive events.\r
+ std::vector<TestEventListener*> listeners_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);\r
+};\r
+\r
+TestEventRepeater::~TestEventRepeater() {\r
+ ForEach(listeners_, Delete<TestEventListener>);\r
+}\r
+\r
+void TestEventRepeater::Append(TestEventListener *listener) {\r
+ listeners_.push_back(listener);\r
+}\r
+\r
+// TODO(vladl@google.com): Factor the search functionality into Vector::Find.\r
+TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {\r
+ for (size_t i = 0; i < listeners_.size(); ++i) {\r
+ if (listeners_[i] == listener) {\r
+ listeners_.erase(listeners_.begin() + i);\r
+ return listener;\r
+ }\r
+ }\r
+\r
+ return NULL;\r
+}\r
+\r
+// Since most methods are very similar, use macros to reduce boilerplate.\r
+// This defines a member that forwards the call to all listeners.\r
+#define GTEST_REPEATER_METHOD_(Name, Type) \\r
+void TestEventRepeater::Name(const Type& parameter) { \\r
+ if (forwarding_enabled_) { \\r
+ for (size_t i = 0; i < listeners_.size(); i++) { \\r
+ listeners_[i]->Name(parameter); \\r
+ } \\r
+ } \\r
+}\r
+// This defines a member that forwards the call to all listeners in reverse\r
+// order.\r
+#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \\r
+void TestEventRepeater::Name(const Type& parameter) { \\r
+ if (forwarding_enabled_) { \\r
+ for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \\r
+ listeners_[i]->Name(parameter); \\r
+ } \\r
+ } \\r
+}\r
+\r
+GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)\r
+GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)\r
+GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)\r
+GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)\r
+GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)\r
+GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)\r
+GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)\r
+GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)\r
+GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)\r
+GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)\r
+GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)\r
+\r
+#undef GTEST_REPEATER_METHOD_\r
+#undef GTEST_REVERSE_REPEATER_METHOD_\r
+\r
+void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,\r
+ int iteration) {\r
+ if (forwarding_enabled_) {\r
+ for (size_t i = 0; i < listeners_.size(); i++) {\r
+ listeners_[i]->OnTestIterationStart(unit_test, iteration);\r
+ }\r
+ }\r
+}\r
+\r
+void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,\r
+ int iteration) {\r
+ if (forwarding_enabled_) {\r
+ for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {\r
+ listeners_[i]->OnTestIterationEnd(unit_test, iteration);\r
+ }\r
+ }\r
+}\r
+\r
+// End TestEventRepeater\r
+\r
+// This class generates an XML output file.\r
+class XmlUnitTestResultPrinter : public EmptyTestEventListener {\r
+ public:\r
+ explicit XmlUnitTestResultPrinter(const char* output_file);\r
+\r
+ virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);\r
+\r
+ private:\r
+ // Is c a whitespace character that is normalized to a space character\r
+ // when it appears in an XML attribute value?\r
+ static bool IsNormalizableWhitespace(char c) {\r
+ return c == 0x9 || c == 0xA || c == 0xD;\r
+ }\r
+\r
+ // May c appear in a well-formed XML document?\r
+ static bool IsValidXmlCharacter(char c) {\r
+ return IsNormalizableWhitespace(c) || c >= 0x20;\r
+ }\r
+\r
+ // Returns an XML-escaped copy of the input string str. If\r
+ // is_attribute is true, the text is meant to appear as an attribute\r
+ // value, and normalizable whitespace is preserved by replacing it\r
+ // with character references.\r
+ static std::string EscapeXml(const std::string& str, bool is_attribute);\r
+\r
+ // Returns the given string with all characters invalid in XML removed.\r
+ static std::string RemoveInvalidXmlCharacters(const std::string& str);\r
+\r
+ // Convenience wrapper around EscapeXml when str is an attribute value.\r
+ static std::string EscapeXmlAttribute(const std::string& str) {\r
+ return EscapeXml(str, true);\r
+ }\r
+\r
+ // Convenience wrapper around EscapeXml when str is not an attribute value.\r
+ static std::string EscapeXmlText(const char* str) {\r
+ return EscapeXml(str, false);\r
+ }\r
+\r
+ // Verifies that the given attribute belongs to the given element and\r
+ // streams the attribute as XML.\r
+ static void OutputXmlAttribute(std::ostream* stream,\r
+ const std::string& element_name,\r
+ const std::string& name,\r
+ const std::string& value);\r
+\r
+ // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.\r
+ static void OutputXmlCDataSection(::std::ostream* stream, const char* data);\r
+\r
+ // Streams an XML representation of a TestInfo object.\r
+ static void OutputXmlTestInfo(::std::ostream* stream,\r
+ const char* test_case_name,\r
+ const TestInfo& test_info);\r
+\r
+ // Prints an XML representation of a TestCase object\r
+ static void PrintXmlTestCase(::std::ostream* stream,\r
+ const TestCase& test_case);\r
+\r
+ // Prints an XML summary of unit_test to output stream out.\r
+ static void PrintXmlUnitTest(::std::ostream* stream,\r
+ const UnitTest& unit_test);\r
+\r
+ // Produces a string representing the test properties in a result as space\r
+ // delimited XML attributes based on the property key="value" pairs.\r
+ // When the std::string is not empty, it includes a space at the beginning,\r
+ // to delimit this attribute from prior attributes.\r
+ static std::string TestPropertiesAsXmlAttributes(const TestResult& result);\r
+\r
+ // The output file.\r
+ const std::string output_file_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);\r
+};\r
+\r
+// Creates a new XmlUnitTestResultPrinter.\r
+XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)\r
+ : output_file_(output_file) {\r
+ if (output_file_.c_str() == NULL || output_file_.empty()) {\r
+ fprintf(stderr, "XML output file may not be null\n");\r
+ fflush(stderr);\r
+ exit(EXIT_FAILURE);\r
+ }\r
+}\r
+\r
+// Called after the unit test ends.\r
+void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\r
+ int /*iteration*/) {\r
+ FILE* xmlout = NULL;\r
+ FilePath output_file(output_file_);\r
+ FilePath output_dir(output_file.RemoveFileName());\r
+\r
+ if (output_dir.CreateDirectoriesRecursively()) {\r
+ xmlout = posix::FOpen(output_file_.c_str(), "w");\r
+ }\r
+ if (xmlout == NULL) {\r
+ // TODO(wan): report the reason of the failure.\r
+ //\r
+ // We don't do it for now as:\r
+ //\r
+ // 1. There is no urgent need for it.\r
+ // 2. It's a bit involved to make the errno variable thread-safe on\r
+ // all three operating systems (Linux, Windows, and Mac OS).\r
+ // 3. To interpret the meaning of errno in a thread-safe way,\r
+ // we need the strerror_r() function, which is not available on\r
+ // Windows.\r
+ fprintf(stderr,\r
+ "Unable to open file \"%s\"\n",\r
+ output_file_.c_str());\r
+ fflush(stderr);\r
+ exit(EXIT_FAILURE);\r
+ }\r
+ std::stringstream stream;\r
+ PrintXmlUnitTest(&stream, unit_test);\r
+ fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());\r
+ fclose(xmlout);\r
+}\r
+\r
+// Returns an XML-escaped copy of the input string str. If is_attribute\r
+// is true, the text is meant to appear as an attribute value, and\r
+// normalizable whitespace is preserved by replacing it with character\r
+// references.\r
+//\r
+// Invalid XML characters in str, if any, are stripped from the output.\r
+// It is expected that most, if not all, of the text processed by this\r
+// module will consist of ordinary English text.\r
+// If this module is ever modified to produce version 1.1 XML output,\r
+// most invalid characters can be retained using character references.\r
+// TODO(wan): It might be nice to have a minimally invasive, human-readable\r
+// escaping scheme for invalid characters, rather than dropping them.\r
+std::string XmlUnitTestResultPrinter::EscapeXml(\r
+ const std::string& str, bool is_attribute) {\r
+ Message m;\r
+\r
+ for (size_t i = 0; i < str.size(); ++i) {\r
+ const char ch = str[i];\r
+ switch (ch) {\r
+ case '<':\r
+ m << "<";\r
+ break;\r
+ case '>':\r
+ m << ">";\r
+ break;\r
+ case '&':\r
+ m << "&";\r
+ break;\r
+ case '\'':\r
+ if (is_attribute)\r
+ m << "'";\r
+ else\r
+ m << '\'';\r
+ break;\r
+ case '"':\r
+ if (is_attribute)\r
+ m << """;\r
+ else\r
+ m << '"';\r
+ break;\r
+ default:\r
+ if (IsValidXmlCharacter(ch)) {\r
+ if (is_attribute && IsNormalizableWhitespace(ch))\r
+ m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))\r
+ << ";";\r
+ else\r
+ m << ch;\r
+ }\r
+ break;\r
+ }\r
+ }\r
+\r
+ return m.GetString();\r
+}\r
+\r
+// Returns the given string with all characters invalid in XML removed.\r
+// Currently invalid characters are dropped from the string. An\r
+// alternative is to replace them with certain characters such as . or ?.\r
+std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(\r
+ const std::string& str) {\r
+ std::string output;\r
+ output.reserve(str.size());\r
+ for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)\r
+ if (IsValidXmlCharacter(*it))\r
+ output.push_back(*it);\r
+\r
+ return output;\r
+}\r
+\r
+// The following routines generate an XML representation of a UnitTest\r
+// object.\r
+//\r
+// This is how Google Test concepts map to the DTD:\r
+//\r
+// <testsuites name="AllTests"> <-- corresponds to a UnitTest object\r
+// <testsuite name="testcase-name"> <-- corresponds to a TestCase object\r
+// <testcase name="test-name"> <-- corresponds to a TestInfo object\r
+// <failure message="...">...</failure>\r
+// <failure message="...">...</failure>\r
+// <failure message="...">...</failure>\r
+// <-- individual assertion failures\r
+// </testcase>\r
+// </testsuite>\r
+// </testsuites>\r
+\r
+// Formats the given time in milliseconds as seconds.\r
+std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {\r
+ ::std::stringstream ss;\r
+ ss << (static_cast<double>(ms) * 1e-3);\r
+ return ss.str();\r
+}\r
+\r
+static bool PortableLocaltime(time_t seconds, struct tm* out) {\r
+#if defined(_MSC_VER)\r
+ return localtime_s(out, &seconds) == 0;\r
+#elif defined(__MINGW32__) || defined(__MINGW64__)\r
+ // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses\r
+ // Windows' localtime(), which has a thread-local tm buffer.\r
+ struct tm* tm_ptr = localtime(&seconds); // NOLINT\r
+ if (tm_ptr == NULL)\r
+ return false;\r
+ *out = *tm_ptr;\r
+ return true;\r
+#else\r
+ return localtime_r(&seconds, out) != NULL;\r
+#endif\r
+}\r
+\r
+// Converts the given epoch time in milliseconds to a date string in the ISO\r
+// 8601 format, without the timezone information.\r
+std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {\r
+ struct tm time_struct;\r
+ if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))\r
+ return "";\r
+ // YYYY-MM-DDThh:mm:ss\r
+ return StreamableToString(time_struct.tm_year + 1900) + "-" +\r
+ String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +\r
+ String::FormatIntWidth2(time_struct.tm_mday) + "T" +\r
+ String::FormatIntWidth2(time_struct.tm_hour) + ":" +\r
+ String::FormatIntWidth2(time_struct.tm_min) + ":" +\r
+ String::FormatIntWidth2(time_struct.tm_sec);\r
+}\r
+\r
+// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.\r
+void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,\r
+ const char* data) {\r
+ const char* segment = data;\r
+ *stream << "<![CDATA[";\r
+ for (;;) {\r
+ const char* const next_segment = strstr(segment, "]]>");\r
+ if (next_segment != NULL) {\r
+ stream->write(\r
+ segment, static_cast<std::streamsize>(next_segment - segment));\r
+ *stream << "]]>]]><![CDATA[";\r
+ segment = next_segment + strlen("]]>");\r
+ } else {\r
+ *stream << segment;\r
+ break;\r
+ }\r
+ }\r
+ *stream << "]]>";\r
+}\r
+\r
+void XmlUnitTestResultPrinter::OutputXmlAttribute(\r
+ std::ostream* stream,\r
+ const std::string& element_name,\r
+ const std::string& name,\r
+ const std::string& value) {\r
+ const std::vector<std::string>& allowed_names =\r
+ GetReservedAttributesForElement(element_name);\r
+\r
+ GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=\r
+ allowed_names.end())\r
+ << "Attribute " << name << " is not allowed for element <" << element_name\r
+ << ">.";\r
+\r
+ *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";\r
+}\r
+\r
+// Prints an XML representation of a TestInfo object.\r
+// TODO(wan): There is also value in printing properties with the plain printer.\r
+void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,\r
+ const char* test_case_name,\r
+ const TestInfo& test_info) {\r
+ const TestResult& result = *test_info.result();\r
+ const std::string kTestcase = "testcase";\r
+\r
+ *stream << " <testcase";\r
+ OutputXmlAttribute(stream, kTestcase, "name", test_info.name());\r
+\r
+ if (test_info.value_param() != NULL) {\r
+ OutputXmlAttribute(stream, kTestcase, "value_param",\r
+ test_info.value_param());\r
+ }\r
+ if (test_info.type_param() != NULL) {\r
+ OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());\r
+ }\r
+\r
+ OutputXmlAttribute(stream, kTestcase, "status",\r
+ test_info.should_run() ? "run" : "notrun");\r
+ OutputXmlAttribute(stream, kTestcase, "time",\r
+ FormatTimeInMillisAsSeconds(result.elapsed_time()));\r
+ OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);\r
+ *stream << TestPropertiesAsXmlAttributes(result);\r
+\r
+ int failures = 0;\r
+ for (int i = 0; i < result.total_part_count(); ++i) {\r
+ const TestPartResult& part = result.GetTestPartResult(i);\r
+ if (part.failed()) {\r
+ if (++failures == 1) {\r
+ *stream << ">\n";\r
+ }\r
+ const string location = internal::FormatCompilerIndependentFileLocation(\r
+ part.file_name(), part.line_number());\r
+ const string summary = location + "\n" + part.summary();\r
+ *stream << " <failure message=\""\r
+ << EscapeXmlAttribute(summary.c_str())\r
+ << "\" type=\"\">";\r
+ const string detail = location + "\n" + part.message();\r
+ OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());\r
+ *stream << "</failure>\n";\r
+ }\r
+ }\r
+\r
+ if (failures == 0)\r
+ *stream << " />\n";\r
+ else\r
+ *stream << " </testcase>\n";\r
+}\r
+\r
+// Prints an XML representation of a TestCase object\r
+void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,\r
+ const TestCase& test_case) {\r
+ const std::string kTestsuite = "testsuite";\r
+ *stream << " <" << kTestsuite;\r
+ OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());\r
+ OutputXmlAttribute(stream, kTestsuite, "tests",\r
+ StreamableToString(test_case.reportable_test_count()));\r
+ OutputXmlAttribute(stream, kTestsuite, "failures",\r
+ StreamableToString(test_case.failed_test_count()));\r
+ OutputXmlAttribute(\r
+ stream, kTestsuite, "disabled",\r
+ StreamableToString(test_case.reportable_disabled_test_count()));\r
+ OutputXmlAttribute(stream, kTestsuite, "errors", "0");\r
+ OutputXmlAttribute(stream, kTestsuite, "time",\r
+ FormatTimeInMillisAsSeconds(test_case.elapsed_time()));\r
+ *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())\r
+ << ">\n";\r
+\r
+ for (int i = 0; i < test_case.total_test_count(); ++i) {\r
+ if (test_case.GetTestInfo(i)->is_reportable())\r
+ OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));\r
+ }\r
+ *stream << " </" << kTestsuite << ">\n";\r
+}\r
+\r
+// Prints an XML summary of unit_test to output stream out.\r
+void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,\r
+ const UnitTest& unit_test) {\r
+ const std::string kTestsuites = "testsuites";\r
+\r
+ *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";\r
+ *stream << "<" << kTestsuites;\r
+\r
+ OutputXmlAttribute(stream, kTestsuites, "tests",\r
+ StreamableToString(unit_test.reportable_test_count()));\r
+ OutputXmlAttribute(stream, kTestsuites, "failures",\r
+ StreamableToString(unit_test.failed_test_count()));\r
+ OutputXmlAttribute(\r
+ stream, kTestsuites, "disabled",\r
+ StreamableToString(unit_test.reportable_disabled_test_count()));\r
+ OutputXmlAttribute(stream, kTestsuites, "errors", "0");\r
+ OutputXmlAttribute(\r
+ stream, kTestsuites, "timestamp",\r
+ FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));\r
+ OutputXmlAttribute(stream, kTestsuites, "time",\r
+ FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));\r
+\r
+ if (GTEST_FLAG(shuffle)) {\r
+ OutputXmlAttribute(stream, kTestsuites, "random_seed",\r
+ StreamableToString(unit_test.random_seed()));\r
+ }\r
+\r
+ *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());\r
+\r
+ OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");\r
+ *stream << ">\n";\r
+\r
+ for (int i = 0; i < unit_test.total_test_case_count(); ++i) {\r
+ if (unit_test.GetTestCase(i)->reportable_test_count() > 0)\r
+ PrintXmlTestCase(stream, *unit_test.GetTestCase(i));\r
+ }\r
+ *stream << "</" << kTestsuites << ">\n";\r
+}\r
+\r
+// Produces a string representing the test properties in a result as space\r
+// delimited XML attributes based on the property key="value" pairs.\r
+std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(\r
+ const TestResult& result) {\r
+ Message attributes;\r
+ for (int i = 0; i < result.test_property_count(); ++i) {\r
+ const TestProperty& property = result.GetTestProperty(i);\r
+ attributes << " " << property.key() << "="\r
+ << "\"" << EscapeXmlAttribute(property.value()) << "\"";\r
+ }\r
+ return attributes.GetString();\r
+}\r
+\r
+// End XmlUnitTestResultPrinter\r
+\r
+#if GTEST_CAN_STREAM_RESULTS_\r
+\r
+// Checks if str contains '=', '&', '%' or '\n' characters. If yes,\r
+// replaces them by "%xx" where xx is their hexadecimal value. For\r
+// example, replaces "=" with "%3D". This algorithm is O(strlen(str))\r
+// in both time and space -- important as the input str may contain an\r
+// arbitrarily long test failure message and stack trace.\r
+string StreamingListener::UrlEncode(const char* str) {\r
+ string result;\r
+ result.reserve(strlen(str) + 1);\r
+ for (char ch = *str; ch != '\0'; ch = *++str) {\r
+ switch (ch) {\r
+ case '%':\r
+ case '=':\r
+ case '&':\r
+ case '\n':\r
+ result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));\r
+ break;\r
+ default:\r
+ result.push_back(ch);\r
+ break;\r
+ }\r
+ }\r
+ return result;\r
+}\r
+\r
+void StreamingListener::SocketWriter::MakeConnection() {\r
+ GTEST_CHECK_(sockfd_ == -1)\r
+ << "MakeConnection() can't be called when there is already a connection.";\r
+\r
+ addrinfo hints;\r
+ memset(&hints, 0, sizeof(hints));\r
+ hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.\r
+ hints.ai_socktype = SOCK_STREAM;\r
+ addrinfo* servinfo = NULL;\r
+\r
+ // Use the getaddrinfo() to get a linked list of IP addresses for\r
+ // the given host name.\r
+ const int error_num = getaddrinfo(\r
+ host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);\r
+ if (error_num != 0) {\r
+ GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "\r
+ << gai_strerror(error_num);\r
+ }\r
+\r
+ // Loop through all the results and connect to the first we can.\r
+ for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;\r
+ cur_addr = cur_addr->ai_next) {\r
+ sockfd_ = socket(\r
+ cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);\r
+ if (sockfd_ != -1) {\r
+ // Connect the client socket to the server socket.\r
+ if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {\r
+ close(sockfd_);\r
+ sockfd_ = -1;\r
+ }\r
+ }\r
+ }\r
+\r
+ freeaddrinfo(servinfo); // all done with this structure\r
+\r
+ if (sockfd_ == -1) {\r
+ GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "\r
+ << host_name_ << ":" << port_num_;\r
+ }\r
+}\r
+\r
+// End of class Streaming Listener\r
+#endif // GTEST_CAN_STREAM_RESULTS__\r
+\r
+// Class ScopedTrace\r
+\r
+// Pushes the given source file location and message onto a per-thread\r
+// trace stack maintained by Google Test.\r
+ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)\r
+ GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {\r
+ TraceInfo trace;\r
+ trace.file = file;\r
+ trace.line = line;\r
+ trace.message = message.GetString();\r
+\r
+ UnitTest::GetInstance()->PushGTestTrace(trace);\r
+}\r
+\r
+// Pops the info pushed by the c'tor.\r
+ScopedTrace::~ScopedTrace()\r
+ GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {\r
+ UnitTest::GetInstance()->PopGTestTrace();\r
+}\r
+\r
+\r
+// class OsStackTraceGetter\r
+\r
+const char* const OsStackTraceGetterInterface::kElidedFramesMarker =\r
+ "... " GTEST_NAME_ " internal frames ...";\r
+\r
+string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/,\r
+ int /*skip_count*/) {\r
+ return "";\r
+}\r
+\r
+void OsStackTraceGetter::UponLeavingGTest() {}\r
+\r
+// A helper class that creates the premature-exit file in its\r
+// constructor and deletes the file in its destructor.\r
+class ScopedPrematureExitFile {\r
+ public:\r
+ explicit ScopedPrematureExitFile(const char* premature_exit_filepath)\r
+ : premature_exit_filepath_(premature_exit_filepath) {\r
+ // If a path to the premature-exit file is specified...\r
+ if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {\r
+ // create the file with a single "0" character in it. I/O\r
+ // errors are ignored as there's nothing better we can do and we\r
+ // don't want to fail the test because of this.\r
+ FILE* pfile = posix::FOpen(premature_exit_filepath, "w");\r
+ fwrite("0", 1, 1, pfile);\r
+ fclose(pfile);\r
+ }\r
+ }\r
+\r
+ ~ScopedPrematureExitFile() {\r
+ if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {\r
+ remove(premature_exit_filepath_);\r
+ }\r
+ }\r
+\r
+ private:\r
+ const char* const premature_exit_filepath_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);\r
+};\r
+\r
+} // namespace internal\r
+\r
+// class TestEventListeners\r
+\r
+TestEventListeners::TestEventListeners()\r
+ : repeater_(new internal::TestEventRepeater()),\r
+ default_result_printer_(NULL),\r
+ default_xml_generator_(NULL) {\r
+}\r
+\r
+TestEventListeners::~TestEventListeners() { delete repeater_; }\r
+\r
+// Returns the standard listener responsible for the default console\r
+// output. Can be removed from the listeners list to shut down default\r
+// console output. Note that removing this object from the listener list\r
+// with Release transfers its ownership to the user.\r
+void TestEventListeners::Append(TestEventListener* listener) {\r
+ repeater_->Append(listener);\r
+}\r
+\r
+// Removes the given event listener from the list and returns it. It then\r
+// becomes the caller's responsibility to delete the listener. Returns\r
+// NULL if the listener is not found in the list.\r
+TestEventListener* TestEventListeners::Release(TestEventListener* listener) {\r
+ if (listener == default_result_printer_)\r
+ default_result_printer_ = NULL;\r
+ else if (listener == default_xml_generator_)\r
+ default_xml_generator_ = NULL;\r
+ return repeater_->Release(listener);\r
+}\r
+\r
+// Returns repeater that broadcasts the TestEventListener events to all\r
+// subscribers.\r
+TestEventListener* TestEventListeners::repeater() { return repeater_; }\r
+\r
+// Sets the default_result_printer attribute to the provided listener.\r
+// The listener is also added to the listener list and previous\r
+// default_result_printer is removed from it and deleted. The listener can\r
+// also be NULL in which case it will not be added to the list. Does\r
+// nothing if the previous and the current listener objects are the same.\r
+void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {\r
+ if (default_result_printer_ != listener) {\r
+ // It is an error to pass this method a listener that is already in the\r
+ // list.\r
+ delete Release(default_result_printer_);\r
+ default_result_printer_ = listener;\r
+ if (listener != NULL)\r
+ Append(listener);\r
+ }\r
+}\r
+\r
+// Sets the default_xml_generator attribute to the provided listener. The\r
+// listener is also added to the listener list and previous\r
+// default_xml_generator is removed from it and deleted. The listener can\r
+// also be NULL in which case it will not be added to the list. Does\r
+// nothing if the previous and the current listener objects are the same.\r
+void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {\r
+ if (default_xml_generator_ != listener) {\r
+ // It is an error to pass this method a listener that is already in the\r
+ // list.\r
+ delete Release(default_xml_generator_);\r
+ default_xml_generator_ = listener;\r
+ if (listener != NULL)\r
+ Append(listener);\r
+ }\r
+}\r
+\r
+// Controls whether events will be forwarded by the repeater to the\r
+// listeners in the list.\r
+bool TestEventListeners::EventForwardingEnabled() const {\r
+ return repeater_->forwarding_enabled();\r
+}\r
+\r
+void TestEventListeners::SuppressEventForwarding() {\r
+ repeater_->set_forwarding_enabled(false);\r
+}\r
+\r
+// class UnitTest\r
+\r
+// Gets the singleton UnitTest object. The first time this method is\r
+// called, a UnitTest object is constructed and returned. Consecutive\r
+// calls will return the same object.\r
+//\r
+// We don't protect this under mutex_ as a user is not supposed to\r
+// call this before main() starts, from which point on the return\r
+// value will never change.\r
+UnitTest* UnitTest::GetInstance() {\r
+ // When compiled with MSVC 7.1 in optimized mode, destroying the\r
+ // UnitTest object upon exiting the program messes up the exit code,\r
+ // causing successful tests to appear failed. We have to use a\r
+ // different implementation in this case to bypass the compiler bug.\r
+ // This implementation makes the compiler happy, at the cost of\r
+ // leaking the UnitTest object.\r
+\r
+ // CodeGear C++Builder insists on a public destructor for the\r
+ // default implementation. Use this implementation to keep good OO\r
+ // design with private destructor.\r
+\r
+#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)\r
+ static UnitTest* const instance = new UnitTest;\r
+ return instance;\r
+#else\r
+ static UnitTest instance;\r
+ return &instance;\r
+#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)\r
+}\r
+\r
+// Gets the number of successful test cases.\r
+int UnitTest::successful_test_case_count() const {\r
+ return impl()->successful_test_case_count();\r
+}\r
+\r
+// Gets the number of failed test cases.\r
+int UnitTest::failed_test_case_count() const {\r
+ return impl()->failed_test_case_count();\r
+}\r
+\r
+// Gets the number of all test cases.\r
+int UnitTest::total_test_case_count() const {\r
+ return impl()->total_test_case_count();\r
+}\r
+\r
+// Gets the number of all test cases that contain at least one test\r
+// that should run.\r
+int UnitTest::test_case_to_run_count() const {\r
+ return impl()->test_case_to_run_count();\r
+}\r
+\r
+// Gets the number of successful tests.\r
+int UnitTest::successful_test_count() const {\r
+ return impl()->successful_test_count();\r
+}\r
+\r
+// Gets the number of failed tests.\r
+int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }\r
+\r
+// Gets the number of disabled tests that will be reported in the XML report.\r
+int UnitTest::reportable_disabled_test_count() const {\r
+ return impl()->reportable_disabled_test_count();\r
+}\r
+\r
+// Gets the number of disabled tests.\r
+int UnitTest::disabled_test_count() const {\r
+ return impl()->disabled_test_count();\r
+}\r
+\r
+// Gets the number of tests to be printed in the XML report.\r
+int UnitTest::reportable_test_count() const {\r
+ return impl()->reportable_test_count();\r
+}\r
+\r
+// Gets the number of all tests.\r
+int UnitTest::total_test_count() const { return impl()->total_test_count(); }\r
+\r
+// Gets the number of tests that should run.\r
+int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }\r
+\r
+// Gets the time of the test program start, in ms from the start of the\r
+// UNIX epoch.\r
+internal::TimeInMillis UnitTest::start_timestamp() const {\r
+ return impl()->start_timestamp();\r
+}\r
+\r
+// Gets the elapsed time, in milliseconds.\r
+internal::TimeInMillis UnitTest::elapsed_time() const {\r
+ return impl()->elapsed_time();\r
+}\r
+\r
+// Returns true iff the unit test passed (i.e. all test cases passed).\r
+bool UnitTest::Passed() const { return impl()->Passed(); }\r
+\r
+// Returns true iff the unit test failed (i.e. some test case failed\r
+// or something outside of all tests failed).\r
+bool UnitTest::Failed() const { return impl()->Failed(); }\r
+\r
+// Gets the i-th test case among all the test cases. i can range from 0 to\r
+// total_test_case_count() - 1. If i is not in that range, returns NULL.\r
+const TestCase* UnitTest::GetTestCase(int i) const {\r
+ return impl()->GetTestCase(i);\r
+}\r
+\r
+// Returns the TestResult containing information on test failures and\r
+// properties logged outside of individual test cases.\r
+const TestResult& UnitTest::ad_hoc_test_result() const {\r
+ return *impl()->ad_hoc_test_result();\r
+}\r
+\r
+// Gets the i-th test case among all the test cases. i can range from 0 to\r
+// total_test_case_count() - 1. If i is not in that range, returns NULL.\r
+TestCase* UnitTest::GetMutableTestCase(int i) {\r
+ return impl()->GetMutableTestCase(i);\r
+}\r
+\r
+// Returns the list of event listeners that can be used to track events\r
+// inside Google Test.\r
+TestEventListeners& UnitTest::listeners() {\r
+ return *impl()->listeners();\r
+}\r
+\r
+// Registers and returns a global test environment. When a test\r
+// program is run, all global test environments will be set-up in the\r
+// order they were registered. After all tests in the program have\r
+// finished, all global test environments will be torn-down in the\r
+// *reverse* order they were registered.\r
+//\r
+// The UnitTest object takes ownership of the given environment.\r
+//\r
+// We don't protect this under mutex_, as we only support calling it\r
+// from the main thread.\r
+Environment* UnitTest::AddEnvironment(Environment* env) {\r
+ if (env == NULL) {\r
+ return NULL;\r
+ }\r
+\r
+ impl_->environments().push_back(env);\r
+ return env;\r
+}\r
+\r
+// Adds a TestPartResult to the current TestResult object. All Google Test\r
+// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call\r
+// this to report their results. The user code should use the\r
+// assertion macros instead of calling this directly.\r
+void UnitTest::AddTestPartResult(\r
+ TestPartResult::Type result_type,\r
+ const char* file_name,\r
+ int line_number,\r
+ const std::string& message,\r
+ const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {\r
+ Message msg;\r
+ msg << message;\r
+\r
+ internal::MutexLock lock(&mutex_);\r
+ if (impl_->gtest_trace_stack().size() > 0) {\r
+ msg << "\n" << GTEST_NAME_ << " trace:";\r
+\r
+ for (int i = static_cast<int>(impl_->gtest_trace_stack().size());\r
+ i > 0; --i) {\r
+ const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];\r
+ msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)\r
+ << " " << trace.message;\r
+ }\r
+ }\r
+\r
+ if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {\r
+ msg << internal::kStackTraceMarker << os_stack_trace;\r
+ }\r
+\r
+ const TestPartResult result =\r
+ TestPartResult(result_type, file_name, line_number,\r
+ msg.GetString().c_str());\r
+ impl_->GetTestPartResultReporterForCurrentThread()->\r
+ ReportTestPartResult(result);\r
+\r
+ if (result_type != TestPartResult::kSuccess) {\r
+ // gtest_break_on_failure takes precedence over\r
+ // gtest_throw_on_failure. This allows a user to set the latter\r
+ // in the code (perhaps in order to use Google Test assertions\r
+ // with another testing framework) and specify the former on the\r
+ // command line for debugging.\r
+ if (GTEST_FLAG(break_on_failure)) {\r
+#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\r
+ // Using DebugBreak on Windows allows gtest to still break into a debugger\r
+ // when a failure happens and both the --gtest_break_on_failure and\r
+ // the --gtest_catch_exceptions flags are specified.\r
+ DebugBreak();\r
+#else\r
+ // Dereference NULL through a volatile pointer to prevent the compiler\r
+ // from removing. We use this rather than abort() or __builtin_trap() for\r
+ // portability: Symbian doesn't implement abort() well, and some debuggers\r
+ // don't correctly trap abort().\r
+ *static_cast<volatile int*>(NULL) = 1;\r
+#endif // GTEST_OS_WINDOWS\r
+ } else if (GTEST_FLAG(throw_on_failure)) {\r
+#if GTEST_HAS_EXCEPTIONS\r
+ throw internal::GoogleTestFailureException(result);\r
+#else\r
+ // We cannot call abort() as it generates a pop-up in debug mode\r
+ // that cannot be suppressed in VC 7.1 or below.\r
+ exit(1);\r
+#endif\r
+ }\r
+ }\r
+}\r
+\r
+// Adds a TestProperty to the current TestResult object when invoked from\r
+// inside a test, to current TestCase's ad_hoc_test_result_ when invoked\r
+// from SetUpTestCase or TearDownTestCase, or to the global property set\r
+// when invoked elsewhere. If the result already contains a property with\r
+// the same key, the value will be updated.\r
+void UnitTest::RecordProperty(const std::string& key,\r
+ const std::string& value) {\r
+ impl_->RecordProperty(TestProperty(key, value));\r
+}\r
+\r
+// Runs all tests in this UnitTest object and prints the result.\r
+// Returns 0 if successful, or 1 otherwise.\r
+//\r
+// We don't protect this under mutex_, as we only support calling it\r
+// from the main thread.\r
+int UnitTest::Run() {\r
+ const bool in_death_test_child_process =\r
+ internal::GTEST_FLAG(internal_run_death_test).length() > 0;\r
+\r
+ // Google Test implements this protocol for catching that a test\r
+ // program exits before returning control to Google Test:\r
+ //\r
+ // 1. Upon start, Google Test creates a file whose absolute path\r
+ // is specified by the environment variable\r
+ // TEST_PREMATURE_EXIT_FILE.\r
+ // 2. When Google Test has finished its work, it deletes the file.\r
+ //\r
+ // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before\r
+ // running a Google-Test-based test program and check the existence\r
+ // of the file at the end of the test execution to see if it has\r
+ // exited prematurely.\r
+\r
+ // If we are in the child process of a death test, don't\r
+ // create/delete the premature exit file, as doing so is unnecessary\r
+ // and will confuse the parent process. Otherwise, create/delete\r
+ // the file upon entering/leaving this function. If the program\r
+ // somehow exits before this function has a chance to return, the\r
+ // premature-exit file will be left undeleted, causing a test runner\r
+ // that understands the premature-exit-file protocol to report the\r
+ // test as having failed.\r
+ const internal::ScopedPrematureExitFile premature_exit_file(\r
+ in_death_test_child_process ?\r
+ NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));\r
+\r
+ // Captures the value of GTEST_FLAG(catch_exceptions). This value will be\r
+ // used for the duration of the program.\r
+ impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));\r
+\r
+#if GTEST_HAS_SEH\r
+ // Either the user wants Google Test to catch exceptions thrown by the\r
+ // tests or this is executing in the context of death test child\r
+ // process. In either case the user does not want to see pop-up dialogs\r
+ // about crashes - they are expected.\r
+ if (impl()->catch_exceptions() || in_death_test_child_process) {\r
+# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\r
+ // SetErrorMode doesn't exist on CE.\r
+ SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |\r
+ SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);\r
+# endif // !GTEST_OS_WINDOWS_MOBILE\r
+\r
+# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE\r
+ // Death test children can be terminated with _abort(). On Windows,\r
+ // _abort() can show a dialog with a warning message. This forces the\r
+ // abort message to go to stderr instead.\r
+ _set_error_mode(_OUT_TO_STDERR);\r
+# endif\r
+\r
+# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE\r
+ // In the debug version, Visual Studio pops up a separate dialog\r
+ // offering a choice to debug the aborted program. We need to suppress\r
+ // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement\r
+ // executed. Google Test will notify the user of any unexpected\r
+ // failure via stderr.\r
+ //\r
+ // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.\r
+ // Users of prior VC versions shall suffer the agony and pain of\r
+ // clicking through the countless debug dialogs.\r
+ // TODO(vladl@google.com): find a way to suppress the abort dialog() in the\r
+ // debug mode when compiled with VC 7.1 or lower.\r
+ if (!GTEST_FLAG(break_on_failure))\r
+ _set_abort_behavior(\r
+ 0x0, // Clear the following flags:\r
+ _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.\r
+# endif\r
+ }\r
+#endif // GTEST_HAS_SEH\r
+\r
+ return internal::HandleExceptionsInMethodIfSupported(\r
+ impl(),\r
+ &internal::UnitTestImpl::RunAllTests,\r
+ "auxiliary test code (environments or event listeners)") ? 0 : 1;\r
+}\r
+\r
+// Returns the working directory when the first TEST() or TEST_F() was\r
+// executed.\r
+const char* UnitTest::original_working_dir() const {\r
+ return impl_->original_working_dir_.c_str();\r
+}\r
+\r
+// Returns the TestCase object for the test that's currently running,\r
+// or NULL if no test is running.\r
+const TestCase* UnitTest::current_test_case() const\r
+ GTEST_LOCK_EXCLUDED_(mutex_) {\r
+ internal::MutexLock lock(&mutex_);\r
+ return impl_->current_test_case();\r
+}\r
+\r
+// Returns the TestInfo object for the test that's currently running,\r
+// or NULL if no test is running.\r
+const TestInfo* UnitTest::current_test_info() const\r
+ GTEST_LOCK_EXCLUDED_(mutex_) {\r
+ internal::MutexLock lock(&mutex_);\r
+ return impl_->current_test_info();\r
+}\r
+\r
+// Returns the random seed used at the start of the current test run.\r
+int UnitTest::random_seed() const { return impl_->random_seed(); }\r
+\r
+#if GTEST_HAS_PARAM_TEST\r
+// Returns ParameterizedTestCaseRegistry object used to keep track of\r
+// value-parameterized tests and instantiate and register them.\r
+internal::ParameterizedTestCaseRegistry&\r
+ UnitTest::parameterized_test_registry()\r
+ GTEST_LOCK_EXCLUDED_(mutex_) {\r
+ return impl_->parameterized_test_registry();\r
+}\r
+#endif // GTEST_HAS_PARAM_TEST\r
+\r
+// Creates an empty UnitTest.\r
+UnitTest::UnitTest() {\r
+ impl_ = new internal::UnitTestImpl(this);\r
+}\r
+\r
+// Destructor of UnitTest.\r
+UnitTest::~UnitTest() {\r
+ delete impl_;\r
+}\r
+\r
+// Pushes a trace defined by SCOPED_TRACE() on to the per-thread\r
+// Google Test trace stack.\r
+void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)\r
+ GTEST_LOCK_EXCLUDED_(mutex_) {\r
+ internal::MutexLock lock(&mutex_);\r
+ impl_->gtest_trace_stack().push_back(trace);\r
+}\r
+\r
+// Pops a trace from the per-thread Google Test trace stack.\r
+void UnitTest::PopGTestTrace()\r
+ GTEST_LOCK_EXCLUDED_(mutex_) {\r
+ internal::MutexLock lock(&mutex_);\r
+ impl_->gtest_trace_stack().pop_back();\r
+}\r
+\r
+namespace internal {\r
+\r
+UnitTestImpl::UnitTestImpl(UnitTest* parent)\r
+ : parent_(parent),\r
+ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)\r
+ default_global_test_part_result_reporter_(this),\r
+ default_per_thread_test_part_result_reporter_(this),\r
+ GTEST_DISABLE_MSC_WARNINGS_POP_()\r
+ global_test_part_result_repoter_(\r
+ &default_global_test_part_result_reporter_),\r
+ per_thread_test_part_result_reporter_(\r
+ &default_per_thread_test_part_result_reporter_),\r
+#if GTEST_HAS_PARAM_TEST\r
+ parameterized_test_registry_(),\r
+ parameterized_tests_registered_(false),\r
+#endif // GTEST_HAS_PARAM_TEST\r
+ last_death_test_case_(-1),\r
+ current_test_case_(NULL),\r
+ current_test_info_(NULL),\r
+ ad_hoc_test_result_(),\r
+ os_stack_trace_getter_(NULL),\r
+ post_flag_parse_init_performed_(false),\r
+ random_seed_(0), // Will be overridden by the flag before first use.\r
+ random_(0), // Will be reseeded before first use.\r
+ start_timestamp_(0),\r
+ elapsed_time_(0),\r
+#if GTEST_HAS_DEATH_TEST\r
+ death_test_factory_(new DefaultDeathTestFactory),\r
+#endif\r
+ // Will be overridden by the flag before first use.\r
+ catch_exceptions_(false) {\r
+ listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);\r
+}\r
+\r
+UnitTestImpl::~UnitTestImpl() {\r
+ // Deletes every TestCase.\r
+ ForEach(test_cases_, internal::Delete<TestCase>);\r
+\r
+ // Deletes every Environment.\r
+ ForEach(environments_, internal::Delete<Environment>);\r
+\r
+ delete os_stack_trace_getter_;\r
+}\r
+\r
+// Adds a TestProperty to the current TestResult object when invoked in a\r
+// context of a test, to current test case's ad_hoc_test_result when invoke\r
+// from SetUpTestCase/TearDownTestCase, or to the global property set\r
+// otherwise. If the result already contains a property with the same key,\r
+// the value will be updated.\r
+void UnitTestImpl::RecordProperty(const TestProperty& test_property) {\r
+ std::string xml_element;\r
+ TestResult* test_result; // TestResult appropriate for property recording.\r
+\r
+ if (current_test_info_ != NULL) {\r
+ xml_element = "testcase";\r
+ test_result = &(current_test_info_->result_);\r
+ } else if (current_test_case_ != NULL) {\r
+ xml_element = "testsuite";\r
+ test_result = &(current_test_case_->ad_hoc_test_result_);\r
+ } else {\r
+ xml_element = "testsuites";\r
+ test_result = &ad_hoc_test_result_;\r
+ }\r
+ test_result->RecordProperty(xml_element, test_property);\r
+}\r
+\r
+#if GTEST_HAS_DEATH_TEST\r
+// Disables event forwarding if the control is currently in a death test\r
+// subprocess. Must not be called before InitGoogleTest.\r
+void UnitTestImpl::SuppressTestEventsIfInSubprocess() {\r
+ if (internal_run_death_test_flag_.get() != NULL)\r
+ listeners()->SuppressEventForwarding();\r
+}\r
+#endif // GTEST_HAS_DEATH_TEST\r
+\r
+// Initializes event listeners performing XML output as specified by\r
+// UnitTestOptions. Must not be called before InitGoogleTest.\r
+void UnitTestImpl::ConfigureXmlOutput() {\r
+ const std::string& output_format = UnitTestOptions::GetOutputFormat();\r
+ if (output_format == "xml") {\r
+ listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(\r
+ UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));\r
+ } else if (output_format != "") {\r
+ printf("WARNING: unrecognized output format \"%s\" ignored.\n",\r
+ output_format.c_str());\r
+ fflush(stdout);\r
+ }\r
+}\r
+\r
+#if GTEST_CAN_STREAM_RESULTS_\r
+// Initializes event listeners for streaming test results in string form.\r
+// Must not be called before InitGoogleTest.\r
+void UnitTestImpl::ConfigureStreamingOutput() {\r
+ const std::string& target = GTEST_FLAG(stream_result_to);\r
+ if (!target.empty()) {\r
+ const size_t pos = target.find(':');\r
+ if (pos != std::string::npos) {\r
+ listeners()->Append(new StreamingListener(target.substr(0, pos),\r
+ target.substr(pos+1)));\r
+ } else {\r
+ printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",\r
+ target.c_str());\r
+ fflush(stdout);\r
+ }\r
+ }\r
+}\r
+#endif // GTEST_CAN_STREAM_RESULTS_\r
+\r
+// Performs initialization dependent upon flag values obtained in\r
+// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to\r
+// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest\r
+// this function is also called from RunAllTests. Since this function can be\r
+// called more than once, it has to be idempotent.\r
+void UnitTestImpl::PostFlagParsingInit() {\r
+ // Ensures that this function does not execute more than once.\r
+ if (!post_flag_parse_init_performed_) {\r
+ post_flag_parse_init_performed_ = true;\r
+\r
+#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)\r
+ // Register to send notifications about key process state changes.\r
+ listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());\r
+#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)\r
+\r
+#if GTEST_HAS_DEATH_TEST\r
+ InitDeathTestSubprocessControlInfo();\r
+ SuppressTestEventsIfInSubprocess();\r
+#endif // GTEST_HAS_DEATH_TEST\r
+\r
+ // Registers parameterized tests. This makes parameterized tests\r
+ // available to the UnitTest reflection API without running\r
+ // RUN_ALL_TESTS.\r
+ RegisterParameterizedTests();\r
+\r
+ // Configures listeners for XML output. This makes it possible for users\r
+ // to shut down the default XML output before invoking RUN_ALL_TESTS.\r
+ ConfigureXmlOutput();\r
+\r
+#if GTEST_CAN_STREAM_RESULTS_\r
+ // Configures listeners for streaming test results to the specified server.\r
+ ConfigureStreamingOutput();\r
+#endif // GTEST_CAN_STREAM_RESULTS_\r
+ }\r
+}\r
+\r
+// A predicate that checks the name of a TestCase against a known\r
+// value.\r
+//\r
+// This is used for implementation of the UnitTest class only. We put\r
+// it in the anonymous namespace to prevent polluting the outer\r
+// namespace.\r
+//\r
+// TestCaseNameIs is copyable.\r
+class TestCaseNameIs {\r
+ public:\r
+ // Constructor.\r
+ explicit TestCaseNameIs(const std::string& name)\r
+ : name_(name) {}\r
+\r
+ // Returns true iff the name of test_case matches name_.\r
+ bool operator()(const TestCase* test_case) const {\r
+ return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;\r
+ }\r
+\r
+ private:\r
+ std::string name_;\r
+};\r
+\r
+// Finds and returns a TestCase with the given name. If one doesn't\r
+// exist, creates one and returns it. It's the CALLER'S\r
+// RESPONSIBILITY to ensure that this function is only called WHEN THE\r
+// TESTS ARE NOT SHUFFLED.\r
+//\r
+// Arguments:\r
+//\r
+// test_case_name: name of the test case\r
+// type_param: the name of the test case's type parameter, or NULL if\r
+// this is not a typed or a type-parameterized test case.\r
+// set_up_tc: pointer to the function that sets up the test case\r
+// tear_down_tc: pointer to the function that tears down the test case\r
+TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,\r
+ const char* type_param,\r
+ Test::SetUpTestCaseFunc set_up_tc,\r
+ Test::TearDownTestCaseFunc tear_down_tc) {\r
+ // Can we find a TestCase with the given name?\r
+ const std::vector<TestCase*>::const_iterator test_case =\r
+ std::find_if(test_cases_.begin(), test_cases_.end(),\r
+ TestCaseNameIs(test_case_name));\r
+\r
+ if (test_case != test_cases_.end())\r
+ return *test_case;\r
+\r
+ // No. Let's create one.\r
+ TestCase* const new_test_case =\r
+ new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);\r
+\r
+ // Is this a death test case?\r
+ if (internal::UnitTestOptions::MatchesFilter(test_case_name,\r
+ kDeathTestCaseFilter)) {\r
+ // Yes. Inserts the test case after the last death test case\r
+ // defined so far. This only works when the test cases haven't\r
+ // been shuffled. Otherwise we may end up running a death test\r
+ // after a non-death test.\r
+ ++last_death_test_case_;\r
+ test_cases_.insert(test_cases_.begin() + last_death_test_case_,\r
+ new_test_case);\r
+ } else {\r
+ // No. Appends to the end of the list.\r
+ test_cases_.push_back(new_test_case);\r
+ }\r
+\r
+ test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));\r
+ return new_test_case;\r
+}\r
+\r
+// Helpers for setting up / tearing down the given environment. They\r
+// are for use in the ForEach() function.\r
+static void SetUpEnvironment(Environment* env) { env->SetUp(); }\r
+static void TearDownEnvironment(Environment* env) { env->TearDown(); }\r
+\r
+// Runs all tests in this UnitTest object, prints the result, and\r
+// returns true if all tests are successful. If any exception is\r
+// thrown during a test, the test is considered to be failed, but the\r
+// rest of the tests will still be run.\r
+//\r
+// When parameterized tests are enabled, it expands and registers\r
+// parameterized tests first in RegisterParameterizedTests().\r
+// All other functions called from RunAllTests() may safely assume that\r
+// parameterized tests are ready to be counted and run.\r
+bool UnitTestImpl::RunAllTests() {\r
+ // Makes sure InitGoogleTest() was called.\r
+ if (!GTestIsInitialized()) {\r
+ printf("%s",\r
+ "\nThis test program did NOT call ::testing::InitGoogleTest "\r
+ "before calling RUN_ALL_TESTS(). Please fix it.\n");\r
+ return false;\r
+ }\r
+\r
+ // Do not run any test if the --help flag was specified.\r
+ if (g_help_flag)\r
+ return true;\r
+\r
+ // Repeats the call to the post-flag parsing initialization in case the\r
+ // user didn't call InitGoogleTest.\r
+ PostFlagParsingInit();\r
+\r
+ // Even if sharding is not on, test runners may want to use the\r
+ // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding\r
+ // protocol.\r
+ internal::WriteToShardStatusFileIfNeeded();\r
+\r
+ // True iff we are in a subprocess for running a thread-safe-style\r
+ // death test.\r
+ bool in_subprocess_for_death_test = false;\r
+\r
+#if GTEST_HAS_DEATH_TEST\r
+ in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);\r
+# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)\r
+ if (in_subprocess_for_death_test) {\r
+ GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();\r
+ }\r
+# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)\r
+#endif // GTEST_HAS_DEATH_TEST\r
+\r
+ const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,\r
+ in_subprocess_for_death_test);\r
+\r
+ // Compares the full test names with the filter to decide which\r
+ // tests to run.\r
+ const bool has_tests_to_run = FilterTests(should_shard\r
+ ? HONOR_SHARDING_PROTOCOL\r
+ : IGNORE_SHARDING_PROTOCOL) > 0;\r
+\r
+ // Lists the tests and exits if the --gtest_list_tests flag was specified.\r
+ if (GTEST_FLAG(list_tests)) {\r
+ // This must be called *after* FilterTests() has been called.\r
+ ListTestsMatchingFilter();\r
+ return true;\r
+ }\r
+\r
+ random_seed_ = GTEST_FLAG(shuffle) ?\r
+ GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;\r
+\r
+ // True iff at least one test has failed.\r
+ bool failed = false;\r
+\r
+ TestEventListener* repeater = listeners()->repeater();\r
+\r
+ start_timestamp_ = GetTimeInMillis();\r
+ repeater->OnTestProgramStart(*parent_);\r
+\r
+ // How many times to repeat the tests? We don't want to repeat them\r
+ // when we are inside the subprocess of a death test.\r
+ const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);\r
+ // Repeats forever if the repeat count is negative.\r
+ const bool forever = repeat < 0;\r
+ for (int i = 0; forever || i != repeat; i++) {\r
+ // We want to preserve failures generated by ad-hoc test\r
+ // assertions executed before RUN_ALL_TESTS().\r
+ ClearNonAdHocTestResult();\r
+\r
+ const TimeInMillis start = GetTimeInMillis();\r
+\r
+ // Shuffles test cases and tests if requested.\r
+ if (has_tests_to_run && GTEST_FLAG(shuffle)) {\r
+ random()->Reseed(random_seed_);\r
+ // This should be done before calling OnTestIterationStart(),\r
+ // such that a test event listener can see the actual test order\r
+ // in the event.\r
+ ShuffleTests();\r
+ }\r
+\r
+ // Tells the unit test event listeners that the tests are about to start.\r
+ repeater->OnTestIterationStart(*parent_, i);\r
+\r
+ // Runs each test case if there is at least one test to run.\r
+ if (has_tests_to_run) {\r
+ // Sets up all environments beforehand.\r
+ repeater->OnEnvironmentsSetUpStart(*parent_);\r
+ ForEach(environments_, SetUpEnvironment);\r
+ repeater->OnEnvironmentsSetUpEnd(*parent_);\r
+\r
+ // Runs the tests only if there was no fatal failure during global\r
+ // set-up.\r
+ if (!Test::HasFatalFailure()) {\r
+ for (int test_index = 0; test_index < total_test_case_count();\r
+ test_index++) {\r
+ GetMutableTestCase(test_index)->Run();\r
+ }\r
+ }\r
+\r
+ // Tears down all environments in reverse order afterwards.\r
+ repeater->OnEnvironmentsTearDownStart(*parent_);\r
+ std::for_each(environments_.rbegin(), environments_.rend(),\r
+ TearDownEnvironment);\r
+ repeater->OnEnvironmentsTearDownEnd(*parent_);\r
+ }\r
+\r
+ elapsed_time_ = GetTimeInMillis() - start;\r
+\r
+ // Tells the unit test event listener that the tests have just finished.\r
+ repeater->OnTestIterationEnd(*parent_, i);\r
+\r
+ // Gets the result and clears it.\r
+ if (!Passed()) {\r
+ failed = true;\r
+ }\r
+\r
+ // Restores the original test order after the iteration. This\r
+ // allows the user to quickly repro a failure that happens in the\r
+ // N-th iteration without repeating the first (N - 1) iterations.\r
+ // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in\r
+ // case the user somehow changes the value of the flag somewhere\r
+ // (it's always safe to unshuffle the tests).\r
+ UnshuffleTests();\r
+\r
+ if (GTEST_FLAG(shuffle)) {\r
+ // Picks a new random seed for each iteration.\r
+ random_seed_ = GetNextRandomSeed(random_seed_);\r
+ }\r
+ }\r
+\r
+ repeater->OnTestProgramEnd(*parent_);\r
+\r
+ return !failed;\r
+}\r
+\r
+// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file\r
+// if the variable is present. If a file already exists at this location, this\r
+// function will write over it. If the variable is present, but the file cannot\r
+// be created, prints an error and exits.\r
+void WriteToShardStatusFileIfNeeded() {\r
+ const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);\r
+ if (test_shard_file != NULL) {\r
+ FILE* const file = posix::FOpen(test_shard_file, "w");\r
+ if (file == NULL) {\r
+ ColoredPrintf(COLOR_RED,\r
+ "Could not write to the test shard status file \"%s\" "\r
+ "specified by the %s environment variable.\n",\r
+ test_shard_file, kTestShardStatusFile);\r
+ fflush(stdout);\r
+ exit(EXIT_FAILURE);\r
+ }\r
+ fclose(file);\r
+ }\r
+}\r
+\r
+// Checks whether sharding is enabled by examining the relevant\r
+// environment variable values. If the variables are present,\r
+// but inconsistent (i.e., shard_index >= total_shards), prints\r
+// an error and exits. If in_subprocess_for_death_test, sharding is\r
+// disabled because it must only be applied to the original test\r
+// process. Otherwise, we could filter out death tests we intended to execute.\r
+bool ShouldShard(const char* total_shards_env,\r
+ const char* shard_index_env,\r
+ bool in_subprocess_for_death_test) {\r
+ if (in_subprocess_for_death_test) {\r
+ return false;\r
+ }\r
+\r
+ const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);\r
+ const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);\r
+\r
+ if (total_shards == -1 && shard_index == -1) {\r
+ return false;\r
+ } else if (total_shards == -1 && shard_index != -1) {\r
+ const Message msg = Message()\r
+ << "Invalid environment variables: you have "\r
+ << kTestShardIndex << " = " << shard_index\r
+ << ", but have left " << kTestTotalShards << " unset.\n";\r
+ ColoredPrintf(COLOR_RED, msg.GetString().c_str());\r
+ fflush(stdout);\r
+ exit(EXIT_FAILURE);\r
+ } else if (total_shards != -1 && shard_index == -1) {\r
+ const Message msg = Message()\r
+ << "Invalid environment variables: you have "\r
+ << kTestTotalShards << " = " << total_shards\r
+ << ", but have left " << kTestShardIndex << " unset.\n";\r
+ ColoredPrintf(COLOR_RED, msg.GetString().c_str());\r
+ fflush(stdout);\r
+ exit(EXIT_FAILURE);\r
+ } else if (shard_index < 0 || shard_index >= total_shards) {\r
+ const Message msg = Message()\r
+ << "Invalid environment variables: we require 0 <= "\r
+ << kTestShardIndex << " < " << kTestTotalShards\r
+ << ", but you have " << kTestShardIndex << "=" << shard_index\r
+ << ", " << kTestTotalShards << "=" << total_shards << ".\n";\r
+ ColoredPrintf(COLOR_RED, msg.GetString().c_str());\r
+ fflush(stdout);\r
+ exit(EXIT_FAILURE);\r
+ }\r
+\r
+ return total_shards > 1;\r
+}\r
+\r
+// Parses the environment variable var as an Int32. If it is unset,\r
+// returns default_val. If it is not an Int32, prints an error\r
+// and aborts.\r
+Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {\r
+ const char* str_val = posix::GetEnv(var);\r
+ if (str_val == NULL) {\r
+ return default_val;\r
+ }\r
+\r
+ Int32 result;\r
+ if (!ParseInt32(Message() << "The value of environment variable " << var,\r
+ str_val, &result)) {\r
+ exit(EXIT_FAILURE);\r
+ }\r
+ return result;\r
+}\r
+\r
+// Given the total number of shards, the shard index, and the test id,\r
+// returns true iff the test should be run on this shard. The test id is\r
+// some arbitrary but unique non-negative integer assigned to each test\r
+// method. Assumes that 0 <= shard_index < total_shards.\r
+bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {\r
+ return (test_id % total_shards) == shard_index;\r
+}\r
+\r
+// Compares the name of each test with the user-specified filter to\r
+// decide whether the test should be run, then records the result in\r
+// each TestCase and TestInfo object.\r
+// If shard_tests == true, further filters tests based on sharding\r
+// variables in the environment - see\r
+// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.\r
+// Returns the number of tests that should run.\r
+int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {\r
+ const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?\r
+ Int32FromEnvOrDie(kTestTotalShards, -1) : -1;\r
+ const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?\r
+ Int32FromEnvOrDie(kTestShardIndex, -1) : -1;\r
+\r
+ // num_runnable_tests are the number of tests that will\r
+ // run across all shards (i.e., match filter and are not disabled).\r
+ // num_selected_tests are the number of tests to be run on\r
+ // this shard.\r
+ int num_runnable_tests = 0;\r
+ int num_selected_tests = 0;\r
+ for (size_t i = 0; i < test_cases_.size(); i++) {\r
+ TestCase* const test_case = test_cases_[i];\r
+ const std::string &test_case_name = test_case->name();\r
+ test_case->set_should_run(false);\r
+\r
+ for (size_t j = 0; j < test_case->test_info_list().size(); j++) {\r
+ TestInfo* const test_info = test_case->test_info_list()[j];\r
+ const std::string test_name(test_info->name());\r
+ // A test is disabled if test case name or test name matches\r
+ // kDisableTestFilter.\r
+ const bool is_disabled =\r
+ internal::UnitTestOptions::MatchesFilter(test_case_name,\r
+ kDisableTestFilter) ||\r
+ internal::UnitTestOptions::MatchesFilter(test_name,\r
+ kDisableTestFilter);\r
+ test_info->is_disabled_ = is_disabled;\r
+\r
+ const bool matches_filter =\r
+ internal::UnitTestOptions::FilterMatchesTest(test_case_name,\r
+ test_name);\r
+ test_info->matches_filter_ = matches_filter;\r
+\r
+ const bool is_runnable =\r
+ (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&\r
+ matches_filter;\r
+\r
+ const bool is_selected = is_runnable &&\r
+ (shard_tests == IGNORE_SHARDING_PROTOCOL ||\r
+ ShouldRunTestOnShard(total_shards, shard_index,\r
+ num_runnable_tests));\r
+\r
+ num_runnable_tests += is_runnable;\r
+ num_selected_tests += is_selected;\r
+\r
+ test_info->should_run_ = is_selected;\r
+ test_case->set_should_run(test_case->should_run() || is_selected);\r
+ }\r
+ }\r
+ return num_selected_tests;\r
+}\r
+\r
+// Prints the given C-string on a single line by replacing all '\n'\r
+// characters with string "\\n". If the output takes more than\r
+// max_length characters, only prints the first max_length characters\r
+// and "...".\r
+static void PrintOnOneLine(const char* str, int max_length) {\r
+ if (str != NULL) {\r
+ for (int i = 0; *str != '\0'; ++str) {\r
+ if (i >= max_length) {\r
+ printf("...");\r
+ break;\r
+ }\r
+ if (*str == '\n') {\r
+ printf("\\n");\r
+ i += 2;\r
+ } else {\r
+ printf("%c", *str);\r
+ ++i;\r
+ }\r
+ }\r
+ }\r
+}\r
+\r
+// Prints the names of the tests matching the user-specified filter flag.\r
+void UnitTestImpl::ListTestsMatchingFilter() {\r
+ // Print at most this many characters for each type/value parameter.\r
+ const int kMaxParamLength = 250;\r
+\r
+ for (size_t i = 0; i < test_cases_.size(); i++) {\r
+ const TestCase* const test_case = test_cases_[i];\r
+ bool printed_test_case_name = false;\r
+\r
+ for (size_t j = 0; j < test_case->test_info_list().size(); j++) {\r
+ const TestInfo* const test_info =\r
+ test_case->test_info_list()[j];\r
+ if (test_info->matches_filter_) {\r
+ if (!printed_test_case_name) {\r
+ printed_test_case_name = true;\r
+ printf("%s.", test_case->name());\r
+ if (test_case->type_param() != NULL) {\r
+ printf(" # %s = ", kTypeParamLabel);\r
+ // We print the type parameter on a single line to make\r
+ // the output easy to parse by a program.\r
+ PrintOnOneLine(test_case->type_param(), kMaxParamLength);\r
+ }\r
+ printf("\n");\r
+ }\r
+ printf(" %s", test_info->name());\r
+ if (test_info->value_param() != NULL) {\r
+ printf(" # %s = ", kValueParamLabel);\r
+ // We print the value parameter on a single line to make the\r
+ // output easy to parse by a program.\r
+ PrintOnOneLine(test_info->value_param(), kMaxParamLength);\r
+ }\r
+ printf("\n");\r
+ }\r
+ }\r
+ }\r
+ fflush(stdout);\r
+}\r
+\r
+// Sets the OS stack trace getter.\r
+//\r
+// Does nothing if the input and the current OS stack trace getter are\r
+// the same; otherwise, deletes the old getter and makes the input the\r
+// current getter.\r
+void UnitTestImpl::set_os_stack_trace_getter(\r
+ OsStackTraceGetterInterface* getter) {\r
+ if (os_stack_trace_getter_ != getter) {\r
+ delete os_stack_trace_getter_;\r
+ os_stack_trace_getter_ = getter;\r
+ }\r
+}\r
+\r
+// Returns the current OS stack trace getter if it is not NULL;\r
+// otherwise, creates an OsStackTraceGetter, makes it the current\r
+// getter, and returns it.\r
+OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {\r
+ if (os_stack_trace_getter_ == NULL) {\r
+#ifdef GTEST_OS_STACK_TRACE_GETTER_\r
+ os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;\r
+#else\r
+ os_stack_trace_getter_ = new OsStackTraceGetter;\r
+#endif // GTEST_OS_STACK_TRACE_GETTER_\r
+ }\r
+\r
+ return os_stack_trace_getter_;\r
+}\r
+\r
+// Returns the TestResult for the test that's currently running, or\r
+// the TestResult for the ad hoc test if no test is running.\r
+TestResult* UnitTestImpl::current_test_result() {\r
+ return current_test_info_ ?\r
+ &(current_test_info_->result_) : &ad_hoc_test_result_;\r
+}\r
+\r
+// Shuffles all test cases, and the tests within each test case,\r
+// making sure that death tests are still run first.\r
+void UnitTestImpl::ShuffleTests() {\r
+ // Shuffles the death test cases.\r
+ ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);\r
+\r
+ // Shuffles the non-death test cases.\r
+ ShuffleRange(random(), last_death_test_case_ + 1,\r
+ static_cast<int>(test_cases_.size()), &test_case_indices_);\r
+\r
+ // Shuffles the tests inside each test case.\r
+ for (size_t i = 0; i < test_cases_.size(); i++) {\r
+ test_cases_[i]->ShuffleTests(random());\r
+ }\r
+}\r
+\r
+// Restores the test cases and tests to their order before the first shuffle.\r
+void UnitTestImpl::UnshuffleTests() {\r
+ for (size_t i = 0; i < test_cases_.size(); i++) {\r
+ // Unshuffles the tests in each test case.\r
+ test_cases_[i]->UnshuffleTests();\r
+ // Resets the index of each test case.\r
+ test_case_indices_[i] = static_cast<int>(i);\r
+ }\r
+}\r
+\r
+// Returns the current OS stack trace as an std::string.\r
+//\r
+// The maximum number of stack frames to be included is specified by\r
+// the gtest_stack_trace_depth flag. The skip_count parameter\r
+// specifies the number of top frames to be skipped, which doesn't\r
+// count against the number of frames to be included.\r
+//\r
+// For example, if Foo() calls Bar(), which in turn calls\r
+// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in\r
+// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.\r
+std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,\r
+ int skip_count) {\r
+ // We pass skip_count + 1 to skip this wrapper function in addition\r
+ // to what the user really wants to skip.\r
+ return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);\r
+}\r
+\r
+// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to\r
+// suppress unreachable code warnings.\r
+namespace {\r
+class ClassUniqueToAlwaysTrue {};\r
+}\r
+\r
+bool IsTrue(bool condition) { return condition; }\r
+\r
+bool AlwaysTrue() {\r
+#if GTEST_HAS_EXCEPTIONS\r
+ // This condition is always false so AlwaysTrue() never actually throws,\r
+ // but it makes the compiler think that it may throw.\r
+ if (IsTrue(false))\r
+ throw ClassUniqueToAlwaysTrue();\r
+#endif // GTEST_HAS_EXCEPTIONS\r
+ return true;\r
+}\r
+\r
+// If *pstr starts with the given prefix, modifies *pstr to be right\r
+// past the prefix and returns true; otherwise leaves *pstr unchanged\r
+// and returns false. None of pstr, *pstr, and prefix can be NULL.\r
+bool SkipPrefix(const char* prefix, const char** pstr) {\r
+ const size_t prefix_len = strlen(prefix);\r
+ if (strncmp(*pstr, prefix, prefix_len) == 0) {\r
+ *pstr += prefix_len;\r
+ return true;\r
+ }\r
+ return false;\r
+}\r
+\r
+// Parses a string as a command line flag. The string should have\r
+// the format "--flag=value". When def_optional is true, the "=value"\r
+// part can be omitted.\r
+//\r
+// Returns the value of the flag, or NULL if the parsing failed.\r
+const char* ParseFlagValue(const char* str,\r
+ const char* flag,\r
+ bool def_optional) {\r
+ // str and flag must not be NULL.\r
+ if (str == NULL || flag == NULL) return NULL;\r
+\r
+ // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.\r
+ const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;\r
+ const size_t flag_len = flag_str.length();\r
+ if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;\r
+\r
+ // Skips the flag name.\r
+ const char* flag_end = str + flag_len;\r
+\r
+ // When def_optional is true, it's OK to not have a "=value" part.\r
+ if (def_optional && (flag_end[0] == '\0')) {\r
+ return flag_end;\r
+ }\r
+\r
+ // If def_optional is true and there are more characters after the\r
+ // flag name, or if def_optional is false, there must be a '=' after\r
+ // the flag name.\r
+ if (flag_end[0] != '=') return NULL;\r
+\r
+ // Returns the string after "=".\r
+ return flag_end + 1;\r
+}\r
+\r
+// Parses a string for a bool flag, in the form of either\r
+// "--flag=value" or "--flag".\r
+//\r
+// In the former case, the value is taken as true as long as it does\r
+// not start with '0', 'f', or 'F'.\r
+//\r
+// In the latter case, the value is taken as true.\r
+//\r
+// On success, stores the value of the flag in *value, and returns\r
+// true. On failure, returns false without changing *value.\r
+bool ParseBoolFlag(const char* str, const char* flag, bool* value) {\r
+ // Gets the value of the flag as a string.\r
+ const char* const value_str = ParseFlagValue(str, flag, true);\r
+\r
+ // Aborts if the parsing failed.\r
+ if (value_str == NULL) return false;\r
+\r
+ // Converts the string value to a bool.\r
+ *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');\r
+ return true;\r
+}\r
+\r
+// Parses a string for an Int32 flag, in the form of\r
+// "--flag=value".\r
+//\r
+// On success, stores the value of the flag in *value, and returns\r
+// true. On failure, returns false without changing *value.\r
+bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {\r
+ // Gets the value of the flag as a string.\r
+ const char* const value_str = ParseFlagValue(str, flag, false);\r
+\r
+ // Aborts if the parsing failed.\r
+ if (value_str == NULL) return false;\r
+\r
+ // Sets *value to the value of the flag.\r
+ return ParseInt32(Message() << "The value of flag --" << flag,\r
+ value_str, value);\r
+}\r
+\r
+// Parses a string for a string flag, in the form of\r
+// "--flag=value".\r
+//\r
+// On success, stores the value of the flag in *value, and returns\r
+// true. On failure, returns false without changing *value.\r
+bool ParseStringFlag(const char* str, const char* flag, std::string* value) {\r
+ // Gets the value of the flag as a string.\r
+ const char* const value_str = ParseFlagValue(str, flag, false);\r
+\r
+ // Aborts if the parsing failed.\r
+ if (value_str == NULL) return false;\r
+\r
+ // Sets *value to the value of the flag.\r
+ *value = value_str;\r
+ return true;\r
+}\r
+\r
+// Determines whether a string has a prefix that Google Test uses for its\r
+// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.\r
+// If Google Test detects that a command line flag has its prefix but is not\r
+// recognized, it will print its help message. Flags starting with\r
+// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test\r
+// internal flags and do not trigger the help message.\r
+static bool HasGoogleTestFlagPrefix(const char* str) {\r
+ return (SkipPrefix("--", &str) ||\r
+ SkipPrefix("-", &str) ||\r
+ SkipPrefix("/", &str)) &&\r
+ !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&\r
+ (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||\r
+ SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));\r
+}\r
+\r
+// Prints a string containing code-encoded text. The following escape\r
+// sequences can be used in the string to control the text color:\r
+//\r
+// @@ prints a single '@' character.\r
+// @R changes the color to red.\r
+// @G changes the color to green.\r
+// @Y changes the color to yellow.\r
+// @D changes to the default terminal text color.\r
+//\r
+// TODO(wan@google.com): Write tests for this once we add stdout\r
+// capturing to Google Test.\r
+static void PrintColorEncoded(const char* str) {\r
+ GTestColor color = COLOR_DEFAULT; // The current color.\r
+\r
+ // Conceptually, we split the string into segments divided by escape\r
+ // sequences. Then we print one segment at a time. At the end of\r
+ // each iteration, the str pointer advances to the beginning of the\r
+ // next segment.\r
+ for (;;) {\r
+ const char* p = strchr(str, '@');\r
+ if (p == NULL) {\r
+ ColoredPrintf(color, "%s", str);\r
+ return;\r
+ }\r
+\r
+ ColoredPrintf(color, "%s", std::string(str, p).c_str());\r
+\r
+ const char ch = p[1];\r
+ str = p + 2;\r
+ if (ch == '@') {\r
+ ColoredPrintf(color, "@");\r
+ } else if (ch == 'D') {\r
+ color = COLOR_DEFAULT;\r
+ } else if (ch == 'R') {\r
+ color = COLOR_RED;\r
+ } else if (ch == 'G') {\r
+ color = COLOR_GREEN;\r
+ } else if (ch == 'Y') {\r
+ color = COLOR_YELLOW;\r
+ } else {\r
+ --str;\r
+ }\r
+ }\r
+}\r
+\r
+static const char kColorEncodedHelpMessage[] =\r
+"This program contains tests written using " GTEST_NAME_ ". You can use the\n"\r
+"following command line flags to control its behavior:\n"\r
+"\n"\r
+"Test Selection:\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"\r
+" List the names of all tests instead of running them. The name of\n"\r
+" TEST(Foo, Bar) is \"Foo.Bar\".\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"\r
+ "[@G-@YNEGATIVE_PATTERNS]@D\n"\r
+" Run only the tests whose name matches one of the positive patterns but\n"\r
+" none of the negative patterns. '?' matches any single character; '*'\n"\r
+" matches any substring; ':' separates two patterns.\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"\r
+" Run all disabled tests too.\n"\r
+"\n"\r
+"Test Execution:\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"\r
+" Run the tests repeatedly; use a negative count to repeat forever.\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"\r
+" Randomize tests' orders on every iteration.\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"\r
+" Random number seed to use for shuffling test orders (between 1 and\n"\r
+" 99999, or 0 to use a seed based on the current time).\n"\r
+"\n"\r
+"Test Output:\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"\r
+" Enable/disable colored output. The default is @Gauto@D.\n"\r
+" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"\r
+" Don't print the elapsed time of each test.\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"\r
+ GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"\r
+" Generate an XML report in the given directory or with the given file\n"\r
+" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"\r
+#if GTEST_CAN_STREAM_RESULTS_\r
+" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"\r
+" Stream test results to the given server.\n"\r
+#endif // GTEST_CAN_STREAM_RESULTS_\r
+"\n"\r
+"Assertion Behavior:\n"\r
+#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS\r
+" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"\r
+" Set the default death test style.\n"\r
+#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS\r
+" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"\r
+" Turn assertion failures into debugger break-points.\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"\r
+" Turn assertion failures into C++ exceptions.\n"\r
+" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"\r
+" Do not report exceptions as test failures. Instead, allow them\n"\r
+" to crash the program or throw a pop-up (on Windows).\n"\r
+"\n"\r
+"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "\r
+ "the corresponding\n"\r
+"environment variable of a flag (all letters in upper-case). For example, to\n"\r
+"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_\r
+ "color=no@D or set\n"\r
+"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"\r
+"\n"\r
+"For more information, please read the " GTEST_NAME_ " documentation at\n"\r
+"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"\r
+"(not one in your own code or tests), please report it to\n"\r
+"@G<" GTEST_DEV_EMAIL_ ">@D.\n";\r
+\r
+bool ParseGoogleTestFlag(const char* const arg) {\r
+ return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,\r
+ >EST_FLAG(also_run_disabled_tests)) ||\r
+ ParseBoolFlag(arg, kBreakOnFailureFlag,\r
+ >EST_FLAG(break_on_failure)) ||\r
+ ParseBoolFlag(arg, kCatchExceptionsFlag,\r
+ >EST_FLAG(catch_exceptions)) ||\r
+ ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||\r
+ ParseStringFlag(arg, kDeathTestStyleFlag,\r
+ >EST_FLAG(death_test_style)) ||\r
+ ParseBoolFlag(arg, kDeathTestUseFork,\r
+ >EST_FLAG(death_test_use_fork)) ||\r
+ ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||\r
+ ParseStringFlag(arg, kInternalRunDeathTestFlag,\r
+ >EST_FLAG(internal_run_death_test)) ||\r
+ ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||\r
+ ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||\r
+ ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||\r
+ ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||\r
+ ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||\r
+ ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||\r
+ ParseInt32Flag(arg, kStackTraceDepthFlag,\r
+ >EST_FLAG(stack_trace_depth)) ||\r
+ ParseStringFlag(arg, kStreamResultToFlag,\r
+ >EST_FLAG(stream_result_to)) ||\r
+ ParseBoolFlag(arg, kThrowOnFailureFlag,\r
+ >EST_FLAG(throw_on_failure));\r
+}\r
+\r
+#if GTEST_USE_OWN_FLAGFILE_FLAG_\r
+void LoadFlagsFromFile(const std::string& path) {\r
+ FILE* flagfile = posix::FOpen(path.c_str(), "r");\r
+ if (!flagfile) {\r
+ fprintf(stderr,\r
+ "Unable to open file \"%s\"\n",\r
+ GTEST_FLAG(flagfile).c_str());\r
+ fflush(stderr);\r
+ exit(EXIT_FAILURE);\r
+ }\r
+ std::string contents(ReadEntireFile(flagfile));\r
+ posix::FClose(flagfile);\r
+ std::vector<std::string> lines;\r
+ SplitString(contents, '\n', &lines);\r
+ for (size_t i = 0; i < lines.size(); ++i) {\r
+ if (lines[i].empty())\r
+ continue;\r
+ if (!ParseGoogleTestFlag(lines[i].c_str()))\r
+ g_help_flag = true;\r
+ }\r
+}\r
+#endif // GTEST_USE_OWN_FLAGFILE_FLAG_\r
+\r
+// Parses the command line for Google Test flags, without initializing\r
+// other parts of Google Test. The type parameter CharType can be\r
+// instantiated to either char or wchar_t.\r
+template <typename CharType>\r
+void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {\r
+ for (int i = 1; i < *argc; i++) {\r
+ const std::string arg_string = StreamableToString(argv[i]);\r
+ const char* const arg = arg_string.c_str();\r
+\r
+ using internal::ParseBoolFlag;\r
+ using internal::ParseInt32Flag;\r
+ using internal::ParseStringFlag;\r
+\r
+ bool remove_flag = false;\r
+ if (ParseGoogleTestFlag(arg)) {\r
+ remove_flag = true;\r
+#if GTEST_USE_OWN_FLAGFILE_FLAG_\r
+ } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) {\r
+ LoadFlagsFromFile(GTEST_FLAG(flagfile));\r
+ remove_flag = true;\r
+#endif // GTEST_USE_OWN_FLAGFILE_FLAG_\r
+ } else if (arg_string == "--help" || arg_string == "-h" ||\r
+ arg_string == "-?" || arg_string == "/?" ||\r
+ HasGoogleTestFlagPrefix(arg)) {\r
+ // Both help flag and unrecognized Google Test flags (excluding\r
+ // internal ones) trigger help display.\r
+ g_help_flag = true;\r
+ }\r
+\r
+ if (remove_flag) {\r
+ // Shift the remainder of the argv list left by one. Note\r
+ // that argv has (*argc + 1) elements, the last one always being\r
+ // NULL. The following loop moves the trailing NULL element as\r
+ // well.\r
+ for (int j = i; j != *argc; j++) {\r
+ argv[j] = argv[j + 1];\r
+ }\r
+\r
+ // Decrements the argument count.\r
+ (*argc)--;\r
+\r
+ // We also need to decrement the iterator as we just removed\r
+ // an element.\r
+ i--;\r
+ }\r
+ }\r
+\r
+ if (g_help_flag) {\r
+ // We print the help here instead of in RUN_ALL_TESTS(), as the\r
+ // latter may not be called at all if the user is using Google\r
+ // Test with another testing framework.\r
+ PrintColorEncoded(kColorEncodedHelpMessage);\r
+ }\r
+}\r
+\r
+// Parses the command line for Google Test flags, without initializing\r
+// other parts of Google Test.\r
+void ParseGoogleTestFlagsOnly(int* argc, char** argv) {\r
+ ParseGoogleTestFlagsOnlyImpl(argc, argv);\r
+}\r
+void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {\r
+ ParseGoogleTestFlagsOnlyImpl(argc, argv);\r
+}\r
+\r
+// The internal implementation of InitGoogleTest().\r
+//\r
+// The type parameter CharType can be instantiated to either char or\r
+// wchar_t.\r
+template <typename CharType>\r
+void InitGoogleTestImpl(int* argc, CharType** argv) {\r
+ // We don't want to run the initialization code twice.\r
+ if (GTestIsInitialized()) return;\r
+\r
+ if (*argc <= 0) return;\r
+\r
+ g_argvs.clear();\r
+ for (int i = 0; i != *argc; i++) {\r
+ g_argvs.push_back(StreamableToString(argv[i]));\r
+ }\r
+\r
+ ParseGoogleTestFlagsOnly(argc, argv);\r
+ GetUnitTestImpl()->PostFlagParsingInit();\r
+}\r
+\r
+} // namespace internal\r
+\r
+// Initializes Google Test. This must be called before calling\r
+// RUN_ALL_TESTS(). In particular, it parses a command line for the\r
+// flags that Google Test recognizes. Whenever a Google Test flag is\r
+// seen, it is removed from argv, and *argc is decremented.\r
+//\r
+// No value is returned. Instead, the Google Test flag variables are\r
+// updated.\r
+//\r
+// Calling the function for the second time has no user-visible effect.\r
+void InitGoogleTest(int* argc, char** argv) {\r
+#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\r
+ GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);\r
+#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\r
+ internal::InitGoogleTestImpl(argc, argv);\r
+#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\r
+}\r
+\r
+// This overloaded version can be used in Windows programs compiled in\r
+// UNICODE mode.\r
+void InitGoogleTest(int* argc, wchar_t** argv) {\r
+#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\r
+ GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);\r
+#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\r
+ internal::InitGoogleTestImpl(argc, argv);\r
+#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\r
+}\r
+\r
+} // namespace testing\r
+// Copyright 2005, Google Inc.\r
+// All rights reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+//\r
+// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)\r
+//\r
+// This file implements death tests.\r
+\r
+\r
+#if GTEST_HAS_DEATH_TEST\r
+\r
+# if GTEST_OS_MAC\r
+# include <crt_externs.h>\r
+# endif // GTEST_OS_MAC\r
+\r
+# include <errno.h>\r
+# include <fcntl.h>\r
+# include <limits.h>\r
+\r
+# if GTEST_OS_LINUX\r
+# include <signal.h>\r
+# endif // GTEST_OS_LINUX\r
+\r
+# include <stdarg.h>\r
+\r
+# if GTEST_OS_WINDOWS\r
+# include <windows.h>\r
+# else\r
+# include <sys/mman.h>\r
+# include <sys/wait.h>\r
+# endif // GTEST_OS_WINDOWS\r
+\r
+# if GTEST_OS_QNX\r
+# include <spawn.h>\r
+# endif // GTEST_OS_QNX\r
+\r
+#endif // GTEST_HAS_DEATH_TEST\r
+\r
+\r
+// Indicates that this translation unit is part of Google Test's\r
+// implementation. It must come before gtest-internal-inl.h is\r
+// included, or there will be a compiler error. This trick exists to\r
+// prevent the accidental inclusion of gtest-internal-inl.h in the\r
+// user's code.\r
+#define GTEST_IMPLEMENTATION_ 1\r
+#undef GTEST_IMPLEMENTATION_\r
+\r
+namespace testing {\r
+\r
+// Constants.\r
+\r
+// The default death test style.\r
+static const char kDefaultDeathTestStyle[] = "fast";\r
+\r
+GTEST_DEFINE_string_(\r
+ death_test_style,\r
+ internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),\r
+ "Indicates how to run a death test in a forked child process: "\r
+ "\"threadsafe\" (child process re-executes the test binary "\r
+ "from the beginning, running only the specific death test) or "\r
+ "\"fast\" (child process runs the death test immediately "\r
+ "after forking).");\r
+\r
+GTEST_DEFINE_bool_(\r
+ death_test_use_fork,\r
+ internal::BoolFromGTestEnv("death_test_use_fork", false),\r
+ "Instructs to use fork()/_exit() instead of clone() in death tests. "\r
+ "Ignored and always uses fork() on POSIX systems where clone() is not "\r
+ "implemented. Useful when running under valgrind or similar tools if "\r
+ "those do not support clone(). Valgrind 3.3.1 will just fail if "\r
+ "it sees an unsupported combination of clone() flags. "\r
+ "It is not recommended to use this flag w/o valgrind though it will "\r
+ "work in 99% of the cases. Once valgrind is fixed, this flag will "\r
+ "most likely be removed.");\r
+\r
+namespace internal {\r
+GTEST_DEFINE_string_(\r
+ internal_run_death_test, "",\r
+ "Indicates the file, line number, temporal index of "\r
+ "the single death test to run, and a file descriptor to "\r
+ "which a success code may be sent, all separated by "\r
+ "the '|' characters. This flag is specified if and only if the current "\r
+ "process is a sub-process launched for running a thread-safe "\r
+ "death test. FOR INTERNAL USE ONLY.");\r
+} // namespace internal\r
+\r
+#if GTEST_HAS_DEATH_TEST\r
+\r
+namespace internal {\r
+\r
+// Valid only for fast death tests. Indicates the code is running in the\r
+// child process of a fast style death test.\r
+static bool g_in_fast_death_test_child = false;\r
+\r
+// Returns a Boolean value indicating whether the caller is currently\r
+// executing in the context of the death test child process. Tools such as\r
+// Valgrind heap checkers may need this to modify their behavior in death\r
+// tests. IMPORTANT: This is an internal utility. Using it may break the\r
+// implementation of death tests. User code MUST NOT use it.\r
+bool InDeathTestChild() {\r
+# if GTEST_OS_WINDOWS\r
+\r
+ // On Windows, death tests are thread-safe regardless of the value of the\r
+ // death_test_style flag.\r
+ return !GTEST_FLAG(internal_run_death_test).empty();\r
+\r
+# else\r
+\r
+ if (GTEST_FLAG(death_test_style) == "threadsafe")\r
+ return !GTEST_FLAG(internal_run_death_test).empty();\r
+ else\r
+ return g_in_fast_death_test_child;\r
+#endif\r
+}\r
+\r
+} // namespace internal\r
+\r
+// ExitedWithCode constructor.\r
+ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {\r
+}\r
+\r
+// ExitedWithCode function-call operator.\r
+bool ExitedWithCode::operator()(int exit_status) const {\r
+# if GTEST_OS_WINDOWS\r
+\r
+ return exit_status == exit_code_;\r
+\r
+# else\r
+\r
+ return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;\r
+\r
+# endif // GTEST_OS_WINDOWS\r
+}\r
+\r
+# if !GTEST_OS_WINDOWS\r
+// KilledBySignal constructor.\r
+KilledBySignal::KilledBySignal(int signum) : signum_(signum) {\r
+}\r
+\r
+// KilledBySignal function-call operator.\r
+bool KilledBySignal::operator()(int exit_status) const {\r
+# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)\r
+ {\r
+ bool result;\r
+ if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {\r
+ return result;\r
+ }\r
+ }\r
+# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)\r
+ return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;\r
+}\r
+# endif // !GTEST_OS_WINDOWS\r
+\r
+namespace internal {\r
+\r
+// Utilities needed for death tests.\r
+\r
+// Generates a textual description of a given exit code, in the format\r
+// specified by wait(2).\r
+static std::string ExitSummary(int exit_code) {\r
+ Message m;\r
+\r
+# if GTEST_OS_WINDOWS\r
+\r
+ m << "Exited with exit status " << exit_code;\r
+\r
+# else\r
+\r
+ if (WIFEXITED(exit_code)) {\r
+ m << "Exited with exit status " << WEXITSTATUS(exit_code);\r
+ } else if (WIFSIGNALED(exit_code)) {\r
+ m << "Terminated by signal " << WTERMSIG(exit_code);\r
+ }\r
+# ifdef WCOREDUMP\r
+ if (WCOREDUMP(exit_code)) {\r
+ m << " (core dumped)";\r
+ }\r
+# endif\r
+# endif // GTEST_OS_WINDOWS\r
+\r
+ return m.GetString();\r
+}\r
+\r
+// Returns true if exit_status describes a process that was terminated\r
+// by a signal, or exited normally with a nonzero exit code.\r
+bool ExitedUnsuccessfully(int exit_status) {\r
+ return !ExitedWithCode(0)(exit_status);\r
+}\r
+\r
+# if !GTEST_OS_WINDOWS\r
+// Generates a textual failure message when a death test finds more than\r
+// one thread running, or cannot determine the number of threads, prior\r
+// to executing the given statement. It is the responsibility of the\r
+// caller not to pass a thread_count of 1.\r
+static std::string DeathTestThreadWarning(size_t thread_count) {\r
+ Message msg;\r
+ msg << "Death tests use fork(), which is unsafe particularly"\r
+ << " in a threaded context. For this test, " << GTEST_NAME_ << " ";\r
+ if (thread_count == 0)\r
+ msg << "couldn't detect the number of threads.";\r
+ else\r
+ msg << "detected " << thread_count << " threads.";\r
+ return msg.GetString();\r
+}\r
+# endif // !GTEST_OS_WINDOWS\r
+\r
+// Flag characters for reporting a death test that did not die.\r
+static const char kDeathTestLived = 'L';\r
+static const char kDeathTestReturned = 'R';\r
+static const char kDeathTestThrew = 'T';\r
+static const char kDeathTestInternalError = 'I';\r
+\r
+// An enumeration describing all of the possible ways that a death test can\r
+// conclude. DIED means that the process died while executing the test\r
+// code; LIVED means that process lived beyond the end of the test code;\r
+// RETURNED means that the test statement attempted to execute a return\r
+// statement, which is not allowed; THREW means that the test statement\r
+// returned control by throwing an exception. IN_PROGRESS means the test\r
+// has not yet concluded.\r
+// TODO(vladl@google.com): Unify names and possibly values for\r
+// AbortReason, DeathTestOutcome, and flag characters above.\r
+enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };\r
+\r
+// Routine for aborting the program which is safe to call from an\r
+// exec-style death test child process, in which case the error\r
+// message is propagated back to the parent process. Otherwise, the\r
+// message is simply printed to stderr. In either case, the program\r
+// then exits with status 1.\r
+void DeathTestAbort(const std::string& message) {\r
+ // On a POSIX system, this function may be called from a threadsafe-style\r
+ // death test child process, which operates on a very small stack. Use\r
+ // the heap for any additional non-minuscule memory requirements.\r
+ const InternalRunDeathTestFlag* const flag =\r
+ GetUnitTestImpl()->internal_run_death_test_flag();\r
+ if (flag != NULL) {\r
+ FILE* parent = posix::FDOpen(flag->write_fd(), "w");\r
+ fputc(kDeathTestInternalError, parent);\r
+ fprintf(parent, "%s", message.c_str());\r
+ fflush(parent);\r
+ _exit(1);\r
+ } else {\r
+ fprintf(stderr, "%s", message.c_str());\r
+ fflush(stderr);\r
+ posix::Abort();\r
+ }\r
+}\r
+\r
+// A replacement for CHECK that calls DeathTestAbort if the assertion\r
+// fails.\r
+# define GTEST_DEATH_TEST_CHECK_(expression) \\r
+ do { \\r
+ if (!::testing::internal::IsTrue(expression)) { \\r
+ DeathTestAbort( \\r
+ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \\r
+ + ::testing::internal::StreamableToString(__LINE__) + ": " \\r
+ + #expression); \\r
+ } \\r
+ } while (::testing::internal::AlwaysFalse())\r
+\r
+// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for\r
+// evaluating any system call that fulfills two conditions: it must return\r
+// -1 on failure, and set errno to EINTR when it is interrupted and\r
+// should be tried again. The macro expands to a loop that repeatedly\r
+// evaluates the expression as long as it evaluates to -1 and sets\r
+// errno to EINTR. If the expression evaluates to -1 but errno is\r
+// something other than EINTR, DeathTestAbort is called.\r
+# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \\r
+ do { \\r
+ int gtest_retval; \\r
+ do { \\r
+ gtest_retval = (expression); \\r
+ } while (gtest_retval == -1 && errno == EINTR); \\r
+ if (gtest_retval == -1) { \\r
+ DeathTestAbort( \\r
+ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \\r
+ + ::testing::internal::StreamableToString(__LINE__) + ": " \\r
+ + #expression + " != -1"); \\r
+ } \\r
+ } while (::testing::internal::AlwaysFalse())\r
+\r
+// Returns the message describing the last system error in errno.\r
+std::string GetLastErrnoDescription() {\r
+ return errno == 0 ? "" : posix::StrError(errno);\r
+}\r
+\r
+// This is called from a death test parent process to read a failure\r
+// message from the death test child process and log it with the FATAL\r
+// severity. On Windows, the message is read from a pipe handle. On other\r
+// platforms, it is read from a file descriptor.\r
+static void FailFromInternalError(int fd) {\r
+ Message error;\r
+ char buffer[256];\r
+ int num_read;\r
+\r
+ do {\r
+ while ((num_read = posix::Read(fd, buffer, 255)) > 0) {\r
+ buffer[num_read] = '\0';\r
+ error << buffer;\r
+ }\r
+ } while (num_read == -1 && errno == EINTR);\r
+\r
+ if (num_read == 0) {\r
+ GTEST_LOG_(FATAL) << error.GetString();\r
+ } else {\r
+ const int last_error = errno;\r
+ GTEST_LOG_(FATAL) << "Error while reading death test internal: "\r
+ << GetLastErrnoDescription() << " [" << last_error << "]";\r
+ }\r
+}\r
+\r
+// Death test constructor. Increments the running death test count\r
+// for the current test.\r
+DeathTest::DeathTest() {\r
+ TestInfo* const info = GetUnitTestImpl()->current_test_info();\r
+ if (info == NULL) {\r
+ DeathTestAbort("Cannot run a death test outside of a TEST or "\r
+ "TEST_F construct");\r
+ }\r
+}\r
+\r
+// Creates and returns a death test by dispatching to the current\r
+// death test factory.\r
+bool DeathTest::Create(const char* statement, const RE* regex,\r
+ const char* file, int line, DeathTest** test) {\r
+ return GetUnitTestImpl()->death_test_factory()->Create(\r
+ statement, regex, file, line, test);\r
+}\r
+\r
+const char* DeathTest::LastMessage() {\r
+ return last_death_test_message_.c_str();\r
+}\r
+\r
+void DeathTest::set_last_death_test_message(const std::string& message) {\r
+ last_death_test_message_ = message;\r
+}\r
+\r
+std::string DeathTest::last_death_test_message_;\r
+\r
+// Provides cross platform implementation for some death functionality.\r
+class DeathTestImpl : public DeathTest {\r
+ protected:\r
+ DeathTestImpl(const char* a_statement, const RE* a_regex)\r
+ : statement_(a_statement),\r
+ regex_(a_regex),\r
+ spawned_(false),\r
+ status_(-1),\r
+ outcome_(IN_PROGRESS),\r
+ read_fd_(-1),\r
+ write_fd_(-1) {}\r
+\r
+ // read_fd_ is expected to be closed and cleared by a derived class.\r
+ ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }\r
+\r
+ void Abort(AbortReason reason);\r
+ virtual bool Passed(bool status_ok);\r
+\r
+ const char* statement() const { return statement_; }\r
+ const RE* regex() const { return regex_; }\r
+ bool spawned() const { return spawned_; }\r
+ void set_spawned(bool is_spawned) { spawned_ = is_spawned; }\r
+ int status() const { return status_; }\r
+ void set_status(int a_status) { status_ = a_status; }\r
+ DeathTestOutcome outcome() const { return outcome_; }\r
+ void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }\r
+ int read_fd() const { return read_fd_; }\r
+ void set_read_fd(int fd) { read_fd_ = fd; }\r
+ int write_fd() const { return write_fd_; }\r
+ void set_write_fd(int fd) { write_fd_ = fd; }\r
+\r
+ // Called in the parent process only. Reads the result code of the death\r
+ // test child process via a pipe, interprets it to set the outcome_\r
+ // member, and closes read_fd_. Outputs diagnostics and terminates in\r
+ // case of unexpected codes.\r
+ void ReadAndInterpretStatusByte();\r
+\r
+ private:\r
+ // The textual content of the code this object is testing. This class\r
+ // doesn't own this string and should not attempt to delete it.\r
+ const char* const statement_;\r
+ // The regular expression which test output must match. DeathTestImpl\r
+ // doesn't own this object and should not attempt to delete it.\r
+ const RE* const regex_;\r
+ // True if the death test child process has been successfully spawned.\r
+ bool spawned_;\r
+ // The exit status of the child process.\r
+ int status_;\r
+ // How the death test concluded.\r
+ DeathTestOutcome outcome_;\r
+ // Descriptor to the read end of the pipe to the child process. It is\r
+ // always -1 in the child process. The child keeps its write end of the\r
+ // pipe in write_fd_.\r
+ int read_fd_;\r
+ // Descriptor to the child's write end of the pipe to the parent process.\r
+ // It is always -1 in the parent process. The parent keeps its end of the\r
+ // pipe in read_fd_.\r
+ int write_fd_;\r
+};\r
+\r
+// Called in the parent process only. Reads the result code of the death\r
+// test child process via a pipe, interprets it to set the outcome_\r
+// member, and closes read_fd_. Outputs diagnostics and terminates in\r
+// case of unexpected codes.\r
+void DeathTestImpl::ReadAndInterpretStatusByte() {\r
+ char flag;\r
+ int bytes_read;\r
+\r
+ // The read() here blocks until data is available (signifying the\r
+ // failure of the death test) or until the pipe is closed (signifying\r
+ // its success), so it's okay to call this in the parent before\r
+ // the child process has exited.\r
+ do {\r
+ bytes_read = posix::Read(read_fd(), &flag, 1);\r
+ } while (bytes_read == -1 && errno == EINTR);\r
+\r
+ if (bytes_read == 0) {\r
+ set_outcome(DIED);\r
+ } else if (bytes_read == 1) {\r
+ switch (flag) {\r
+ case kDeathTestReturned:\r
+ set_outcome(RETURNED);\r
+ break;\r
+ case kDeathTestThrew:\r
+ set_outcome(THREW);\r
+ break;\r
+ case kDeathTestLived:\r
+ set_outcome(LIVED);\r
+ break;\r
+ case kDeathTestInternalError:\r
+ FailFromInternalError(read_fd()); // Does not return.\r
+ break;\r
+ default:\r
+ GTEST_LOG_(FATAL) << "Death test child process reported "\r
+ << "unexpected status byte ("\r
+ << static_cast<unsigned int>(flag) << ")";\r
+ }\r
+ } else {\r
+ GTEST_LOG_(FATAL) << "Read from death test child process failed: "\r
+ << GetLastErrnoDescription();\r
+ }\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));\r
+ set_read_fd(-1);\r
+}\r
+\r
+// Signals that the death test code which should have exited, didn't.\r
+// Should be called only in a death test child process.\r
+// Writes a status byte to the child's status file descriptor, then\r
+// calls _exit(1).\r
+void DeathTestImpl::Abort(AbortReason reason) {\r
+ // The parent process considers the death test to be a failure if\r
+ // it finds any data in our pipe. So, here we write a single flag byte\r
+ // to the pipe, then exit.\r
+ const char status_ch =\r
+ reason == TEST_DID_NOT_DIE ? kDeathTestLived :\r
+ reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;\r
+\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));\r
+ // We are leaking the descriptor here because on some platforms (i.e.,\r
+ // when built as Windows DLL), destructors of global objects will still\r
+ // run after calling _exit(). On such systems, write_fd_ will be\r
+ // indirectly closed from the destructor of UnitTestImpl, causing double\r
+ // close if it is also closed here. On debug configurations, double close\r
+ // may assert. As there are no in-process buffers to flush here, we are\r
+ // relying on the OS to close the descriptor after the process terminates\r
+ // when the destructors are not run.\r
+ _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)\r
+}\r
+\r
+// Returns an indented copy of stderr output for a death test.\r
+// This makes distinguishing death test output lines from regular log lines\r
+// much easier.\r
+static ::std::string FormatDeathTestOutput(const ::std::string& output) {\r
+ ::std::string ret;\r
+ for (size_t at = 0; ; ) {\r
+ const size_t line_end = output.find('\n', at);\r
+ ret += "[ DEATH ] ";\r
+ if (line_end == ::std::string::npos) {\r
+ ret += output.substr(at);\r
+ break;\r
+ }\r
+ ret += output.substr(at, line_end + 1 - at);\r
+ at = line_end + 1;\r
+ }\r
+ return ret;\r
+}\r
+\r
+// Assesses the success or failure of a death test, using both private\r
+// members which have previously been set, and one argument:\r
+//\r
+// Private data members:\r
+// outcome: An enumeration describing how the death test\r
+// concluded: DIED, LIVED, THREW, or RETURNED. The death test\r
+// fails in the latter three cases.\r
+// status: The exit status of the child process. On *nix, it is in the\r
+// in the format specified by wait(2). On Windows, this is the\r
+// value supplied to the ExitProcess() API or a numeric code\r
+// of the exception that terminated the program.\r
+// regex: A regular expression object to be applied to\r
+// the test's captured standard error output; the death test\r
+// fails if it does not match.\r
+//\r
+// Argument:\r
+// status_ok: true if exit_status is acceptable in the context of\r
+// this particular death test, which fails if it is false\r
+//\r
+// Returns true iff all of the above conditions are met. Otherwise, the\r
+// first failing condition, in the order given above, is the one that is\r
+// reported. Also sets the last death test message string.\r
+bool DeathTestImpl::Passed(bool status_ok) {\r
+ if (!spawned())\r
+ return false;\r
+\r
+ const std::string error_message = GetCapturedStderr();\r
+\r
+ bool success = false;\r
+ Message buffer;\r
+\r
+ buffer << "Death test: " << statement() << "\n";\r
+ switch (outcome()) {\r
+ case LIVED:\r
+ buffer << " Result: failed to die.\n"\r
+ << " Error msg:\n" << FormatDeathTestOutput(error_message);\r
+ break;\r
+ case THREW:\r
+ buffer << " Result: threw an exception.\n"\r
+ << " Error msg:\n" << FormatDeathTestOutput(error_message);\r
+ break;\r
+ case RETURNED:\r
+ buffer << " Result: illegal return in test statement.\n"\r
+ << " Error msg:\n" << FormatDeathTestOutput(error_message);\r
+ break;\r
+ case DIED:\r
+ if (status_ok) {\r
+ const bool matched = RE::PartialMatch(error_message.c_str(), *regex());\r
+ if (matched) {\r
+ success = true;\r
+ } else {\r
+ buffer << " Result: died but not with expected error.\n"\r
+ << " Expected: " << regex()->pattern() << "\n"\r
+ << "Actual msg:\n" << FormatDeathTestOutput(error_message);\r
+ }\r
+ } else {\r
+ buffer << " Result: died but not with expected exit code:\n"\r
+ << " " << ExitSummary(status()) << "\n"\r
+ << "Actual msg:\n" << FormatDeathTestOutput(error_message);\r
+ }\r
+ break;\r
+ case IN_PROGRESS:\r
+ default:\r
+ GTEST_LOG_(FATAL)\r
+ << "DeathTest::Passed somehow called before conclusion of test";\r
+ }\r
+\r
+ DeathTest::set_last_death_test_message(buffer.GetString());\r
+ return success;\r
+}\r
+\r
+# if GTEST_OS_WINDOWS\r
+// WindowsDeathTest implements death tests on Windows. Due to the\r
+// specifics of starting new processes on Windows, death tests there are\r
+// always threadsafe, and Google Test considers the\r
+// --gtest_death_test_style=fast setting to be equivalent to\r
+// --gtest_death_test_style=threadsafe there.\r
+//\r
+// A few implementation notes: Like the Linux version, the Windows\r
+// implementation uses pipes for child-to-parent communication. But due to\r
+// the specifics of pipes on Windows, some extra steps are required:\r
+//\r
+// 1. The parent creates a communication pipe and stores handles to both\r
+// ends of it.\r
+// 2. The parent starts the child and provides it with the information\r
+// necessary to acquire the handle to the write end of the pipe.\r
+// 3. The child acquires the write end of the pipe and signals the parent\r
+// using a Windows event.\r
+// 4. Now the parent can release the write end of the pipe on its side. If\r
+// this is done before step 3, the object's reference count goes down to\r
+// 0 and it is destroyed, preventing the child from acquiring it. The\r
+// parent now has to release it, or read operations on the read end of\r
+// the pipe will not return when the child terminates.\r
+// 5. The parent reads child's output through the pipe (outcome code and\r
+// any possible error messages) from the pipe, and its stderr and then\r
+// determines whether to fail the test.\r
+//\r
+// Note: to distinguish Win32 API calls from the local method and function\r
+// calls, the former are explicitly resolved in the global namespace.\r
+//\r
+class WindowsDeathTest : public DeathTestImpl {\r
+ public:\r
+ WindowsDeathTest(const char* a_statement,\r
+ const RE* a_regex,\r
+ const char* file,\r
+ int line)\r
+ : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}\r
+\r
+ // All of these virtual functions are inherited from DeathTest.\r
+ virtual int Wait();\r
+ virtual TestRole AssumeRole();\r
+\r
+ private:\r
+ // The name of the file in which the death test is located.\r
+ const char* const file_;\r
+ // The line number on which the death test is located.\r
+ const int line_;\r
+ // Handle to the write end of the pipe to the child process.\r
+ AutoHandle write_handle_;\r
+ // Child process handle.\r
+ AutoHandle child_handle_;\r
+ // Event the child process uses to signal the parent that it has\r
+ // acquired the handle to the write end of the pipe. After seeing this\r
+ // event the parent can release its own handles to make sure its\r
+ // ReadFile() calls return when the child terminates.\r
+ AutoHandle event_handle_;\r
+};\r
+\r
+// Waits for the child in a death test to exit, returning its exit\r
+// status, or 0 if no child process exists. As a side effect, sets the\r
+// outcome data member.\r
+int WindowsDeathTest::Wait() {\r
+ if (!spawned())\r
+ return 0;\r
+\r
+ // Wait until the child either signals that it has acquired the write end\r
+ // of the pipe or it dies.\r
+ const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };\r
+ switch (::WaitForMultipleObjects(2,\r
+ wait_handles,\r
+ FALSE, // Waits for any of the handles.\r
+ INFINITE)) {\r
+ case WAIT_OBJECT_0:\r
+ case WAIT_OBJECT_0 + 1:\r
+ break;\r
+ default:\r
+ GTEST_DEATH_TEST_CHECK_(false); // Should not get here.\r
+ }\r
+\r
+ // The child has acquired the write end of the pipe or exited.\r
+ // We release the handle on our side and continue.\r
+ write_handle_.Reset();\r
+ event_handle_.Reset();\r
+\r
+ ReadAndInterpretStatusByte();\r
+\r
+ // Waits for the child process to exit if it haven't already. This\r
+ // returns immediately if the child has already exited, regardless of\r
+ // whether previous calls to WaitForMultipleObjects synchronized on this\r
+ // handle or not.\r
+ GTEST_DEATH_TEST_CHECK_(\r
+ WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),\r
+ INFINITE));\r
+ DWORD status_code;\r
+ GTEST_DEATH_TEST_CHECK_(\r
+ ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);\r
+ child_handle_.Reset();\r
+ set_status(static_cast<int>(status_code));\r
+ return status();\r
+}\r
+\r
+// The AssumeRole process for a Windows death test. It creates a child\r
+// process with the same executable as the current process to run the\r
+// death test. The child process is given the --gtest_filter and\r
+// --gtest_internal_run_death_test flags such that it knows to run the\r
+// current death test only.\r
+DeathTest::TestRole WindowsDeathTest::AssumeRole() {\r
+ const UnitTestImpl* const impl = GetUnitTestImpl();\r
+ const InternalRunDeathTestFlag* const flag =\r
+ impl->internal_run_death_test_flag();\r
+ const TestInfo* const info = impl->current_test_info();\r
+ const int death_test_index = info->result()->death_test_count();\r
+\r
+ if (flag != NULL) {\r
+ // ParseInternalRunDeathTestFlag() has performed all the necessary\r
+ // processing.\r
+ set_write_fd(flag->write_fd());\r
+ return EXECUTE_TEST;\r
+ }\r
+\r
+ // WindowsDeathTest uses an anonymous pipe to communicate results of\r
+ // a death test.\r
+ SECURITY_ATTRIBUTES handles_are_inheritable = {\r
+ sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };\r
+ HANDLE read_handle, write_handle;\r
+ GTEST_DEATH_TEST_CHECK_(\r
+ ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,\r
+ 0) // Default buffer size.\r
+ != FALSE);\r
+ set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),\r
+ O_RDONLY));\r
+ write_handle_.Reset(write_handle);\r
+ event_handle_.Reset(::CreateEvent(\r
+ &handles_are_inheritable,\r
+ TRUE, // The event will automatically reset to non-signaled state.\r
+ FALSE, // The initial state is non-signalled.\r
+ NULL)); // The even is unnamed.\r
+ GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);\r
+ const std::string filter_flag =\r
+ std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +\r
+ info->test_case_name() + "." + info->name();\r
+ const std::string internal_flag =\r
+ std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +\r
+ "=" + file_ + "|" + StreamableToString(line_) + "|" +\r
+ StreamableToString(death_test_index) + "|" +\r
+ StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +\r
+ // size_t has the same width as pointers on both 32-bit and 64-bit\r
+ // Windows platforms.\r
+ // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.\r
+ "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +\r
+ "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));\r
+\r
+ char executable_path[_MAX_PATH + 1]; // NOLINT\r
+ GTEST_DEATH_TEST_CHECK_(\r
+ _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,\r
+ executable_path,\r
+ _MAX_PATH));\r
+\r
+ std::string command_line =\r
+ std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +\r
+ internal_flag + "\"";\r
+\r
+ DeathTest::set_last_death_test_message("");\r
+\r
+ CaptureStderr();\r
+ // Flush the log buffers since the log streams are shared with the child.\r
+ FlushInfoLog();\r
+\r
+ // The child process will share the standard handles with the parent.\r
+ STARTUPINFOA startup_info;\r
+ memset(&startup_info, 0, sizeof(STARTUPINFO));\r
+ startup_info.dwFlags = STARTF_USESTDHANDLES;\r
+ startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);\r
+ startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);\r
+ startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);\r
+\r
+ PROCESS_INFORMATION process_info;\r
+ GTEST_DEATH_TEST_CHECK_(::CreateProcessA(\r
+ executable_path,\r
+ const_cast<char*>(command_line.c_str()),\r
+ NULL, // Retuned process handle is not inheritable.\r
+ NULL, // Retuned thread handle is not inheritable.\r
+ TRUE, // Child inherits all inheritable handles (for write_handle_).\r
+ 0x0, // Default creation flags.\r
+ NULL, // Inherit the parent's environment.\r
+ UnitTest::GetInstance()->original_working_dir(),\r
+ &startup_info,\r
+ &process_info) != FALSE);\r
+ child_handle_.Reset(process_info.hProcess);\r
+ ::CloseHandle(process_info.hThread);\r
+ set_spawned(true);\r
+ return OVERSEE_TEST;\r
+}\r
+# else // We are not on Windows.\r
+\r
+// ForkingDeathTest provides implementations for most of the abstract\r
+// methods of the DeathTest interface. Only the AssumeRole method is\r
+// left undefined.\r
+class ForkingDeathTest : public DeathTestImpl {\r
+ public:\r
+ ForkingDeathTest(const char* statement, const RE* regex);\r
+\r
+ // All of these virtual functions are inherited from DeathTest.\r
+ virtual int Wait();\r
+\r
+ protected:\r
+ void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }\r
+\r
+ private:\r
+ // PID of child process during death test; 0 in the child process itself.\r
+ pid_t child_pid_;\r
+};\r
+\r
+// Constructs a ForkingDeathTest.\r
+ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)\r
+ : DeathTestImpl(a_statement, a_regex),\r
+ child_pid_(-1) {}\r
+\r
+// Waits for the child in a death test to exit, returning its exit\r
+// status, or 0 if no child process exists. As a side effect, sets the\r
+// outcome data member.\r
+int ForkingDeathTest::Wait() {\r
+ if (!spawned())\r
+ return 0;\r
+\r
+ ReadAndInterpretStatusByte();\r
+\r
+ int status_value;\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));\r
+ set_status(status_value);\r
+ return status_value;\r
+}\r
+\r
+// A concrete death test class that forks, then immediately runs the test\r
+// in the child process.\r
+class NoExecDeathTest : public ForkingDeathTest {\r
+ public:\r
+ NoExecDeathTest(const char* a_statement, const RE* a_regex) :\r
+ ForkingDeathTest(a_statement, a_regex) { }\r
+ virtual TestRole AssumeRole();\r
+};\r
+\r
+// The AssumeRole process for a fork-and-run death test. It implements a\r
+// straightforward fork, with a simple pipe to transmit the status byte.\r
+DeathTest::TestRole NoExecDeathTest::AssumeRole() {\r
+ const size_t thread_count = GetThreadCount();\r
+ if (thread_count != 1) {\r
+ GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);\r
+ }\r
+\r
+ int pipe_fd[2];\r
+ GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);\r
+\r
+ DeathTest::set_last_death_test_message("");\r
+ CaptureStderr();\r
+ // When we fork the process below, the log file buffers are copied, but the\r
+ // file descriptors are shared. We flush all log files here so that closing\r
+ // the file descriptors in the child process doesn't throw off the\r
+ // synchronization between descriptors and buffers in the parent process.\r
+ // This is as close to the fork as possible to avoid a race condition in case\r
+ // there are multiple threads running before the death test, and another\r
+ // thread writes to the log file.\r
+ FlushInfoLog();\r
+\r
+ const pid_t child_pid = fork();\r
+ GTEST_DEATH_TEST_CHECK_(child_pid != -1);\r
+ set_child_pid(child_pid);\r
+ if (child_pid == 0) {\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));\r
+ set_write_fd(pipe_fd[1]);\r
+ // Redirects all logging to stderr in the child process to prevent\r
+ // concurrent writes to the log files. We capture stderr in the parent\r
+ // process and append the child process' output to a log.\r
+ LogToStderr();\r
+ // Event forwarding to the listeners of event listener API mush be shut\r
+ // down in death test subprocesses.\r
+ GetUnitTestImpl()->listeners()->SuppressEventForwarding();\r
+ g_in_fast_death_test_child = true;\r
+ return EXECUTE_TEST;\r
+ } else {\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));\r
+ set_read_fd(pipe_fd[0]);\r
+ set_spawned(true);\r
+ return OVERSEE_TEST;\r
+ }\r
+}\r
+\r
+// A concrete death test class that forks and re-executes the main\r
+// program from the beginning, with command-line flags set that cause\r
+// only this specific death test to be run.\r
+class ExecDeathTest : public ForkingDeathTest {\r
+ public:\r
+ ExecDeathTest(const char* a_statement, const RE* a_regex,\r
+ const char* file, int line) :\r
+ ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }\r
+ virtual TestRole AssumeRole();\r
+ private:\r
+ static ::std::vector<testing::internal::string>\r
+ GetArgvsForDeathTestChildProcess() {\r
+ ::std::vector<testing::internal::string> args = GetInjectableArgvs();\r
+# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)\r
+ ::std::vector<testing::internal::string> extra_args =\r
+ GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();\r
+ args.insert(args.end(), extra_args.begin(), extra_args.end());\r
+# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)\r
+ return args;\r
+ }\r
+ // The name of the file in which the death test is located.\r
+ const char* const file_;\r
+ // The line number on which the death test is located.\r
+ const int line_;\r
+};\r
+\r
+// Utility class for accumulating command-line arguments.\r
+class Arguments {\r
+ public:\r
+ Arguments() {\r
+ args_.push_back(NULL);\r
+ }\r
+\r
+ ~Arguments() {\r
+ for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();\r
+ ++i) {\r
+ free(*i);\r
+ }\r
+ }\r
+ void AddArgument(const char* argument) {\r
+ args_.insert(args_.end() - 1, posix::StrDup(argument));\r
+ }\r
+\r
+ template <typename Str>\r
+ void AddArguments(const ::std::vector<Str>& arguments) {\r
+ for (typename ::std::vector<Str>::const_iterator i = arguments.begin();\r
+ i != arguments.end();\r
+ ++i) {\r
+ args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));\r
+ }\r
+ }\r
+ char* const* Argv() {\r
+ return &args_[0];\r
+ }\r
+\r
+ private:\r
+ std::vector<char*> args_;\r
+};\r
+\r
+// A struct that encompasses the arguments to the child process of a\r
+// threadsafe-style death test process.\r
+struct ExecDeathTestArgs {\r
+ char* const* argv; // Command-line arguments for the child's call to exec\r
+ int close_fd; // File descriptor to close; the read end of a pipe\r
+};\r
+\r
+# if GTEST_OS_MAC\r
+inline char** GetEnviron() {\r
+ // When Google Test is built as a framework on MacOS X, the environ variable\r
+ // is unavailable. Apple's documentation (man environ) recommends using\r
+ // _NSGetEnviron() instead.\r
+ return *_NSGetEnviron();\r
+}\r
+# else\r
+// Some POSIX platforms expect you to declare environ. extern "C" makes\r
+// it reside in the global namespace.\r
+extern "C" char** environ;\r
+inline char** GetEnviron() { return environ; }\r
+# endif // GTEST_OS_MAC\r
+\r
+# if !GTEST_OS_QNX\r
+// The main function for a threadsafe-style death test child process.\r
+// This function is called in a clone()-ed process and thus must avoid\r
+// any potentially unsafe operations like malloc or libc functions.\r
+static int ExecDeathTestChildMain(void* child_arg) {\r
+ ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));\r
+\r
+ // We need to execute the test program in the same environment where\r
+ // it was originally invoked. Therefore we change to the original\r
+ // working directory first.\r
+ const char* const original_dir =\r
+ UnitTest::GetInstance()->original_working_dir();\r
+ // We can safely call chdir() as it's a direct system call.\r
+ if (chdir(original_dir) != 0) {\r
+ DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +\r
+ GetLastErrnoDescription());\r
+ return EXIT_FAILURE;\r
+ }\r
+\r
+ // We can safely call execve() as it's a direct system call. We\r
+ // cannot use execvp() as it's a libc function and thus potentially\r
+ // unsafe. Since execve() doesn't search the PATH, the user must\r
+ // invoke the test program via a valid path that contains at least\r
+ // one path separator.\r
+ execve(args->argv[0], args->argv, GetEnviron());\r
+ DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +\r
+ original_dir + " failed: " +\r
+ GetLastErrnoDescription());\r
+ return EXIT_FAILURE;\r
+}\r
+# endif // !GTEST_OS_QNX\r
+\r
+// Two utility routines that together determine the direction the stack\r
+// grows.\r
+// This could be accomplished more elegantly by a single recursive\r
+// function, but we want to guard against the unlikely possibility of\r
+// a smart compiler optimizing the recursion away.\r
+//\r
+// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining\r
+// StackLowerThanAddress into StackGrowsDown, which then doesn't give\r
+// correct answer.\r
+void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;\r
+void StackLowerThanAddress(const void* ptr, bool* result) {\r
+ int dummy;\r
+ *result = (&dummy < ptr);\r
+}\r
+\r
+// Make sure AddressSanitizer does not tamper with the stack here.\r
+GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\r
+bool StackGrowsDown() {\r
+ int dummy;\r
+ bool result;\r
+ StackLowerThanAddress(&dummy, &result);\r
+ return result;\r
+}\r
+\r
+// Spawns a child process with the same executable as the current process in\r
+// a thread-safe manner and instructs it to run the death test. The\r
+// implementation uses fork(2) + exec. On systems where clone(2) is\r
+// available, it is used instead, being slightly more thread-safe. On QNX,\r
+// fork supports only single-threaded environments, so this function uses\r
+// spawn(2) there instead. The function dies with an error message if\r
+// anything goes wrong.\r
+static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {\r
+ ExecDeathTestArgs args = { argv, close_fd };\r
+ pid_t child_pid = -1;\r
+\r
+# if GTEST_OS_QNX\r
+ // Obtains the current directory and sets it to be closed in the child\r
+ // process.\r
+ const int cwd_fd = open(".", O_RDONLY);\r
+ GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));\r
+ // We need to execute the test program in the same environment where\r
+ // it was originally invoked. Therefore we change to the original\r
+ // working directory first.\r
+ const char* const original_dir =\r
+ UnitTest::GetInstance()->original_working_dir();\r
+ // We can safely call chdir() as it's a direct system call.\r
+ if (chdir(original_dir) != 0) {\r
+ DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +\r
+ GetLastErrnoDescription());\r
+ return EXIT_FAILURE;\r
+ }\r
+\r
+ int fd_flags;\r
+ // Set close_fd to be closed after spawn.\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,\r
+ fd_flags | FD_CLOEXEC));\r
+ struct inheritance inherit = {0};\r
+ // spawn is a system call.\r
+ child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());\r
+ // Restores the current working directory.\r
+ GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));\r
+\r
+# else // GTEST_OS_QNX\r
+# if GTEST_OS_LINUX\r
+ // When a SIGPROF signal is received while fork() or clone() are executing,\r
+ // the process may hang. To avoid this, we ignore SIGPROF here and re-enable\r
+ // it after the call to fork()/clone() is complete.\r
+ struct sigaction saved_sigprof_action;\r
+ struct sigaction ignore_sigprof_action;\r
+ memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));\r
+ sigemptyset(&ignore_sigprof_action.sa_mask);\r
+ ignore_sigprof_action.sa_handler = SIG_IGN;\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(\r
+ SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));\r
+# endif // GTEST_OS_LINUX\r
+\r
+# if GTEST_HAS_CLONE\r
+ const bool use_fork = GTEST_FLAG(death_test_use_fork);\r
+\r
+ if (!use_fork) {\r
+ static const bool stack_grows_down = StackGrowsDown();\r
+ const size_t stack_size = getpagesize();\r
+ // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.\r
+ void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,\r
+ MAP_ANON | MAP_PRIVATE, -1, 0);\r
+ GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);\r
+\r
+ // Maximum stack alignment in bytes: For a downward-growing stack, this\r
+ // amount is subtracted from size of the stack space to get an address\r
+ // that is within the stack space and is aligned on all systems we care\r
+ // about. As far as I know there is no ABI with stack alignment greater\r
+ // than 64. We assume stack and stack_size already have alignment of\r
+ // kMaxStackAlignment.\r
+ const size_t kMaxStackAlignment = 64;\r
+ void* const stack_top =\r
+ static_cast<char*>(stack) +\r
+ (stack_grows_down ? stack_size - kMaxStackAlignment : 0);\r
+ GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&\r
+ reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);\r
+\r
+ child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);\r
+\r
+ GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);\r
+ }\r
+# else\r
+ const bool use_fork = true;\r
+# endif // GTEST_HAS_CLONE\r
+\r
+ if (use_fork && (child_pid = fork()) == 0) {\r
+ ExecDeathTestChildMain(&args);\r
+ _exit(0);\r
+ }\r
+# endif // GTEST_OS_QNX\r
+# if GTEST_OS_LINUX\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(\r
+ sigaction(SIGPROF, &saved_sigprof_action, NULL));\r
+# endif // GTEST_OS_LINUX\r
+\r
+ GTEST_DEATH_TEST_CHECK_(child_pid != -1);\r
+ return child_pid;\r
+}\r
+\r
+// The AssumeRole process for a fork-and-exec death test. It re-executes the\r
+// main program from the beginning, setting the --gtest_filter\r
+// and --gtest_internal_run_death_test flags to cause only the current\r
+// death test to be re-run.\r
+DeathTest::TestRole ExecDeathTest::AssumeRole() {\r
+ const UnitTestImpl* const impl = GetUnitTestImpl();\r
+ const InternalRunDeathTestFlag* const flag =\r
+ impl->internal_run_death_test_flag();\r
+ const TestInfo* const info = impl->current_test_info();\r
+ const int death_test_index = info->result()->death_test_count();\r
+\r
+ if (flag != NULL) {\r
+ set_write_fd(flag->write_fd());\r
+ return EXECUTE_TEST;\r
+ }\r
+\r
+ int pipe_fd[2];\r
+ GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);\r
+ // Clear the close-on-exec flag on the write end of the pipe, lest\r
+ // it be closed when the child process does an exec:\r
+ GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);\r
+\r
+ const std::string filter_flag =\r
+ std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="\r
+ + info->test_case_name() + "." + info->name();\r
+ const std::string internal_flag =\r
+ std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="\r
+ + file_ + "|" + StreamableToString(line_) + "|"\r
+ + StreamableToString(death_test_index) + "|"\r
+ + StreamableToString(pipe_fd[1]);\r
+ Arguments args;\r
+ args.AddArguments(GetArgvsForDeathTestChildProcess());\r
+ args.AddArgument(filter_flag.c_str());\r
+ args.AddArgument(internal_flag.c_str());\r
+\r
+ DeathTest::set_last_death_test_message("");\r
+\r
+ CaptureStderr();\r
+ // See the comment in NoExecDeathTest::AssumeRole for why the next line\r
+ // is necessary.\r
+ FlushInfoLog();\r
+\r
+ const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);\r
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));\r
+ set_child_pid(child_pid);\r
+ set_read_fd(pipe_fd[0]);\r
+ set_spawned(true);\r
+ return OVERSEE_TEST;\r
+}\r
+\r
+# endif // !GTEST_OS_WINDOWS\r
+\r
+// Creates a concrete DeathTest-derived class that depends on the\r
+// --gtest_death_test_style flag, and sets the pointer pointed to\r
+// by the "test" argument to its address. If the test should be\r
+// skipped, sets that pointer to NULL. Returns true, unless the\r
+// flag is set to an invalid value.\r
+bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,\r
+ const char* file, int line,\r
+ DeathTest** test) {\r
+ UnitTestImpl* const impl = GetUnitTestImpl();\r
+ const InternalRunDeathTestFlag* const flag =\r
+ impl->internal_run_death_test_flag();\r
+ const int death_test_index = impl->current_test_info()\r
+ ->increment_death_test_count();\r
+\r
+ if (flag != NULL) {\r
+ if (death_test_index > flag->index()) {\r
+ DeathTest::set_last_death_test_message(\r
+ "Death test count (" + StreamableToString(death_test_index)\r
+ + ") somehow exceeded expected maximum ("\r
+ + StreamableToString(flag->index()) + ")");\r
+ return false;\r
+ }\r
+\r
+ if (!(flag->file() == file && flag->line() == line &&\r
+ flag->index() == death_test_index)) {\r
+ *test = NULL;\r
+ return true;\r
+ }\r
+ }\r
+\r
+# if GTEST_OS_WINDOWS\r
+\r
+ if (GTEST_FLAG(death_test_style) == "threadsafe" ||\r
+ GTEST_FLAG(death_test_style) == "fast") {\r
+ *test = new WindowsDeathTest(statement, regex, file, line);\r
+ }\r
+\r
+# else\r
+\r
+ if (GTEST_FLAG(death_test_style) == "threadsafe") {\r
+ *test = new ExecDeathTest(statement, regex, file, line);\r
+ } else if (GTEST_FLAG(death_test_style) == "fast") {\r
+ *test = new NoExecDeathTest(statement, regex);\r
+ }\r
+\r
+# endif // GTEST_OS_WINDOWS\r
+\r
+ else { // NOLINT - this is more readable than unbalanced brackets inside #if.\r
+ DeathTest::set_last_death_test_message(\r
+ "Unknown death test style \"" + GTEST_FLAG(death_test_style)\r
+ + "\" encountered");\r
+ return false;\r
+ }\r
+\r
+ return true;\r
+}\r
+\r
+# if GTEST_OS_WINDOWS\r
+// Recreates the pipe and event handles from the provided parameters,\r
+// signals the event, and returns a file descriptor wrapped around the pipe\r
+// handle. This function is called in the child process only.\r
+int GetStatusFileDescriptor(unsigned int parent_process_id,\r
+ size_t write_handle_as_size_t,\r
+ size_t event_handle_as_size_t) {\r
+ AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,\r
+ FALSE, // Non-inheritable.\r
+ parent_process_id));\r
+ if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {\r
+ DeathTestAbort("Unable to open parent process " +\r
+ StreamableToString(parent_process_id));\r
+ }\r
+\r
+ // TODO(vladl@google.com): Replace the following check with a\r
+ // compile-time assertion when available.\r
+ GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));\r
+\r
+ const HANDLE write_handle =\r
+ reinterpret_cast<HANDLE>(write_handle_as_size_t);\r
+ HANDLE dup_write_handle;\r
+\r
+ // The newly initialized handle is accessible only in in the parent\r
+ // process. To obtain one accessible within the child, we need to use\r
+ // DuplicateHandle.\r
+ if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,\r
+ ::GetCurrentProcess(), &dup_write_handle,\r
+ 0x0, // Requested privileges ignored since\r
+ // DUPLICATE_SAME_ACCESS is used.\r
+ FALSE, // Request non-inheritable handler.\r
+ DUPLICATE_SAME_ACCESS)) {\r
+ DeathTestAbort("Unable to duplicate the pipe handle " +\r
+ StreamableToString(write_handle_as_size_t) +\r
+ " from the parent process " +\r
+ StreamableToString(parent_process_id));\r
+ }\r
+\r
+ const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);\r
+ HANDLE dup_event_handle;\r
+\r
+ if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,\r
+ ::GetCurrentProcess(), &dup_event_handle,\r
+ 0x0,\r
+ FALSE,\r
+ DUPLICATE_SAME_ACCESS)) {\r
+ DeathTestAbort("Unable to duplicate the event handle " +\r
+ StreamableToString(event_handle_as_size_t) +\r
+ " from the parent process " +\r
+ StreamableToString(parent_process_id));\r
+ }\r
+\r
+ const int write_fd =\r
+ ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);\r
+ if (write_fd == -1) {\r
+ DeathTestAbort("Unable to convert pipe handle " +\r
+ StreamableToString(write_handle_as_size_t) +\r
+ " to a file descriptor");\r
+ }\r
+\r
+ // Signals the parent that the write end of the pipe has been acquired\r
+ // so the parent can release its own write end.\r
+ ::SetEvent(dup_event_handle);\r
+\r
+ return write_fd;\r
+}\r
+# endif // GTEST_OS_WINDOWS\r
+\r
+// Returns a newly created InternalRunDeathTestFlag object with fields\r
+// initialized from the GTEST_FLAG(internal_run_death_test) flag if\r
+// the flag is specified; otherwise returns NULL.\r
+InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {\r
+ if (GTEST_FLAG(internal_run_death_test) == "") return NULL;\r
+\r
+ // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we\r
+ // can use it here.\r
+ int line = -1;\r
+ int index = -1;\r
+ ::std::vector< ::std::string> fields;\r
+ SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);\r
+ int write_fd = -1;\r
+\r
+# if GTEST_OS_WINDOWS\r
+\r
+ unsigned int parent_process_id = 0;\r
+ size_t write_handle_as_size_t = 0;\r
+ size_t event_handle_as_size_t = 0;\r
+\r
+ if (fields.size() != 6\r
+ || !ParseNaturalNumber(fields[1], &line)\r
+ || !ParseNaturalNumber(fields[2], &index)\r
+ || !ParseNaturalNumber(fields[3], &parent_process_id)\r
+ || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)\r
+ || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {\r
+ DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +\r
+ GTEST_FLAG(internal_run_death_test));\r
+ }\r
+ write_fd = GetStatusFileDescriptor(parent_process_id,\r
+ write_handle_as_size_t,\r
+ event_handle_as_size_t);\r
+# else\r
+\r
+ if (fields.size() != 4\r
+ || !ParseNaturalNumber(fields[1], &line)\r
+ || !ParseNaturalNumber(fields[2], &index)\r
+ || !ParseNaturalNumber(fields[3], &write_fd)) {\r
+ DeathTestAbort("Bad --gtest_internal_run_death_test flag: "\r
+ + GTEST_FLAG(internal_run_death_test));\r
+ }\r
+\r
+# endif // GTEST_OS_WINDOWS\r
+\r
+ return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);\r
+}\r
+\r
+} // namespace internal\r
+\r
+#endif // GTEST_HAS_DEATH_TEST\r
+\r
+} // namespace testing\r
+// Copyright 2008, Google Inc.\r
+// All rights reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+//\r
+// Authors: keith.ray@gmail.com (Keith Ray)\r
+\r
+\r
+#include <stdlib.h>\r
+\r
+#if GTEST_OS_WINDOWS_MOBILE\r
+# include <windows.h>\r
+#elif GTEST_OS_WINDOWS\r
+# include <direct.h>\r
+# include <io.h>\r
+#elif GTEST_OS_SYMBIAN\r
+// Symbian OpenC has PATH_MAX in sys/syslimits.h\r
+# include <sys/syslimits.h>\r
+#else\r
+# include <limits.h>\r
+# include <climits> // Some Linux distributions define PATH_MAX here.\r
+#endif // GTEST_OS_WINDOWS_MOBILE\r
+\r
+#if GTEST_OS_WINDOWS\r
+# define GTEST_PATH_MAX_ _MAX_PATH\r
+#elif defined(PATH_MAX)\r
+# define GTEST_PATH_MAX_ PATH_MAX\r
+#elif defined(_XOPEN_PATH_MAX)\r
+# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX\r
+#else\r
+# define GTEST_PATH_MAX_ _POSIX_PATH_MAX\r
+#endif // GTEST_OS_WINDOWS\r
+\r
+\r
+namespace testing {\r
+namespace internal {\r
+\r
+#if GTEST_OS_WINDOWS\r
+// On Windows, '\\' is the standard path separator, but many tools and the\r
+// Windows API also accept '/' as an alternate path separator. Unless otherwise\r
+// noted, a file path can contain either kind of path separators, or a mixture\r
+// of them.\r
+const char kPathSeparator = '\\';\r
+const char kAlternatePathSeparator = '/';\r
+const char kAlternatePathSeparatorString[] = "/";\r
+# if GTEST_OS_WINDOWS_MOBILE\r
+// Windows CE doesn't have a current directory. You should not use\r
+// the current directory in tests on Windows CE, but this at least\r
+// provides a reasonable fallback.\r
+const char kCurrentDirectoryString[] = "\\";\r
+// Windows CE doesn't define INVALID_FILE_ATTRIBUTES\r
+const DWORD kInvalidFileAttributes = 0xffffffff;\r
+# else\r
+const char kCurrentDirectoryString[] = ".\\";\r
+# endif // GTEST_OS_WINDOWS_MOBILE\r
+#else\r
+const char kPathSeparator = '/';\r
+const char kCurrentDirectoryString[] = "./";\r
+#endif // GTEST_OS_WINDOWS\r
+\r
+// Returns whether the given character is a valid path separator.\r
+static bool IsPathSeparator(char c) {\r
+#if GTEST_HAS_ALT_PATH_SEP_\r
+ return (c == kPathSeparator) || (c == kAlternatePathSeparator);\r
+#else\r
+ return c == kPathSeparator;\r
+#endif\r
+}\r
+\r
+// Returns the current working directory, or "" if unsuccessful.\r
+FilePath FilePath::GetCurrentDir() {\r
+#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT\r
+ // Windows CE doesn't have a current directory, so we just return\r
+ // something reasonable.\r
+ return FilePath(kCurrentDirectoryString);\r
+#elif GTEST_OS_WINDOWS\r
+ char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };\r
+ return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);\r
+#else\r
+ char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };\r
+ char* result = getcwd(cwd, sizeof(cwd));\r
+# if GTEST_OS_NACL\r
+ // getcwd will likely fail in NaCl due to the sandbox, so return something\r
+ // reasonable. The user may have provided a shim implementation for getcwd,\r
+ // however, so fallback only when failure is detected.\r
+ return FilePath(result == NULL ? kCurrentDirectoryString : cwd);\r
+# endif // GTEST_OS_NACL\r
+ return FilePath(result == NULL ? "" : cwd);\r
+#endif // GTEST_OS_WINDOWS_MOBILE\r
+}\r
+\r
+// Returns a copy of the FilePath with the case-insensitive extension removed.\r
+// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns\r
+// FilePath("dir/file"). If a case-insensitive extension is not\r
+// found, returns a copy of the original FilePath.\r
+FilePath FilePath::RemoveExtension(const char* extension) const {\r
+ const std::string dot_extension = std::string(".") + extension;\r
+ if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {\r
+ return FilePath(pathname_.substr(\r
+ 0, pathname_.length() - dot_extension.length()));\r
+ }\r
+ return *this;\r
+}\r
+\r
+// Returns a pointer to the last occurence of a valid path separator in\r
+// the FilePath. On Windows, for example, both '/' and '\' are valid path\r
+// separators. Returns NULL if no path separator was found.\r
+const char* FilePath::FindLastPathSeparator() const {\r
+ const char* const last_sep = strrchr(c_str(), kPathSeparator);\r
+#if GTEST_HAS_ALT_PATH_SEP_\r
+ const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);\r
+ // Comparing two pointers of which only one is NULL is undefined.\r
+ if (last_alt_sep != NULL &&\r
+ (last_sep == NULL || last_alt_sep > last_sep)) {\r
+ return last_alt_sep;\r
+ }\r
+#endif\r
+ return last_sep;\r
+}\r
+\r
+// Returns a copy of the FilePath with the directory part removed.\r
+// Example: FilePath("path/to/file").RemoveDirectoryName() returns\r
+// FilePath("file"). If there is no directory part ("just_a_file"), it returns\r
+// the FilePath unmodified. If there is no file part ("just_a_dir/") it\r
+// returns an empty FilePath ("").\r
+// On Windows platform, '\' is the path separator, otherwise it is '/'.\r
+FilePath FilePath::RemoveDirectoryName() const {\r
+ const char* const last_sep = FindLastPathSeparator();\r
+ return last_sep ? FilePath(last_sep + 1) : *this;\r
+}\r
+\r
+// RemoveFileName returns the directory path with the filename removed.\r
+// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".\r
+// If the FilePath is "a_file" or "/a_file", RemoveFileName returns\r
+// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does\r
+// not have a file, like "just/a/dir/", it returns the FilePath unmodified.\r
+// On Windows platform, '\' is the path separator, otherwise it is '/'.\r
+FilePath FilePath::RemoveFileName() const {\r
+ const char* const last_sep = FindLastPathSeparator();\r
+ std::string dir;\r
+ if (last_sep) {\r
+ dir = std::string(c_str(), last_sep + 1 - c_str());\r
+ } else {\r
+ dir = kCurrentDirectoryString;\r
+ }\r
+ return FilePath(dir);\r
+}\r
+\r
+// Helper functions for naming files in a directory for xml output.\r
+\r
+// Given directory = "dir", base_name = "test", number = 0,\r
+// extension = "xml", returns "dir/test.xml". If number is greater\r
+// than zero (e.g., 12), returns "dir/test_12.xml".\r
+// On Windows platform, uses \ as the separator rather than /.\r
+FilePath FilePath::MakeFileName(const FilePath& directory,\r
+ const FilePath& base_name,\r
+ int number,\r
+ const char* extension) {\r
+ std::string file;\r
+ if (number == 0) {\r
+ file = base_name.string() + "." + extension;\r
+ } else {\r
+ file = base_name.string() + "_" + StreamableToString(number)\r
+ + "." + extension;\r
+ }\r
+ return ConcatPaths(directory, FilePath(file));\r
+}\r
+\r
+// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".\r
+// On Windows, uses \ as the separator rather than /.\r
+FilePath FilePath::ConcatPaths(const FilePath& directory,\r
+ const FilePath& relative_path) {\r
+ if (directory.IsEmpty())\r
+ return relative_path;\r
+ const FilePath dir(directory.RemoveTrailingPathSeparator());\r
+ return FilePath(dir.string() + kPathSeparator + relative_path.string());\r
+}\r
+\r
+// Returns true if pathname describes something findable in the file-system,\r
+// either a file, directory, or whatever.\r
+bool FilePath::FileOrDirectoryExists() const {\r
+#if GTEST_OS_WINDOWS_MOBILE\r
+ LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());\r
+ const DWORD attributes = GetFileAttributes(unicode);\r
+ delete [] unicode;\r
+ return attributes != kInvalidFileAttributes;\r
+#else\r
+ posix::StatStruct file_stat;\r
+ return posix::Stat(pathname_.c_str(), &file_stat) == 0;\r
+#endif // GTEST_OS_WINDOWS_MOBILE\r
+}\r
+\r
+// Returns true if pathname describes a directory in the file-system\r
+// that exists.\r
+bool FilePath::DirectoryExists() const {\r
+ bool result = false;\r
+#if GTEST_OS_WINDOWS\r
+ // Don't strip off trailing separator if path is a root directory on\r
+ // Windows (like "C:\\").\r
+ const FilePath& path(IsRootDirectory() ? *this :\r
+ RemoveTrailingPathSeparator());\r
+#else\r
+ const FilePath& path(*this);\r
+#endif\r
+\r
+#if GTEST_OS_WINDOWS_MOBILE\r
+ LPCWSTR unicode = String::AnsiToUtf16(path.c_str());\r
+ const DWORD attributes = GetFileAttributes(unicode);\r
+ delete [] unicode;\r
+ if ((attributes != kInvalidFileAttributes) &&\r
+ (attributes & FILE_ATTRIBUTE_DIRECTORY)) {\r
+ result = true;\r
+ }\r
+#else\r
+ posix::StatStruct file_stat;\r
+ result = posix::Stat(path.c_str(), &file_stat) == 0 &&\r
+ posix::IsDir(file_stat);\r
+#endif // GTEST_OS_WINDOWS_MOBILE\r
+\r
+ return result;\r
+}\r
+\r
+// Returns true if pathname describes a root directory. (Windows has one\r
+// root directory per disk drive.)\r
+bool FilePath::IsRootDirectory() const {\r
+#if GTEST_OS_WINDOWS\r
+ // TODO(wan@google.com): on Windows a network share like\r
+ // \\server\share can be a root directory, although it cannot be the\r
+ // current directory. Handle this properly.\r
+ return pathname_.length() == 3 && IsAbsolutePath();\r
+#else\r
+ return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);\r
+#endif\r
+}\r
+\r
+// Returns true if pathname describes an absolute path.\r
+bool FilePath::IsAbsolutePath() const {\r
+ const char* const name = pathname_.c_str();\r
+#if GTEST_OS_WINDOWS\r
+ return pathname_.length() >= 3 &&\r
+ ((name[0] >= 'a' && name[0] <= 'z') ||\r
+ (name[0] >= 'A' && name[0] <= 'Z')) &&\r
+ name[1] == ':' &&\r
+ IsPathSeparator(name[2]);\r
+#else\r
+ return IsPathSeparator(name[0]);\r
+#endif\r
+}\r
+\r
+// Returns a pathname for a file that does not currently exist. The pathname\r
+// will be directory/base_name.extension or\r
+// directory/base_name_<number>.extension if directory/base_name.extension\r
+// already exists. The number will be incremented until a pathname is found\r
+// that does not already exist.\r
+// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.\r
+// There could be a race condition if two or more processes are calling this\r
+// function at the same time -- they could both pick the same filename.\r
+FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,\r
+ const FilePath& base_name,\r
+ const char* extension) {\r
+ FilePath full_pathname;\r
+ int number = 0;\r
+ do {\r
+ full_pathname.Set(MakeFileName(directory, base_name, number++, extension));\r
+ } while (full_pathname.FileOrDirectoryExists());\r
+ return full_pathname;\r
+}\r
+\r
+// Returns true if FilePath ends with a path separator, which indicates that\r
+// it is intended to represent a directory. Returns false otherwise.\r
+// This does NOT check that a directory (or file) actually exists.\r
+bool FilePath::IsDirectory() const {\r
+ return !pathname_.empty() &&\r
+ IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);\r
+}\r
+\r
+// Create directories so that path exists. Returns true if successful or if\r
+// the directories already exist; returns false if unable to create directories\r
+// for any reason.\r
+bool FilePath::CreateDirectoriesRecursively() const {\r
+ if (!this->IsDirectory()) {\r
+ return false;\r
+ }\r
+\r
+ if (pathname_.length() == 0 || this->DirectoryExists()) {\r
+ return true;\r
+ }\r
+\r
+ const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());\r
+ return parent.CreateDirectoriesRecursively() && this->CreateFolder();\r
+}\r
+\r
+// Create the directory so that path exists. Returns true if successful or\r
+// if the directory already exists; returns false if unable to create the\r
+// directory for any reason, including if the parent directory does not\r
+// exist. Not named "CreateDirectory" because that's a macro on Windows.\r
+bool FilePath::CreateFolder() const {\r
+#if GTEST_OS_WINDOWS_MOBILE\r
+ FilePath removed_sep(this->RemoveTrailingPathSeparator());\r
+ LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());\r
+ int result = CreateDirectory(unicode, NULL) ? 0 : -1;\r
+ delete [] unicode;\r
+#elif GTEST_OS_WINDOWS\r
+ int result = _mkdir(pathname_.c_str());\r
+#else\r
+ int result = mkdir(pathname_.c_str(), 0777);\r
+#endif // GTEST_OS_WINDOWS_MOBILE\r
+\r
+ if (result == -1) {\r
+ return this->DirectoryExists(); // An error is OK if the directory exists.\r
+ }\r
+ return true; // No error.\r
+}\r
+\r
+// If input name has a trailing separator character, remove it and return the\r
+// name, otherwise return the name string unmodified.\r
+// On Windows platform, uses \ as the separator, other platforms use /.\r
+FilePath FilePath::RemoveTrailingPathSeparator() const {\r
+ return IsDirectory()\r
+ ? FilePath(pathname_.substr(0, pathname_.length() - 1))\r
+ : *this;\r
+}\r
+\r
+// Removes any redundant separators that might be in the pathname.\r
+// For example, "bar///foo" becomes "bar/foo". Does not eliminate other\r
+// redundancies that might be in a pathname involving "." or "..".\r
+// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).\r
+void FilePath::Normalize() {\r
+ if (pathname_.c_str() == NULL) {\r
+ pathname_ = "";\r
+ return;\r
+ }\r
+ const char* src = pathname_.c_str();\r
+ char* const dest = new char[pathname_.length() + 1];\r
+ char* dest_ptr = dest;\r
+ memset(dest_ptr, 0, pathname_.length() + 1);\r
+\r
+ while (*src != '\0') {\r
+ *dest_ptr = *src;\r
+ if (!IsPathSeparator(*src)) {\r
+ src++;\r
+ } else {\r
+#if GTEST_HAS_ALT_PATH_SEP_\r
+ if (*dest_ptr == kAlternatePathSeparator) {\r
+ *dest_ptr = kPathSeparator;\r
+ }\r
+#endif\r
+ while (IsPathSeparator(*src))\r
+ src++;\r
+ }\r
+ dest_ptr++;\r
+ }\r
+ *dest_ptr = '\0';\r
+ pathname_ = dest;\r
+ delete[] dest;\r
+}\r
+\r
+} // namespace internal\r
+} // namespace testing\r
+// Copyright 2008, Google Inc.\r
+// All rights reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+//\r
+// Author: wan@google.com (Zhanyong Wan)\r
+\r
+\r
+#include <limits.h>\r
+#include <stdlib.h>\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <fstream>\r
+\r
+#if GTEST_OS_WINDOWS\r
+# include <windows.h>\r
+# include <io.h>\r
+# include <sys/stat.h>\r
+# include <map> // Used in ThreadLocal.\r
+#else\r
+# include <unistd.h>\r
+#endif // GTEST_OS_WINDOWS\r
+\r
+#if GTEST_OS_MAC\r
+# include <mach/mach_init.h>\r
+# include <mach/task.h>\r
+# include <mach/vm_map.h>\r
+#endif // GTEST_OS_MAC\r
+\r
+#if GTEST_OS_QNX\r
+# include <devctl.h>\r
+# include <fcntl.h>\r
+# include <sys/procfs.h>\r
+#endif // GTEST_OS_QNX\r
+\r
+\r
+// Indicates that this translation unit is part of Google Test's\r
+// implementation. It must come before gtest-internal-inl.h is\r
+// included, or there will be a compiler error. This trick exists to\r
+// prevent the accidental inclusion of gtest-internal-inl.h in the\r
+// user's code.\r
+#define GTEST_IMPLEMENTATION_ 1\r
+#undef GTEST_IMPLEMENTATION_\r
+\r
+namespace testing {\r
+namespace internal {\r
+\r
+#if defined(_MSC_VER) || defined(__BORLANDC__)\r
+// MSVC and C++Builder do not provide a definition of STDERR_FILENO.\r
+const int kStdOutFileno = 1;\r
+const int kStdErrFileno = 2;\r
+#else\r
+const int kStdOutFileno = STDOUT_FILENO;\r
+const int kStdErrFileno = STDERR_FILENO;\r
+#endif // _MSC_VER\r
+\r
+#if GTEST_OS_LINUX\r
+\r
+namespace {\r
+template <typename T>\r
+T ReadProcFileField(const string& filename, int field) {\r
+ std::string dummy;\r
+ std::ifstream file(filename.c_str());\r
+ while (field-- > 0) {\r
+ file >> dummy;\r
+ }\r
+ T output = 0;\r
+ file >> output;\r
+ return output;\r
+}\r
+} // namespace\r
+\r
+// Returns the number of active threads, or 0 when there is an error.\r
+size_t GetThreadCount() {\r
+ const string filename =\r
+ (Message() << "/proc/" << getpid() << "/stat").GetString();\r
+ return ReadProcFileField<int>(filename, 19);\r
+}\r
+\r
+#elif GTEST_OS_MAC\r
+\r
+size_t GetThreadCount() {\r
+ const task_t task = mach_task_self();\r
+ mach_msg_type_number_t thread_count;\r
+ thread_act_array_t thread_list;\r
+ const kern_return_t status = task_threads(task, &thread_list, &thread_count);\r
+ if (status == KERN_SUCCESS) {\r
+ // task_threads allocates resources in thread_list and we need to free them\r
+ // to avoid leaks.\r
+ vm_deallocate(task,\r
+ reinterpret_cast<vm_address_t>(thread_list),\r
+ sizeof(thread_t) * thread_count);\r
+ return static_cast<size_t>(thread_count);\r
+ } else {\r
+ return 0;\r
+ }\r
+}\r
+\r
+#elif GTEST_OS_QNX\r
+\r
+// Returns the number of threads running in the process, or 0 to indicate that\r
+// we cannot detect it.\r
+size_t GetThreadCount() {\r
+ const int fd = open("/proc/self/as", O_RDONLY);\r
+ if (fd < 0) {\r
+ return 0;\r
+ }\r
+ procfs_info process_info;\r
+ const int status =\r
+ devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);\r
+ close(fd);\r
+ if (status == EOK) {\r
+ return static_cast<size_t>(process_info.num_threads);\r
+ } else {\r
+ return 0;\r
+ }\r
+}\r
+\r
+#else\r
+\r
+size_t GetThreadCount() {\r
+ // There's no portable way to detect the number of threads, so we just\r
+ // return 0 to indicate that we cannot detect it.\r
+ return 0;\r
+}\r
+\r
+#endif // GTEST_OS_LINUX\r
+\r
+#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS\r
+\r
+void SleepMilliseconds(int n) {\r
+ ::Sleep(n);\r
+}\r
+\r
+AutoHandle::AutoHandle()\r
+ : handle_(INVALID_HANDLE_VALUE) {}\r
+\r
+AutoHandle::AutoHandle(Handle handle)\r
+ : handle_(handle) {}\r
+\r
+AutoHandle::~AutoHandle() {\r
+ Reset();\r
+}\r
+\r
+AutoHandle::Handle AutoHandle::Get() const {\r
+ return handle_;\r
+}\r
+\r
+void AutoHandle::Reset() {\r
+ Reset(INVALID_HANDLE_VALUE);\r
+}\r
+\r
+void AutoHandle::Reset(HANDLE handle) {\r
+ // Resetting with the same handle we already own is invalid.\r
+ if (handle_ != handle) {\r
+ if (IsCloseable()) {\r
+ ::CloseHandle(handle_);\r
+ }\r
+ handle_ = handle;\r
+ } else {\r
+ GTEST_CHECK_(!IsCloseable())\r
+ << "Resetting a valid handle to itself is likely a programmer error "\r
+ "and thus not allowed.";\r
+ }\r
+}\r
+\r
+bool AutoHandle::IsCloseable() const {\r
+ // Different Windows APIs may use either of these values to represent an\r
+ // invalid handle.\r
+ return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;\r
+}\r
+\r
+Notification::Notification()\r
+ : event_(::CreateEvent(NULL, // Default security attributes.\r
+ TRUE, // Do not reset automatically.\r
+ FALSE, // Initially unset.\r
+ NULL)) { // Anonymous event.\r
+ GTEST_CHECK_(event_.Get() != NULL);\r
+}\r
+\r
+void Notification::Notify() {\r
+ GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);\r
+}\r
+\r
+void Notification::WaitForNotification() {\r
+ GTEST_CHECK_(\r
+ ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);\r
+}\r
+\r
+Mutex::Mutex()\r
+ : owner_thread_id_(0),\r
+ type_(kDynamic),\r
+ critical_section_init_phase_(0),\r
+ critical_section_(new CRITICAL_SECTION) {\r
+ ::InitializeCriticalSection(critical_section_);\r
+}\r
+\r
+Mutex::~Mutex() {\r
+ // Static mutexes are leaked intentionally. It is not thread-safe to try\r
+ // to clean them up.\r
+ // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires\r
+ // nothing to clean it up but is available only on Vista and later.\r
+ // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx\r
+ if (type_ == kDynamic) {\r
+ ::DeleteCriticalSection(critical_section_);\r
+ delete critical_section_;\r
+ critical_section_ = NULL;\r
+ }\r
+}\r
+\r
+void Mutex::Lock() {\r
+ ThreadSafeLazyInit();\r
+ ::EnterCriticalSection(critical_section_);\r
+ owner_thread_id_ = ::GetCurrentThreadId();\r
+}\r
+\r
+void Mutex::Unlock() {\r
+ ThreadSafeLazyInit();\r
+ // We don't protect writing to owner_thread_id_ here, as it's the\r
+ // caller's responsibility to ensure that the current thread holds the\r
+ // mutex when this is called.\r
+ owner_thread_id_ = 0;\r
+ ::LeaveCriticalSection(critical_section_);\r
+}\r
+\r
+// Does nothing if the current thread holds the mutex. Otherwise, crashes\r
+// with high probability.\r
+void Mutex::AssertHeld() {\r
+ ThreadSafeLazyInit();\r
+ GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())\r
+ << "The current thread is not holding the mutex @" << this;\r
+}\r
+\r
+// Initializes owner_thread_id_ and critical_section_ in static mutexes.\r
+void Mutex::ThreadSafeLazyInit() {\r
+ // Dynamic mutexes are initialized in the constructor.\r
+ if (type_ == kStatic) {\r
+ switch (\r
+ ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {\r
+ case 0:\r
+ // If critical_section_init_phase_ was 0 before the exchange, we\r
+ // are the first to test it and need to perform the initialization.\r
+ owner_thread_id_ = 0;\r
+ critical_section_ = new CRITICAL_SECTION;\r
+ ::InitializeCriticalSection(critical_section_);\r
+ // Updates the critical_section_init_phase_ to 2 to signal\r
+ // initialization complete.\r
+ GTEST_CHECK_(::InterlockedCompareExchange(\r
+ &critical_section_init_phase_, 2L, 1L) ==\r
+ 1L);\r
+ break;\r
+ case 1:\r
+ // Somebody else is already initializing the mutex; spin until they\r
+ // are done.\r
+ while (::InterlockedCompareExchange(&critical_section_init_phase_,\r
+ 2L,\r
+ 2L) != 2L) {\r
+ // Possibly yields the rest of the thread's time slice to other\r
+ // threads.\r
+ ::Sleep(0);\r
+ }\r
+ break;\r
+\r
+ case 2:\r
+ break; // The mutex is already initialized and ready for use.\r
+\r
+ default:\r
+ GTEST_CHECK_(false)\r
+ << "Unexpected value of critical_section_init_phase_ "\r
+ << "while initializing a static mutex.";\r
+ }\r
+ }\r
+}\r
+\r
+namespace {\r
+\r
+class ThreadWithParamSupport : public ThreadWithParamBase {\r
+ public:\r
+ static HANDLE CreateThread(Runnable* runnable,\r
+ Notification* thread_can_start) {\r
+ ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);\r
+ DWORD thread_id;\r
+ // TODO(yukawa): Consider to use _beginthreadex instead.\r
+ HANDLE thread_handle = ::CreateThread(\r
+ NULL, // Default security.\r
+ 0, // Default stack size.\r
+ &ThreadWithParamSupport::ThreadMain,\r
+ param, // Parameter to ThreadMainStatic\r
+ 0x0, // Default creation flags.\r
+ &thread_id); // Need a valid pointer for the call to work under Win98.\r
+ GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "\r
+ << ::GetLastError() << ".";\r
+ if (thread_handle == NULL) {\r
+ delete param;\r
+ }\r
+ return thread_handle;\r
+ }\r
+\r
+ private:\r
+ struct ThreadMainParam {\r
+ ThreadMainParam(Runnable* runnable, Notification* thread_can_start)\r
+ : runnable_(runnable),\r
+ thread_can_start_(thread_can_start) {\r
+ }\r
+ scoped_ptr<Runnable> runnable_;\r
+ // Does not own.\r
+ Notification* thread_can_start_;\r
+ };\r
+\r
+ static DWORD WINAPI ThreadMain(void* ptr) {\r
+ // Transfers ownership.\r
+ scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));\r
+ if (param->thread_can_start_ != NULL)\r
+ param->thread_can_start_->WaitForNotification();\r
+ param->runnable_->Run();\r
+ return 0;\r
+ }\r
+\r
+ // Prohibit instantiation.\r
+ ThreadWithParamSupport();\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);\r
+};\r
+\r
+} // namespace\r
+\r
+ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,\r
+ Notification* thread_can_start)\r
+ : thread_(ThreadWithParamSupport::CreateThread(runnable,\r
+ thread_can_start)) {\r
+}\r
+\r
+ThreadWithParamBase::~ThreadWithParamBase() {\r
+ Join();\r
+}\r
+\r
+void ThreadWithParamBase::Join() {\r
+ GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)\r
+ << "Failed to join the thread with error " << ::GetLastError() << ".";\r
+}\r
+\r
+// Maps a thread to a set of ThreadIdToThreadLocals that have values\r
+// instantiated on that thread and notifies them when the thread exits. A\r
+// ThreadLocal instance is expected to persist until all threads it has\r
+// values on have terminated.\r
+class ThreadLocalRegistryImpl {\r
+ public:\r
+ // Registers thread_local_instance as having value on the current thread.\r
+ // Returns a value that can be used to identify the thread from other threads.\r
+ static ThreadLocalValueHolderBase* GetValueOnCurrentThread(\r
+ const ThreadLocalBase* thread_local_instance) {\r
+ DWORD current_thread = ::GetCurrentThreadId();\r
+ MutexLock lock(&mutex_);\r
+ ThreadIdToThreadLocals* const thread_to_thread_locals =\r
+ GetThreadLocalsMapLocked();\r
+ ThreadIdToThreadLocals::iterator thread_local_pos =\r
+ thread_to_thread_locals->find(current_thread);\r
+ if (thread_local_pos == thread_to_thread_locals->end()) {\r
+ thread_local_pos = thread_to_thread_locals->insert(\r
+ std::make_pair(current_thread, ThreadLocalValues())).first;\r
+ StartWatcherThreadFor(current_thread);\r
+ }\r
+ ThreadLocalValues& thread_local_values = thread_local_pos->second;\r
+ ThreadLocalValues::iterator value_pos =\r
+ thread_local_values.find(thread_local_instance);\r
+ if (value_pos == thread_local_values.end()) {\r
+ value_pos =\r
+ thread_local_values\r
+ .insert(std::make_pair(\r
+ thread_local_instance,\r
+ linked_ptr<ThreadLocalValueHolderBase>(\r
+ thread_local_instance->NewValueForCurrentThread())))\r
+ .first;\r
+ }\r
+ return value_pos->second.get();\r
+ }\r
+\r
+ static void OnThreadLocalDestroyed(\r
+ const ThreadLocalBase* thread_local_instance) {\r
+ std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;\r
+ // Clean up the ThreadLocalValues data structure while holding the lock, but\r
+ // defer the destruction of the ThreadLocalValueHolderBases.\r
+ {\r
+ MutexLock lock(&mutex_);\r
+ ThreadIdToThreadLocals* const thread_to_thread_locals =\r
+ GetThreadLocalsMapLocked();\r
+ for (ThreadIdToThreadLocals::iterator it =\r
+ thread_to_thread_locals->begin();\r
+ it != thread_to_thread_locals->end();\r
+ ++it) {\r
+ ThreadLocalValues& thread_local_values = it->second;\r
+ ThreadLocalValues::iterator value_pos =\r
+ thread_local_values.find(thread_local_instance);\r
+ if (value_pos != thread_local_values.end()) {\r
+ value_holders.push_back(value_pos->second);\r
+ thread_local_values.erase(value_pos);\r
+ // This 'if' can only be successful at most once, so theoretically we\r
+ // could break out of the loop here, but we don't bother doing so.\r
+ }\r
+ }\r
+ }\r
+ // Outside the lock, let the destructor for 'value_holders' deallocate the\r
+ // ThreadLocalValueHolderBases.\r
+ }\r
+\r
+ static void OnThreadExit(DWORD thread_id) {\r
+ GTEST_CHECK_(thread_id != 0) << ::GetLastError();\r
+ std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;\r
+ // Clean up the ThreadIdToThreadLocals data structure while holding the\r
+ // lock, but defer the destruction of the ThreadLocalValueHolderBases.\r
+ {\r
+ MutexLock lock(&mutex_);\r
+ ThreadIdToThreadLocals* const thread_to_thread_locals =\r
+ GetThreadLocalsMapLocked();\r
+ ThreadIdToThreadLocals::iterator thread_local_pos =\r
+ thread_to_thread_locals->find(thread_id);\r
+ if (thread_local_pos != thread_to_thread_locals->end()) {\r
+ ThreadLocalValues& thread_local_values = thread_local_pos->second;\r
+ for (ThreadLocalValues::iterator value_pos =\r
+ thread_local_values.begin();\r
+ value_pos != thread_local_values.end();\r
+ ++value_pos) {\r
+ value_holders.push_back(value_pos->second);\r
+ }\r
+ thread_to_thread_locals->erase(thread_local_pos);\r
+ }\r
+ }\r
+ // Outside the lock, let the destructor for 'value_holders' deallocate the\r
+ // ThreadLocalValueHolderBases.\r
+ }\r
+\r
+ private:\r
+ // In a particular thread, maps a ThreadLocal object to its value.\r
+ typedef std::map<const ThreadLocalBase*,\r
+ linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;\r
+ // Stores all ThreadIdToThreadLocals having values in a thread, indexed by\r
+ // thread's ID.\r
+ typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;\r
+\r
+ // Holds the thread id and thread handle that we pass from\r
+ // StartWatcherThreadFor to WatcherThreadFunc.\r
+ typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;\r
+\r
+ static void StartWatcherThreadFor(DWORD thread_id) {\r
+ // The returned handle will be kept in thread_map and closed by\r
+ // watcher_thread in WatcherThreadFunc.\r
+ HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,\r
+ FALSE,\r
+ thread_id);\r
+ GTEST_CHECK_(thread != NULL);\r
+ // We need to to pass a valid thread ID pointer into CreateThread for it\r
+ // to work correctly under Win98.\r
+ DWORD watcher_thread_id;\r
+ HANDLE watcher_thread = ::CreateThread(\r
+ NULL, // Default security.\r
+ 0, // Default stack size\r
+ &ThreadLocalRegistryImpl::WatcherThreadFunc,\r
+ reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),\r
+ CREATE_SUSPENDED,\r
+ &watcher_thread_id);\r
+ GTEST_CHECK_(watcher_thread != NULL);\r
+ // Give the watcher thread the same priority as ours to avoid being\r
+ // blocked by it.\r
+ ::SetThreadPriority(watcher_thread,\r
+ ::GetThreadPriority(::GetCurrentThread()));\r
+ ::ResumeThread(watcher_thread);\r
+ ::CloseHandle(watcher_thread);\r
+ }\r
+\r
+ // Monitors exit from a given thread and notifies those\r
+ // ThreadIdToThreadLocals about thread termination.\r
+ static DWORD WINAPI WatcherThreadFunc(LPVOID param) {\r
+ const ThreadIdAndHandle* tah =\r
+ reinterpret_cast<const ThreadIdAndHandle*>(param);\r
+ GTEST_CHECK_(\r
+ ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);\r
+ OnThreadExit(tah->first);\r
+ ::CloseHandle(tah->second);\r
+ delete tah;\r
+ return 0;\r
+ }\r
+\r
+ // Returns map of thread local instances.\r
+ static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {\r
+ mutex_.AssertHeld();\r
+ static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals;\r
+ return map;\r
+ }\r
+\r
+ // Protects access to GetThreadLocalsMapLocked() and its return value.\r
+ static Mutex mutex_;\r
+ // Protects access to GetThreadMapLocked() and its return value.\r
+ static Mutex thread_map_mutex_;\r
+};\r
+\r
+Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);\r
+Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);\r
+\r
+ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(\r
+ const ThreadLocalBase* thread_local_instance) {\r
+ return ThreadLocalRegistryImpl::GetValueOnCurrentThread(\r
+ thread_local_instance);\r
+}\r
+\r
+void ThreadLocalRegistry::OnThreadLocalDestroyed(\r
+ const ThreadLocalBase* thread_local_instance) {\r
+ ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);\r
+}\r
+\r
+#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS\r
+\r
+#if GTEST_USES_POSIX_RE\r
+\r
+// Implements RE. Currently only needed for death tests.\r
+\r
+RE::~RE() {\r
+ if (is_valid_) {\r
+ // regfree'ing an invalid regex might crash because the content\r
+ // of the regex is undefined. Since the regex's are essentially\r
+ // the same, one cannot be valid (or invalid) without the other\r
+ // being so too.\r
+ regfree(&partial_regex_);\r
+ regfree(&full_regex_);\r
+ }\r
+ free(const_cast<char*>(pattern_));\r
+}\r
+\r
+// Returns true iff regular expression re matches the entire str.\r
+bool RE::FullMatch(const char* str, const RE& re) {\r
+ if (!re.is_valid_) return false;\r
+\r
+ regmatch_t match;\r
+ return regexec(&re.full_regex_, str, 1, &match, 0) == 0;\r
+}\r
+\r
+// Returns true iff regular expression re matches a substring of str\r
+// (including str itself).\r
+bool RE::PartialMatch(const char* str, const RE& re) {\r
+ if (!re.is_valid_) return false;\r
+\r
+ regmatch_t match;\r
+ return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;\r
+}\r
+\r
+// Initializes an RE from its string representation.\r
+void RE::Init(const char* regex) {\r
+ pattern_ = posix::StrDup(regex);\r
+\r
+ // Reserves enough bytes to hold the regular expression used for a\r
+ // full match.\r
+ const size_t full_regex_len = strlen(regex) + 10;\r
+ char* const full_pattern = new char[full_regex_len];\r
+\r
+ snprintf(full_pattern, full_regex_len, "^(%s)$", regex);\r
+ is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;\r
+ // We want to call regcomp(&partial_regex_, ...) even if the\r
+ // previous expression returns false. Otherwise partial_regex_ may\r
+ // not be properly initialized can may cause trouble when it's\r
+ // freed.\r
+ //\r
+ // Some implementation of POSIX regex (e.g. on at least some\r
+ // versions of Cygwin) doesn't accept the empty string as a valid\r
+ // regex. We change it to an equivalent form "()" to be safe.\r
+ if (is_valid_) {\r
+ const char* const partial_regex = (*regex == '\0') ? "()" : regex;\r
+ is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;\r
+ }\r
+ EXPECT_TRUE(is_valid_)\r
+ << "Regular expression \"" << regex\r
+ << "\" is not a valid POSIX Extended regular expression.";\r
+\r
+ delete[] full_pattern;\r
+}\r
+\r
+#elif GTEST_USES_SIMPLE_RE\r
+\r
+// Returns true iff ch appears anywhere in str (excluding the\r
+// terminating '\0' character).\r
+bool IsInSet(char ch, const char* str) {\r
+ return ch != '\0' && strchr(str, ch) != NULL;\r
+}\r
+\r
+// Returns true iff ch belongs to the given classification. Unlike\r
+// similar functions in <ctype.h>, these aren't affected by the\r
+// current locale.\r
+bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }\r
+bool IsAsciiPunct(char ch) {\r
+ return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");\r
+}\r
+bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }\r
+bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }\r
+bool IsAsciiWordChar(char ch) {\r
+ return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||\r
+ ('0' <= ch && ch <= '9') || ch == '_';\r
+}\r
+\r
+// Returns true iff "\\c" is a supported escape sequence.\r
+bool IsValidEscape(char c) {\r
+ return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));\r
+}\r
+\r
+// Returns true iff the given atom (specified by escaped and pattern)\r
+// matches ch. The result is undefined if the atom is invalid.\r
+bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {\r
+ if (escaped) { // "\\p" where p is pattern_char.\r
+ switch (pattern_char) {\r
+ case 'd': return IsAsciiDigit(ch);\r
+ case 'D': return !IsAsciiDigit(ch);\r
+ case 'f': return ch == '\f';\r
+ case 'n': return ch == '\n';\r
+ case 'r': return ch == '\r';\r
+ case 's': return IsAsciiWhiteSpace(ch);\r
+ case 'S': return !IsAsciiWhiteSpace(ch);\r
+ case 't': return ch == '\t';\r
+ case 'v': return ch == '\v';\r
+ case 'w': return IsAsciiWordChar(ch);\r
+ case 'W': return !IsAsciiWordChar(ch);\r
+ }\r
+ return IsAsciiPunct(pattern_char) && pattern_char == ch;\r
+ }\r
+\r
+ return (pattern_char == '.' && ch != '\n') || pattern_char == ch;\r
+}\r
+\r
+// Helper function used by ValidateRegex() to format error messages.\r
+std::string FormatRegexSyntaxError(const char* regex, int index) {\r
+ return (Message() << "Syntax error at index " << index\r
+ << " in simple regular expression \"" << regex << "\": ").GetString();\r
+}\r
+\r
+// Generates non-fatal failures and returns false if regex is invalid;\r
+// otherwise returns true.\r
+bool ValidateRegex(const char* regex) {\r
+ if (regex == NULL) {\r
+ // TODO(wan@google.com): fix the source file location in the\r
+ // assertion failures to match where the regex is used in user\r
+ // code.\r
+ ADD_FAILURE() << "NULL is not a valid simple regular expression.";\r
+ return false;\r
+ }\r
+\r
+ bool is_valid = true;\r
+\r
+ // True iff ?, *, or + can follow the previous atom.\r
+ bool prev_repeatable = false;\r
+ for (int i = 0; regex[i]; i++) {\r
+ if (regex[i] == '\\') { // An escape sequence\r
+ i++;\r
+ if (regex[i] == '\0') {\r
+ ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)\r
+ << "'\\' cannot appear at the end.";\r
+ return false;\r
+ }\r
+\r
+ if (!IsValidEscape(regex[i])) {\r
+ ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)\r
+ << "invalid escape sequence \"\\" << regex[i] << "\".";\r
+ is_valid = false;\r
+ }\r
+ prev_repeatable = true;\r
+ } else { // Not an escape sequence.\r
+ const char ch = regex[i];\r
+\r
+ if (ch == '^' && i > 0) {\r
+ ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\r
+ << "'^' can only appear at the beginning.";\r
+ is_valid = false;\r
+ } else if (ch == '$' && regex[i + 1] != '\0') {\r
+ ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\r
+ << "'$' can only appear at the end.";\r
+ is_valid = false;\r
+ } else if (IsInSet(ch, "()[]{}|")) {\r
+ ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\r
+ << "'" << ch << "' is unsupported.";\r
+ is_valid = false;\r
+ } else if (IsRepeat(ch) && !prev_repeatable) {\r
+ ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\r
+ << "'" << ch << "' can only follow a repeatable token.";\r
+ is_valid = false;\r
+ }\r
+\r
+ prev_repeatable = !IsInSet(ch, "^$?*+");\r
+ }\r
+ }\r
+\r
+ return is_valid;\r
+}\r
+\r
+// Matches a repeated regex atom followed by a valid simple regular\r
+// expression. The regex atom is defined as c if escaped is false,\r
+// or \c otherwise. repeat is the repetition meta character (?, *,\r
+// or +). The behavior is undefined if str contains too many\r
+// characters to be indexable by size_t, in which case the test will\r
+// probably time out anyway. We are fine with this limitation as\r
+// std::string has it too.\r
+bool MatchRepetitionAndRegexAtHead(\r
+ bool escaped, char c, char repeat, const char* regex,\r
+ const char* str) {\r
+ const size_t min_count = (repeat == '+') ? 1 : 0;\r
+ const size_t max_count = (repeat == '?') ? 1 :\r
+ static_cast<size_t>(-1) - 1;\r
+ // We cannot call numeric_limits::max() as it conflicts with the\r
+ // max() macro on Windows.\r
+\r
+ for (size_t i = 0; i <= max_count; ++i) {\r
+ // We know that the atom matches each of the first i characters in str.\r
+ if (i >= min_count && MatchRegexAtHead(regex, str + i)) {\r
+ // We have enough matches at the head, and the tail matches too.\r
+ // Since we only care about *whether* the pattern matches str\r
+ // (as opposed to *how* it matches), there is no need to find a\r
+ // greedy match.\r
+ return true;\r
+ }\r
+ if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))\r
+ return false;\r
+ }\r
+ return false;\r
+}\r
+\r
+// Returns true iff regex matches a prefix of str. regex must be a\r
+// valid simple regular expression and not start with "^", or the\r
+// result is undefined.\r
+bool MatchRegexAtHead(const char* regex, const char* str) {\r
+ if (*regex == '\0') // An empty regex matches a prefix of anything.\r
+ return true;\r
+\r
+ // "$" only matches the end of a string. Note that regex being\r
+ // valid guarantees that there's nothing after "$" in it.\r
+ if (*regex == '$')\r
+ return *str == '\0';\r
+\r
+ // Is the first thing in regex an escape sequence?\r
+ const bool escaped = *regex == '\\';\r
+ if (escaped)\r
+ ++regex;\r
+ if (IsRepeat(regex[1])) {\r
+ // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so\r
+ // here's an indirect recursion. It terminates as the regex gets\r
+ // shorter in each recursion.\r
+ return MatchRepetitionAndRegexAtHead(\r
+ escaped, regex[0], regex[1], regex + 2, str);\r
+ } else {\r
+ // regex isn't empty, isn't "$", and doesn't start with a\r
+ // repetition. We match the first atom of regex with the first\r
+ // character of str and recurse.\r
+ return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&\r
+ MatchRegexAtHead(regex + 1, str + 1);\r
+ }\r
+}\r
+\r
+// Returns true iff regex matches any substring of str. regex must be\r
+// a valid simple regular expression, or the result is undefined.\r
+//\r
+// The algorithm is recursive, but the recursion depth doesn't exceed\r
+// the regex length, so we won't need to worry about running out of\r
+// stack space normally. In rare cases the time complexity can be\r
+// exponential with respect to the regex length + the string length,\r
+// but usually it's must faster (often close to linear).\r
+bool MatchRegexAnywhere(const char* regex, const char* str) {\r
+ if (regex == NULL || str == NULL)\r
+ return false;\r
+\r
+ if (*regex == '^')\r
+ return MatchRegexAtHead(regex + 1, str);\r
+\r
+ // A successful match can be anywhere in str.\r
+ do {\r
+ if (MatchRegexAtHead(regex, str))\r
+ return true;\r
+ } while (*str++ != '\0');\r
+ return false;\r
+}\r
+\r
+// Implements the RE class.\r
+\r
+RE::~RE() {\r
+ free(const_cast<char*>(pattern_));\r
+ free(const_cast<char*>(full_pattern_));\r
+}\r
+\r
+// Returns true iff regular expression re matches the entire str.\r
+bool RE::FullMatch(const char* str, const RE& re) {\r
+ return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);\r
+}\r
+\r
+// Returns true iff regular expression re matches a substring of str\r
+// (including str itself).\r
+bool RE::PartialMatch(const char* str, const RE& re) {\r
+ return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);\r
+}\r
+\r
+// Initializes an RE from its string representation.\r
+void RE::Init(const char* regex) {\r
+ pattern_ = full_pattern_ = NULL;\r
+ if (regex != NULL) {\r
+ pattern_ = posix::StrDup(regex);\r
+ }\r
+\r
+ is_valid_ = ValidateRegex(regex);\r
+ if (!is_valid_) {\r
+ // No need to calculate the full pattern when the regex is invalid.\r
+ return;\r
+ }\r
+\r
+ const size_t len = strlen(regex);\r
+ // Reserves enough bytes to hold the regular expression used for a\r
+ // full match: we need space to prepend a '^', append a '$', and\r
+ // terminate the string with '\0'.\r
+ char* buffer = static_cast<char*>(malloc(len + 3));\r
+ full_pattern_ = buffer;\r
+\r
+ if (*regex != '^')\r
+ *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.\r
+\r
+ // We don't use snprintf or strncpy, as they trigger a warning when\r
+ // compiled with VC++ 8.0.\r
+ memcpy(buffer, regex, len);\r
+ buffer += len;\r
+\r
+ if (len == 0 || regex[len - 1] != '$')\r
+ *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.\r
+\r
+ *buffer = '\0';\r
+}\r
+\r
+#endif // GTEST_USES_POSIX_RE\r
+\r
+const char kUnknownFile[] = "unknown file";\r
+\r
+// Formats a source file path and a line number as they would appear\r
+// in an error message from the compiler used to compile this code.\r
+GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {\r
+ const std::string file_name(file == NULL ? kUnknownFile : file);\r
+\r
+ if (line < 0) {\r
+ return file_name + ":";\r
+ }\r
+#ifdef _MSC_VER\r
+ return file_name + "(" + StreamableToString(line) + "):";\r
+#else\r
+ return file_name + ":" + StreamableToString(line) + ":";\r
+#endif // _MSC_VER\r
+}\r
+\r
+// Formats a file location for compiler-independent XML output.\r
+// Although this function is not platform dependent, we put it next to\r
+// FormatFileLocation in order to contrast the two functions.\r
+// Note that FormatCompilerIndependentFileLocation() does NOT append colon\r
+// to the file location it produces, unlike FormatFileLocation().\r
+GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(\r
+ const char* file, int line) {\r
+ const std::string file_name(file == NULL ? kUnknownFile : file);\r
+\r
+ if (line < 0)\r
+ return file_name;\r
+ else\r
+ return file_name + ":" + StreamableToString(line);\r
+}\r
+\r
+GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)\r
+ : severity_(severity) {\r
+ const char* const marker =\r
+ severity == GTEST_INFO ? "[ INFO ]" :\r
+ severity == GTEST_WARNING ? "[WARNING]" :\r
+ severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";\r
+ GetStream() << ::std::endl << marker << " "\r
+ << FormatFileLocation(file, line).c_str() << ": ";\r
+}\r
+\r
+// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.\r
+GTestLog::~GTestLog() {\r
+ GetStream() << ::std::endl;\r
+ if (severity_ == GTEST_FATAL) {\r
+ fflush(stderr);\r
+ posix::Abort();\r
+ }\r
+}\r
+// Disable Microsoft deprecation warnings for POSIX functions called from\r
+// this class (creat, dup, dup2, and close)\r
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)\r
+\r
+#if GTEST_HAS_STREAM_REDIRECTION\r
+\r
+// Object that captures an output stream (stdout/stderr).\r
+class CapturedStream {\r
+ public:\r
+ // The ctor redirects the stream to a temporary file.\r
+ explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {\r
+# if GTEST_OS_WINDOWS\r
+ char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT\r
+ char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT\r
+\r
+ ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);\r
+ const UINT success = ::GetTempFileNameA(temp_dir_path,\r
+ "gtest_redir",\r
+ 0, // Generate unique file name.\r
+ temp_file_path);\r
+ GTEST_CHECK_(success != 0)\r
+ << "Unable to create a temporary file in " << temp_dir_path;\r
+ const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);\r
+ GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "\r
+ << temp_file_path;\r
+ filename_ = temp_file_path;\r
+# else\r
+ // There's no guarantee that a test has write access to the current\r
+ // directory, so we create the temporary file in the /tmp directory\r
+ // instead. We use /tmp on most systems, and /sdcard on Android.\r
+ // That's because Android doesn't have /tmp.\r
+# if GTEST_OS_LINUX_ANDROID\r
+ // Note: Android applications are expected to call the framework's\r
+ // Context.getExternalStorageDirectory() method through JNI to get\r
+ // the location of the world-writable SD Card directory. However,\r
+ // this requires a Context handle, which cannot be retrieved\r
+ // globally from native code. Doing so also precludes running the\r
+ // code as part of a regular standalone executable, which doesn't\r
+ // run in a Dalvik process (e.g. when running it through 'adb shell').\r
+ //\r
+ // The location /sdcard is directly accessible from native code\r
+ // and is the only location (unofficially) supported by the Android\r
+ // team. It's generally a symlink to the real SD Card mount point\r
+ // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or\r
+ // other OEM-customized locations. Never rely on these, and always\r
+ // use /sdcard.\r
+ char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";\r
+# else\r
+ char name_template[] = "/tmp/captured_stream.XXXXXX";\r
+# endif // GTEST_OS_LINUX_ANDROID\r
+ const int captured_fd = mkstemp(name_template);\r
+ filename_ = name_template;\r
+# endif // GTEST_OS_WINDOWS\r
+ fflush(NULL);\r
+ dup2(captured_fd, fd_);\r
+ close(captured_fd);\r
+ }\r
+\r
+ ~CapturedStream() {\r
+ remove(filename_.c_str());\r
+ }\r
+\r
+ std::string GetCapturedString() {\r
+ if (uncaptured_fd_ != -1) {\r
+ // Restores the original stream.\r
+ fflush(NULL);\r
+ dup2(uncaptured_fd_, fd_);\r
+ close(uncaptured_fd_);\r
+ uncaptured_fd_ = -1;\r
+ }\r
+\r
+ FILE* const file = posix::FOpen(filename_.c_str(), "r");\r
+ const std::string content = ReadEntireFile(file);\r
+ posix::FClose(file);\r
+ return content;\r
+ }\r
+\r
+ private:\r
+ const int fd_; // A stream to capture.\r
+ int uncaptured_fd_;\r
+ // Name of the temporary file holding the stderr output.\r
+ ::std::string filename_;\r
+\r
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);\r
+};\r
+\r
+GTEST_DISABLE_MSC_WARNINGS_POP_()\r
+\r
+static CapturedStream* g_captured_stderr = NULL;\r
+static CapturedStream* g_captured_stdout = NULL;\r
+\r
+// Starts capturing an output stream (stdout/stderr).\r
+void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {\r
+ if (*stream != NULL) {\r
+ GTEST_LOG_(FATAL) << "Only one " << stream_name\r
+ << " capturer can exist at a time.";\r
+ }\r
+ *stream = new CapturedStream(fd);\r
+}\r
+\r
+// Stops capturing the output stream and returns the captured string.\r
+std::string GetCapturedStream(CapturedStream** captured_stream) {\r
+ const std::string content = (*captured_stream)->GetCapturedString();\r
+\r
+ delete *captured_stream;\r
+ *captured_stream = NULL;\r
+\r
+ return content;\r
+}\r
+\r
+// Starts capturing stdout.\r
+void CaptureStdout() {\r
+ CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);\r
+}\r
+\r
+// Starts capturing stderr.\r
+void CaptureStderr() {\r
+ CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);\r
+}\r
+\r
+// Stops capturing stdout and returns the captured string.\r
+std::string GetCapturedStdout() {\r
+ return GetCapturedStream(&g_captured_stdout);\r
+}\r
+\r
+// Stops capturing stderr and returns the captured string.\r
+std::string GetCapturedStderr() {\r
+ return GetCapturedStream(&g_captured_stderr);\r
+}\r
+\r
+#endif // GTEST_HAS_STREAM_REDIRECTION\r
+\r
+std::string TempDir() {\r
+#if GTEST_OS_WINDOWS_MOBILE\r
+ return "\\temp\\";\r
+#elif GTEST_OS_WINDOWS\r
+ const char* temp_dir = posix::GetEnv("TEMP");\r
+ if (temp_dir == NULL || temp_dir[0] == '\0')\r
+ return "\\temp\\";\r
+ else if (temp_dir[strlen(temp_dir) - 1] == '\\')\r
+ return temp_dir;\r
+ else\r
+ return std::string(temp_dir) + "\\";\r
+#elif GTEST_OS_LINUX_ANDROID\r
+ return "/sdcard/";\r
+#else\r
+ return "/tmp/";\r
+#endif // GTEST_OS_WINDOWS_MOBILE\r
+}\r
+\r
+size_t GetFileSize(FILE* file) {\r
+ fseek(file, 0, SEEK_END);\r
+ return static_cast<size_t>(ftell(file));\r
+}\r
+\r
+std::string ReadEntireFile(FILE* file) {\r
+ const size_t file_size = GetFileSize(file);\r
+ char* const buffer = new char[file_size];\r
+\r
+ size_t bytes_last_read = 0; // # of bytes read in the last fread()\r
+ size_t bytes_read = 0; // # of bytes read so far\r
+\r
+ fseek(file, 0, SEEK_SET);\r
+\r
+ // Keeps reading the file until we cannot read further or the\r
+ // pre-determined file size is reached.\r
+ do {\r
+ bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);\r
+ bytes_read += bytes_last_read;\r
+ } while (bytes_last_read > 0 && bytes_read < file_size);\r
+\r
+ const std::string content(buffer, bytes_read);\r
+ delete[] buffer;\r
+\r
+ return content;\r
+}\r
+\r
+#if GTEST_HAS_DEATH_TEST\r
+\r
+static const ::std::vector<testing::internal::string>* g_injected_test_argvs =\r
+ NULL; // Owned.\r
+\r
+void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {\r
+ if (g_injected_test_argvs != argvs)\r
+ delete g_injected_test_argvs;\r
+ g_injected_test_argvs = argvs;\r
+}\r
+\r
+const ::std::vector<testing::internal::string>& GetInjectableArgvs() {\r
+ if (g_injected_test_argvs != NULL) {\r
+ return *g_injected_test_argvs;\r
+ }\r
+ return GetArgvs();\r
+}\r
+#endif // GTEST_HAS_DEATH_TEST\r
+\r
+#if GTEST_OS_WINDOWS_MOBILE\r
+namespace posix {\r
+void Abort() {\r
+ DebugBreak();\r
+ TerminateProcess(GetCurrentProcess(), 1);\r
+}\r
+} // namespace posix\r
+#endif // GTEST_OS_WINDOWS_MOBILE\r
+\r
+// Returns the name of the environment variable corresponding to the\r
+// given flag. For example, FlagToEnvVar("foo") will return\r
+// "GTEST_FOO" in the open-source version.\r
+static std::string FlagToEnvVar(const char* flag) {\r
+ const std::string full_flag =\r
+ (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();\r
+\r
+ Message env_var;\r
+ for (size_t i = 0; i != full_flag.length(); i++) {\r
+ env_var << ToUpper(full_flag.c_str()[i]);\r
+ }\r
+\r
+ return env_var.GetString();\r
+}\r
+\r
+// Parses 'str' for a 32-bit signed integer. If successful, writes\r
+// the result to *value and returns true; otherwise leaves *value\r
+// unchanged and returns false.\r
+bool ParseInt32(const Message& src_text, const char* str, Int32* value) {\r
+ // Parses the environment variable as a decimal integer.\r
+ char* end = NULL;\r
+ const long long_value = strtol(str, &end, 10); // NOLINT\r
+\r
+ // Has strtol() consumed all characters in the string?\r
+ if (*end != '\0') {\r
+ // No - an invalid character was encountered.\r
+ Message msg;\r
+ msg << "WARNING: " << src_text\r
+ << " is expected to be a 32-bit integer, but actually"\r
+ << " has value \"" << str << "\".\n";\r
+ printf("%s", msg.GetString().c_str());\r
+ fflush(stdout);\r
+ return false;\r
+ }\r
+\r
+ // Is the parsed value in the range of an Int32?\r
+ const Int32 result = static_cast<Int32>(long_value);\r
+ if (long_value == LONG_MAX || long_value == LONG_MIN ||\r
+ // The parsed value overflows as a long. (strtol() returns\r
+ // LONG_MAX or LONG_MIN when the input overflows.)\r
+ result != long_value\r
+ // The parsed value overflows as an Int32.\r
+ ) {\r
+ Message msg;\r
+ msg << "WARNING: " << src_text\r
+ << " is expected to be a 32-bit integer, but actually"\r
+ << " has value " << str << ", which overflows.\n";\r
+ printf("%s", msg.GetString().c_str());\r
+ fflush(stdout);\r
+ return false;\r
+ }\r
+\r
+ *value = result;\r
+ return true;\r
+}\r
+\r
+// Reads and returns the Boolean environment variable corresponding to\r
+// the given flag; if it's not set, returns default_value.\r
+//\r
+// The value is considered true iff it's not "0".\r
+bool BoolFromGTestEnv(const char* flag, bool default_value) {\r
+#if defined(GTEST_GET_BOOL_FROM_ENV_)\r
+ return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);\r
+#endif // defined(GTEST_GET_BOOL_FROM_ENV_)\r
+ const std::string env_var = FlagToEnvVar(flag);\r
+ const char* const string_value = posix::GetEnv(env_var.c_str());\r
+ return string_value == NULL ?\r
+ default_value : strcmp(string_value, "0") != 0;\r
+}\r
+\r
+// Reads and returns a 32-bit integer stored in the environment\r
+// variable corresponding to the given flag; if it isn't set or\r
+// doesn't represent a valid 32-bit integer, returns default_value.\r
+Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {\r
+#if defined(GTEST_GET_INT32_FROM_ENV_)\r
+ return GTEST_GET_INT32_FROM_ENV_(flag, default_value);\r
+#endif // defined(GTEST_GET_INT32_FROM_ENV_)\r
+ const std::string env_var = FlagToEnvVar(flag);\r
+ const char* const string_value = posix::GetEnv(env_var.c_str());\r
+ if (string_value == NULL) {\r
+ // The environment variable is not set.\r
+ return default_value;\r
+ }\r
+\r
+ Int32 result = default_value;\r
+ if (!ParseInt32(Message() << "Environment variable " << env_var,\r
+ string_value, &result)) {\r
+ printf("The default value %s is used.\n",\r
+ (Message() << default_value).GetString().c_str());\r
+ fflush(stdout);\r
+ return default_value;\r
+ }\r
+\r
+ return result;\r
+}\r
+\r
+// Reads and returns the string environment variable corresponding to\r
+// the given flag; if it's not set, returns default_value.\r
+const char* StringFromGTestEnv(const char* flag, const char* default_value) {\r
+#if defined(GTEST_GET_STRING_FROM_ENV_)\r
+ return GTEST_GET_STRING_FROM_ENV_(flag, default_value);\r
+#endif // defined(GTEST_GET_STRING_FROM_ENV_)\r
+ const std::string env_var = FlagToEnvVar(flag);\r
+ const char* const value = posix::GetEnv(env_var.c_str());\r
+ return value == NULL ? default_value : value;\r
+}\r
+\r
+} // namespace internal\r
+} // namespace testing\r
+// Copyright 2007, Google Inc.\r
+// All rights reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+//\r
+// Author: wan@google.com (Zhanyong Wan)\r
+\r
+// Google Test - The Google C++ Testing Framework\r
+//\r
+// This file implements a universal value printer that can print a\r
+// value of any type T:\r
+//\r
+// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);\r
+//\r
+// It uses the << operator when possible, and prints the bytes in the\r
+// object otherwise. A user can override its behavior for a class\r
+// type Foo by defining either operator<<(::std::ostream&, const Foo&)\r
+// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that\r
+// defines Foo.\r
+\r
+#include <ctype.h>\r
+#include <stdio.h>\r
+#include <cwchar>\r
+#include <ostream> // NOLINT\r
+#include <string>\r
+\r
+namespace testing {\r
+\r
+namespace {\r
+\r
+using ::std::ostream;\r
+\r
+// Prints a segment of bytes in the given object.\r
+GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\r
+GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\r
+GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\r
+void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,\r
+ size_t count, ostream* os) {\r
+ char text[5] = "";\r
+ for (size_t i = 0; i != count; i++) {\r
+ const size_t j = start + i;\r
+ if (i != 0) {\r
+ // Organizes the bytes into groups of 2 for easy parsing by\r
+ // human.\r
+ if ((j % 2) == 0)\r
+ *os << ' ';\r
+ else\r
+ *os << '-';\r
+ }\r
+ GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);\r
+ *os << text;\r
+ }\r
+}\r
+\r
+// Prints the bytes in the given value to the given ostream.\r
+void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,\r
+ ostream* os) {\r
+ // Tells the user how big the object is.\r
+ *os << count << "-byte object <";\r
+\r
+ const size_t kThreshold = 132;\r
+ const size_t kChunkSize = 64;\r
+ // If the object size is bigger than kThreshold, we'll have to omit\r
+ // some details by printing only the first and the last kChunkSize\r
+ // bytes.\r
+ // TODO(wan): let the user control the threshold using a flag.\r
+ if (count < kThreshold) {\r
+ PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);\r
+ } else {\r
+ PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);\r
+ *os << " ... ";\r
+ // Rounds up to 2-byte boundary.\r
+ const size_t resume_pos = (count - kChunkSize + 1)/2*2;\r
+ PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);\r
+ }\r
+ *os << ">";\r
+}\r
+\r
+} // namespace\r
+\r
+namespace internal2 {\r
+\r
+// Delegates to PrintBytesInObjectToImpl() to print the bytes in the\r
+// given object. The delegation simplifies the implementation, which\r
+// uses the << operator and thus is easier done outside of the\r
+// ::testing::internal namespace, which contains a << operator that\r
+// sometimes conflicts with the one in STL.\r
+void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,\r
+ ostream* os) {\r
+ PrintBytesInObjectToImpl(obj_bytes, count, os);\r
+}\r
+\r
+} // namespace internal2\r
+\r
+namespace internal {\r
+\r
+// Depending on the value of a char (or wchar_t), we print it in one\r
+// of three formats:\r
+// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),\r
+// - as a hexidecimal escape sequence (e.g. '\x7F'), or\r
+// - as a special escape sequence (e.g. '\r', '\n').\r
+enum CharFormat {\r
+ kAsIs,\r
+ kHexEscape,\r
+ kSpecialEscape\r
+};\r
+\r
+// Returns true if c is a printable ASCII character. We test the\r
+// value of c directly instead of calling isprint(), which is buggy on\r
+// Windows Mobile.\r
+inline bool IsPrintableAscii(wchar_t c) {\r
+ return 0x20 <= c && c <= 0x7E;\r
+}\r
+\r
+// Prints a wide or narrow char c as a character literal without the\r
+// quotes, escaping it when necessary; returns how c was formatted.\r
+// The template argument UnsignedChar is the unsigned version of Char,\r
+// which is the type of c.\r
+template <typename UnsignedChar, typename Char>\r
+static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {\r
+ switch (static_cast<wchar_t>(c)) {\r
+ case L'\0':\r
+ *os << "\\0";\r
+ break;\r
+ case L'\'':\r
+ *os << "\\'";\r
+ break;\r
+ case L'\\':\r
+ *os << "\\\\";\r
+ break;\r
+ case L'\a':\r
+ *os << "\\a";\r
+ break;\r
+ case L'\b':\r
+ *os << "\\b";\r
+ break;\r
+ case L'\f':\r
+ *os << "\\f";\r
+ break;\r
+ case L'\n':\r
+ *os << "\\n";\r
+ break;\r
+ case L'\r':\r
+ *os << "\\r";\r
+ break;\r
+ case L'\t':\r
+ *os << "\\t";\r
+ break;\r
+ case L'\v':\r
+ *os << "\\v";\r
+ break;\r
+ default:\r
+ if (IsPrintableAscii(c)) {\r
+ *os << static_cast<char>(c);\r
+ return kAsIs;\r
+ } else {\r
+ *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));\r
+ return kHexEscape;\r
+ }\r
+ }\r
+ return kSpecialEscape;\r
+}\r
+\r
+// Prints a wchar_t c as if it's part of a string literal, escaping it when\r
+// necessary; returns how c was formatted.\r
+static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {\r
+ switch (c) {\r
+ case L'\'':\r
+ *os << "'";\r
+ return kAsIs;\r
+ case L'"':\r
+ *os << "\\\"";\r
+ return kSpecialEscape;\r
+ default:\r
+ return PrintAsCharLiteralTo<wchar_t>(c, os);\r
+ }\r
+}\r
+\r
+// Prints a char c as if it's part of a string literal, escaping it when\r
+// necessary; returns how c was formatted.\r
+static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {\r
+ return PrintAsStringLiteralTo(\r
+ static_cast<wchar_t>(static_cast<unsigned char>(c)), os);\r
+}\r
+\r
+// Prints a wide or narrow character c and its code. '\0' is printed\r
+// as "'\\0'", other unprintable characters are also properly escaped\r
+// using the standard C++ escape sequence. The template argument\r
+// UnsignedChar is the unsigned version of Char, which is the type of c.\r
+template <typename UnsignedChar, typename Char>\r
+void PrintCharAndCodeTo(Char c, ostream* os) {\r
+ // First, print c as a literal in the most readable form we can find.\r
+ *os << ((sizeof(c) > 1) ? "L'" : "'");\r
+ const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);\r
+ *os << "'";\r
+\r
+ // To aid user debugging, we also print c's code in decimal, unless\r
+ // it's 0 (in which case c was printed as '\\0', making the code\r
+ // obvious).\r
+ if (c == 0)\r
+ return;\r
+ *os << " (" << static_cast<int>(c);\r
+\r
+ // For more convenience, we print c's code again in hexidecimal,\r
+ // unless c was already printed in the form '\x##' or the code is in\r
+ // [1, 9].\r
+ if (format == kHexEscape || (1 <= c && c <= 9)) {\r
+ // Do nothing.\r
+ } else {\r
+ *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));\r
+ }\r
+ *os << ")";\r
+}\r
+\r
+void PrintTo(unsigned char c, ::std::ostream* os) {\r
+ PrintCharAndCodeTo<unsigned char>(c, os);\r
+}\r
+void PrintTo(signed char c, ::std::ostream* os) {\r
+ PrintCharAndCodeTo<unsigned char>(c, os);\r
+}\r
+\r
+// Prints a wchar_t as a symbol if it is printable or as its internal\r
+// code otherwise and also as its code. L'\0' is printed as "L'\\0'".\r
+void PrintTo(wchar_t wc, ostream* os) {\r
+ PrintCharAndCodeTo<wchar_t>(wc, os);\r
+}\r
+\r
+// Prints the given array of characters to the ostream. CharType must be either\r
+// char or wchar_t.\r
+// The array starts at begin, the length is len, it may include '\0' characters\r
+// and may not be NUL-terminated.\r
+template <typename CharType>\r
+GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\r
+GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\r
+GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\r
+static void PrintCharsAsStringTo(\r
+ const CharType* begin, size_t len, ostream* os) {\r
+ const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";\r
+ *os << kQuoteBegin;\r
+ bool is_previous_hex = false;\r
+ for (size_t index = 0; index < len; ++index) {\r
+ const CharType cur = begin[index];\r
+ if (is_previous_hex && IsXDigit(cur)) {\r
+ // Previous character is of '\x..' form and this character can be\r
+ // interpreted as another hexadecimal digit in its number. Break string to\r
+ // disambiguate.\r
+ *os << "\" " << kQuoteBegin;\r
+ }\r
+ is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;\r
+ }\r
+ *os << "\"";\r
+}\r
+\r
+// Prints a (const) char/wchar_t array of 'len' elements, starting at address\r
+// 'begin'. CharType must be either char or wchar_t.\r
+template <typename CharType>\r
+GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\r
+GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\r
+GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\r
+static void UniversalPrintCharArray(\r
+ const CharType* begin, size_t len, ostream* os) {\r
+ // The code\r
+ // const char kFoo[] = "foo";\r
+ // generates an array of 4, not 3, elements, with the last one being '\0'.\r
+ //\r
+ // Therefore when printing a char array, we don't print the last element if\r
+ // it's '\0', such that the output matches the string literal as it's\r
+ // written in the source code.\r
+ if (len > 0 && begin[len - 1] == '\0') {\r
+ PrintCharsAsStringTo(begin, len - 1, os);\r
+ return;\r
+ }\r
+\r
+ // If, however, the last element in the array is not '\0', e.g.\r
+ // const char kFoo[] = { 'f', 'o', 'o' };\r
+ // we must print the entire array. We also print a message to indicate\r
+ // that the array is not NUL-terminated.\r
+ PrintCharsAsStringTo(begin, len, os);\r
+ *os << " (no terminating NUL)";\r
+}\r
+\r
+// Prints a (const) char array of 'len' elements, starting at address 'begin'.\r
+void UniversalPrintArray(const char* begin, size_t len, ostream* os) {\r
+ UniversalPrintCharArray(begin, len, os);\r
+}\r
+\r
+// Prints a (const) wchar_t array of 'len' elements, starting at address\r
+// 'begin'.\r
+void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {\r
+ UniversalPrintCharArray(begin, len, os);\r
+}\r
+\r
+// Prints the given C string to the ostream.\r
+void PrintTo(const char* s, ostream* os) {\r
+ if (s == NULL) {\r
+ *os << "NULL";\r
+ } else {\r
+ *os << ImplicitCast_<const void*>(s) << " pointing to ";\r
+ PrintCharsAsStringTo(s, strlen(s), os);\r
+ }\r
+}\r
+\r
+// MSVC compiler can be configured to define whar_t as a typedef\r
+// of unsigned short. Defining an overload for const wchar_t* in that case\r
+// would cause pointers to unsigned shorts be printed as wide strings,\r
+// possibly accessing more memory than intended and causing invalid\r
+// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when\r
+// wchar_t is implemented as a native type.\r
+#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)\r
+// Prints the given wide C string to the ostream.\r
+void PrintTo(const wchar_t* s, ostream* os) {\r
+ if (s == NULL) {\r
+ *os << "NULL";\r
+ } else {\r
+ *os << ImplicitCast_<const void*>(s) << " pointing to ";\r
+ PrintCharsAsStringTo(s, std::wcslen(s), os);\r
+ }\r
+}\r
+#endif // wchar_t is native\r
+\r
+// Prints a ::string object.\r
+#if GTEST_HAS_GLOBAL_STRING\r
+void PrintStringTo(const ::string& s, ostream* os) {\r
+ PrintCharsAsStringTo(s.data(), s.size(), os);\r
+}\r
+#endif // GTEST_HAS_GLOBAL_STRING\r
+\r
+void PrintStringTo(const ::std::string& s, ostream* os) {\r
+ PrintCharsAsStringTo(s.data(), s.size(), os);\r
+}\r
+\r
+// Prints a ::wstring object.\r
+#if GTEST_HAS_GLOBAL_WSTRING\r
+void PrintWideStringTo(const ::wstring& s, ostream* os) {\r
+ PrintCharsAsStringTo(s.data(), s.size(), os);\r
+}\r
+#endif // GTEST_HAS_GLOBAL_WSTRING\r
+\r
+#if GTEST_HAS_STD_WSTRING\r
+void PrintWideStringTo(const ::std::wstring& s, ostream* os) {\r
+ PrintCharsAsStringTo(s.data(), s.size(), os);\r
+}\r
+#endif // GTEST_HAS_STD_WSTRING\r
+\r
+} // namespace internal\r
+\r
+} // namespace testing\r
+// Copyright 2008, Google Inc.\r
+// All rights reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+//\r
+// Author: mheule@google.com (Markus Heule)\r
+//\r
+// The Google C++ Testing Framework (Google Test)\r
+\r
+\r
+// Indicates that this translation unit is part of Google Test's\r
+// implementation. It must come before gtest-internal-inl.h is\r
+// included, or there will be a compiler error. This trick exists to\r
+// prevent the accidental inclusion of gtest-internal-inl.h in the\r
+// user's code.\r
+#define GTEST_IMPLEMENTATION_ 1\r
+#undef GTEST_IMPLEMENTATION_\r
+\r
+namespace testing {\r
+\r
+using internal::GetUnitTestImpl;\r
+\r
+// Gets the summary of the failure message by omitting the stack trace\r
+// in it.\r
+std::string TestPartResult::ExtractSummary(const char* message) {\r
+ const char* const stack_trace = strstr(message, internal::kStackTraceMarker);\r
+ return stack_trace == NULL ? message :\r
+ std::string(message, stack_trace);\r
+}\r
+\r
+// Prints a TestPartResult object.\r
+std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {\r
+ return os\r
+ << result.file_name() << ":" << result.line_number() << ": "\r
+ << (result.type() == TestPartResult::kSuccess ? "Success" :\r
+ result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :\r
+ "Non-fatal failure") << ":\n"\r
+ << result.message() << std::endl;\r
+}\r
+\r
+// Appends a TestPartResult to the array.\r
+void TestPartResultArray::Append(const TestPartResult& result) {\r
+ array_.push_back(result);\r
+}\r
+\r
+// Returns the TestPartResult at the given index (0-based).\r
+const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {\r
+ if (index < 0 || index >= size()) {\r
+ printf("\nInvalid index (%d) into TestPartResultArray.\n", index);\r
+ internal::posix::Abort();\r
+ }\r
+\r
+ return array_[index];\r
+}\r
+\r
+// Returns the number of TestPartResult objects in the array.\r
+int TestPartResultArray::size() const {\r
+ return static_cast<int>(array_.size());\r
+}\r
+\r
+namespace internal {\r
+\r
+HasNewFatalFailureHelper::HasNewFatalFailureHelper()\r
+ : has_new_fatal_failure_(false),\r
+ original_reporter_(GetUnitTestImpl()->\r
+ GetTestPartResultReporterForCurrentThread()) {\r
+ GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);\r
+}\r
+\r
+HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {\r
+ GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(\r
+ original_reporter_);\r
+}\r
+\r
+void HasNewFatalFailureHelper::ReportTestPartResult(\r
+ const TestPartResult& result) {\r
+ if (result.fatally_failed())\r
+ has_new_fatal_failure_ = true;\r
+ original_reporter_->ReportTestPartResult(result);\r
+}\r
+\r
+} // namespace internal\r
+\r
+} // namespace testing\r
+// Copyright 2008 Google Inc.\r
+// All Rights Reserved.\r
+//\r
+// Redistribution and use in source and binary forms, with or without\r
+// modification, are permitted provided that the following conditions are\r
+// met:\r
+//\r
+// * Redistributions of source code must retain the above copyright\r
+// notice, this list of conditions and the following disclaimer.\r
+// * Redistributions in binary form must reproduce the above\r
+// copyright notice, this list of conditions and the following disclaimer\r
+// in the documentation and/or other materials provided with the\r
+// distribution.\r
+// * Neither the name of Google Inc. nor the names of its\r
+// contributors may be used to endorse or promote products derived from\r
+// this software without specific prior written permission.\r
+//\r
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+//\r
+// Author: wan@google.com (Zhanyong Wan)\r
+\r
+\r
+namespace testing {\r
+namespace internal {\r
+\r
+#if GTEST_HAS_TYPED_TEST_P\r
+\r
+// Skips to the first non-space char in str. Returns an empty string if str\r
+// contains only whitespace characters.\r
+static const char* SkipSpaces(const char* str) {\r
+ while (IsSpace(*str))\r
+ str++;\r
+ return str;\r
+}\r
+\r
+static std::vector<std::string> SplitIntoTestNames(const char* src) {\r
+ std::vector<std::string> name_vec;\r
+ src = SkipSpaces(src);\r
+ for (; src != NULL; src = SkipComma(src)) {\r
+ name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));\r
+ }\r
+ return name_vec;\r
+}\r
+\r
+// Verifies that registered_tests match the test names in\r
+// registered_tests_; returns registered_tests if successful, or\r
+// aborts the program otherwise.\r
+const char* TypedTestCasePState::VerifyRegisteredTestNames(\r
+ const char* file, int line, const char* registered_tests) {\r
+ typedef RegisteredTestsMap::const_iterator RegisteredTestIter;\r
+ registered_ = true;\r
+\r
+ std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);\r
+\r
+ Message errors;\r
+\r
+ std::set<std::string> tests;\r
+ for (std::vector<std::string>::const_iterator name_it = name_vec.begin();\r
+ name_it != name_vec.end(); ++name_it) {\r
+ const std::string& name = *name_it;\r
+ if (tests.count(name) != 0) {\r
+ errors << "Test " << name << " is listed more than once.\n";\r
+ continue;\r
+ }\r
+\r
+ bool found = false;\r
+ for (RegisteredTestIter it = registered_tests_.begin();\r
+ it != registered_tests_.end();\r
+ ++it) {\r
+ if (name == it->first) {\r
+ found = true;\r
+ break;\r
+ }\r
+ }\r
+\r
+ if (found) {\r
+ tests.insert(name);\r
+ } else {\r
+ errors << "No test named " << name\r
+ << " can be found in this test case.\n";\r
+ }\r
+ }\r
+\r
+ for (RegisteredTestIter it = registered_tests_.begin();\r
+ it != registered_tests_.end();\r
+ ++it) {\r
+ if (tests.count(it->first) == 0) {\r
+ errors << "You forgot to list test " << it->first << ".\n";\r
+ }\r
+ }\r
+\r
+ const std::string& errors_str = errors.GetString();\r
+ if (errors_str != "") {\r
+ fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),\r
+ errors_str.c_str());\r
+ fflush(stderr);\r
+ posix::Abort();\r
+ }\r
+\r
+ return registered_tests;\r
+}\r
+\r
+#endif // GTEST_HAS_TYPED_TEST_P\r
+\r
+} // namespace internal\r
+} // namespace testing\r