?login_element?

Subversion Repositories NedoOS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. // Copyright 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. //     * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. //     * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. //     * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29.  
  30. //
  31. // The Google C++ Testing and Mocking Framework (Google Test)
  32.  
  33. #include "gtest/gtest.h"
  34. #include "gtest/internal/custom/gtest.h"
  35. #include "gtest/gtest-spi.h"
  36.  
  37. #include <ctype.h>
  38. #include <math.h>
  39. #include <stdarg.h>
  40. #include <stdio.h>
  41. #include <stdlib.h>
  42. #include <time.h>
  43. #include <wchar.h>
  44. #include <wctype.h>
  45.  
  46. #include <algorithm>
  47. #include <iomanip>
  48. #include <limits>
  49. #include <list>
  50. #include <map>
  51. #include <ostream>  // NOLINT
  52. #include <sstream>
  53. #include <vector>
  54.  
  55. #if GTEST_OS_LINUX
  56.  
  57. // FIXME: Use autoconf to detect availability of
  58. // gettimeofday().
  59. # define GTEST_HAS_GETTIMEOFDAY_ 1
  60.  
  61. # include <fcntl.h>  // NOLINT
  62. # include <limits.h>  // NOLINT
  63. # include <sched.h>  // NOLINT
  64. // Declares vsnprintf().  This header is not available on Windows.
  65. # include <strings.h>  // NOLINT
  66. # include <sys/mman.h>  // NOLINT
  67. # include <sys/time.h>  // NOLINT
  68. # include <unistd.h>  // NOLINT
  69. # include <string>
  70.  
  71. #elif GTEST_OS_SYMBIAN
  72. # define GTEST_HAS_GETTIMEOFDAY_ 1
  73. # include <sys/time.h>  // NOLINT
  74.  
  75. #elif GTEST_OS_ZOS
  76. # define GTEST_HAS_GETTIMEOFDAY_ 1
  77. # include <sys/time.h>  // NOLINT
  78.  
  79. // On z/OS we additionally need strings.h for strcasecmp.
  80. # include <strings.h>  // NOLINT
  81.  
  82. #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
  83.  
  84. # include <windows.h>  // NOLINT
  85. # undef min
  86.  
  87. #elif GTEST_OS_WINDOWS  // We are on Windows proper.
  88.  
  89. # include <io.h>  // NOLINT
  90. # include <sys/timeb.h>  // NOLINT
  91. # include <sys/types.h>  // NOLINT
  92. # include <sys/stat.h>  // NOLINT
  93.  
  94. # if GTEST_OS_WINDOWS_MINGW
  95. // MinGW has gettimeofday() but not _ftime64().
  96. // FIXME: Use autoconf to detect availability of
  97. //   gettimeofday().
  98. // FIXME: There are other ways to get the time on
  99. //   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
  100. //   supports these.  consider using them instead.
  101. #  define GTEST_HAS_GETTIMEOFDAY_ 1
  102. #  include <sys/time.h>  // NOLINT
  103. # endif  // GTEST_OS_WINDOWS_MINGW
  104.  
  105. // cpplint thinks that the header is already included, so we want to
  106. // silence it.
  107. # include <windows.h>  // NOLINT
  108. # undef min
  109.  
  110. #else
  111.  
  112. // Assume other platforms have gettimeofday().
  113. // FIXME: Use autoconf to detect availability of
  114. //   gettimeofday().
  115. # define GTEST_HAS_GETTIMEOFDAY_ 1
  116.  
  117. // cpplint thinks that the header is already included, so we want to
  118. // silence it.
  119. # include <sys/time.h>  // NOLINT
  120. # include <unistd.h>  // NOLINT
  121.  
  122. #endif  // GTEST_OS_LINUX
  123.  
  124. #if GTEST_HAS_EXCEPTIONS
  125. # include <stdexcept>
  126. #endif
  127.  
  128. #if GTEST_CAN_STREAM_RESULTS_
  129. # include <arpa/inet.h>  // NOLINT
  130. # include <netdb.h>  // NOLINT
  131. # include <sys/socket.h>  // NOLINT
  132. # include <sys/types.h>  // NOLINT
  133. #endif
  134.  
  135. #include "src/gtest-internal-inl.h"
  136.  
  137. #if GTEST_OS_WINDOWS
  138. # define vsnprintf _vsnprintf
  139. #endif  // GTEST_OS_WINDOWS
  140.  
  141. #if GTEST_OS_MAC
  142. #ifndef GTEST_OS_IOS
  143. #include <crt_externs.h>
  144. #endif
  145. #endif
  146.  
  147. #if GTEST_HAS_ABSL
  148. #include "absl/debugging/failure_signal_handler.h"
  149. #include "absl/debugging/stacktrace.h"
  150. #include "absl/debugging/symbolize.h"
  151. #include "absl/strings/str_cat.h"
  152. #endif  // GTEST_HAS_ABSL
  153.  
  154. namespace testing {
  155.  
  156. using internal::CountIf;
  157. using internal::ForEach;
  158. using internal::GetElementOr;
  159. using internal::Shuffle;
  160.  
  161. // Constants.
  162.  
  163. // A test whose test case name or test name matches this filter is
  164. // disabled and not run.
  165. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  166.  
  167. // A test case whose name matches this filter is considered a death
  168. // test case and will be run before test cases whose name doesn't
  169. // match this filter.
  170. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
  171.  
  172. // A test filter that matches everything.
  173. static const char kUniversalFilter[] = "*";
  174.  
  175. // The default output format.
  176. static const char kDefaultOutputFormat[] = "xml";
  177. // The default output file.
  178. static const char kDefaultOutputFile[] = "test_detail";
  179.  
  180. // The environment variable name for the test shard index.
  181. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  182. // The environment variable name for the total number of test shards.
  183. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  184. // The environment variable name for the test shard status file.
  185. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  186.  
  187. namespace internal {
  188.  
  189. // The text used in failure messages to indicate the start of the
  190. // stack trace.
  191. const char kStackTraceMarker[] = "\nStack trace:\n";
  192.  
  193. // g_help_flag is true iff the --help flag or an equivalent form is
  194. // specified on the command line.
  195. bool g_help_flag = false;
  196.  
  197. // Utilty function to Open File for Writing
  198. static FILE* OpenFileForWriting(const std::string& output_file) {
  199.   FILE* fileout = NULL;
  200.   FilePath output_file_path(output_file);
  201.   FilePath output_dir(output_file_path.RemoveFileName());
  202.  
  203.   if (output_dir.CreateDirectoriesRecursively()) {
  204.     fileout = posix::FOpen(output_file.c_str(), "w");
  205.   }
  206.   if (fileout == NULL) {
  207.     GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
  208.   }
  209.   return fileout;
  210. }
  211.  
  212. }  // namespace internal
  213.  
  214. // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
  215. // environment variable.
  216. static const char* GetDefaultFilter() {
  217.   const char* const testbridge_test_only =
  218.       internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
  219.   if (testbridge_test_only != NULL) {
  220.     return testbridge_test_only;
  221.   }
  222.   return kUniversalFilter;
  223. }
  224.  
  225. GTEST_DEFINE_bool_(
  226.     also_run_disabled_tests,
  227.     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  228.     "Run disabled tests too, in addition to the tests normally being run.");
  229.  
  230. GTEST_DEFINE_bool_(
  231.     break_on_failure,
  232.     internal::BoolFromGTestEnv("break_on_failure", false),
  233.     "True iff a failed assertion should be a debugger break-point.");
  234.  
  235. GTEST_DEFINE_bool_(
  236.     catch_exceptions,
  237.     internal::BoolFromGTestEnv("catch_exceptions", true),
  238.     "True iff " GTEST_NAME_
  239.     " should catch exceptions and treat them as test failures.");
  240.  
  241. GTEST_DEFINE_string_(
  242.     color,
  243.     internal::StringFromGTestEnv("color", "auto"),
  244.     "Whether to use colors in the output.  Valid values: yes, no, "
  245.     "and auto.  'auto' means to use colors if the output is "
  246.     "being sent to a terminal and the TERM environment variable "
  247.     "is set to a terminal type that supports colors.");
  248.  
  249. GTEST_DEFINE_string_(
  250.     filter,
  251.     internal::StringFromGTestEnv("filter", GetDefaultFilter()),
  252.     "A colon-separated list of glob (not regex) patterns "
  253.     "for filtering the tests to run, optionally followed by a "
  254.     "'-' and a : separated list of negative patterns (tests to "
  255.     "exclude).  A test is run if it matches one of the positive "
  256.     "patterns and does not match any of the negative patterns.");
  257.  
  258. GTEST_DEFINE_bool_(
  259.     install_failure_signal_handler,
  260.     internal::BoolFromGTestEnv("install_failure_signal_handler", false),
  261.     "If true and supported on the current platform, " GTEST_NAME_ " should "
  262.     "install a signal handler that dumps debugging information when fatal "
  263.     "signals are raised.");
  264.  
  265. GTEST_DEFINE_bool_(list_tests, false,
  266.                    "List all tests without running them.");
  267.  
  268. // The net priority order after flag processing is thus:
  269. //   --gtest_output command line flag
  270. //   GTEST_OUTPUT environment variable
  271. //   XML_OUTPUT_FILE environment variable
  272. //   ''
  273. GTEST_DEFINE_string_(
  274.     output,
  275.     internal::StringFromGTestEnv("output",
  276.       internal::OutputFlagAlsoCheckEnvVar().c_str()),
  277.     "A format (defaults to \"xml\" but can be specified to be \"json\"), "
  278.     "optionally followed by a colon and an output file name or directory. "
  279.     "A directory is indicated by a trailing pathname separator. "
  280.     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  281.     "If a directory is specified, output files will be created "
  282.     "within that directory, with file-names based on the test "
  283.     "executable's name and, if necessary, made unique by adding "
  284.     "digits.");
  285.  
  286. GTEST_DEFINE_bool_(
  287.     print_time,
  288.     internal::BoolFromGTestEnv("print_time", true),
  289.     "True iff " GTEST_NAME_
  290.     " should display elapsed time in text output.");
  291.  
  292. GTEST_DEFINE_bool_(
  293.     print_utf8,
  294.     internal::BoolFromGTestEnv("print_utf8", true),
  295.     "True iff " GTEST_NAME_
  296.     " prints UTF8 characters as text.");
  297.  
  298. GTEST_DEFINE_int32_(
  299.     random_seed,
  300.     internal::Int32FromGTestEnv("random_seed", 0),
  301.     "Random number seed to use when shuffling test orders.  Must be in range "
  302.     "[1, 99999], or 0 to use a seed based on the current time.");
  303.  
  304. GTEST_DEFINE_int32_(
  305.     repeat,
  306.     internal::Int32FromGTestEnv("repeat", 1),
  307.     "How many times to repeat each test.  Specify a negative number "
  308.     "for repeating forever.  Useful for shaking out flaky tests.");
  309.  
  310. GTEST_DEFINE_bool_(
  311.     show_internal_stack_frames, false,
  312.     "True iff " GTEST_NAME_ " should include internal stack frames when "
  313.     "printing test failure stack traces.");
  314.  
  315. GTEST_DEFINE_bool_(
  316.     shuffle,
  317.     internal::BoolFromGTestEnv("shuffle", false),
  318.     "True iff " GTEST_NAME_
  319.     " should randomize tests' order on every run.");
  320.  
  321. GTEST_DEFINE_int32_(
  322.     stack_trace_depth,
  323.     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  324.     "The maximum number of stack frames to print when an "
  325.     "assertion fails.  The valid range is 0 through 100, inclusive.");
  326.  
  327. GTEST_DEFINE_string_(
  328.     stream_result_to,
  329.     internal::StringFromGTestEnv("stream_result_to", ""),
  330.     "This flag specifies the host name and the port number on which to stream "
  331.     "test results. Example: \"localhost:555\". The flag is effective only on "
  332.     "Linux.");
  333.  
  334. GTEST_DEFINE_bool_(
  335.     throw_on_failure,
  336.     internal::BoolFromGTestEnv("throw_on_failure", false),
  337.     "When this flag is specified, a failed assertion will throw an exception "
  338.     "if exceptions are enabled or exit the program with a non-zero code "
  339.     "otherwise. For use with an external test framework.");
  340.  
  341. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  342. GTEST_DEFINE_string_(
  343.     flagfile,
  344.     internal::StringFromGTestEnv("flagfile", ""),
  345.     "This flag specifies the flagfile to read command-line flags from.");
  346. #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
  347.  
  348. namespace internal {
  349.  
  350. // Generates a random number from [0, range), using a Linear
  351. // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
  352. // than kMaxRange.
  353. UInt32 Random::Generate(UInt32 range) {
  354.   // These constants are the same as are used in glibc's rand(3).
  355.   // Use wider types than necessary to prevent unsigned overflow diagnostics.
  356.   state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
  357.  
  358.   GTEST_CHECK_(range > 0)
  359.       << "Cannot generate a number in the range [0, 0).";
  360.   GTEST_CHECK_(range <= kMaxRange)
  361.       << "Generation of a number in [0, " << range << ") was requested, "
  362.       << "but this can only generate numbers in [0, " << kMaxRange << ").";
  363.  
  364.   // Converting via modulus introduces a bit of downward bias, but
  365.   // it's simple, and a linear congruential generator isn't too good
  366.   // to begin with.
  367.   return state_ % range;
  368. }
  369.  
  370. // GTestIsInitialized() returns true iff the user has initialized
  371. // Google Test.  Useful for catching the user mistake of not initializing
  372. // Google Test before calling RUN_ALL_TESTS().
  373. static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
  374.  
  375. // Iterates over a vector of TestCases, keeping a running sum of the
  376. // results of calling a given int-returning method on each.
  377. // Returns the sum.
  378. static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
  379.                                int (TestCase::*method)() const) {
  380.   int sum = 0;
  381.   for (size_t i = 0; i < case_list.size(); i++) {
  382.     sum += (case_list[i]->*method)();
  383.   }
  384.   return sum;
  385. }
  386.  
  387. // Returns true iff the test case passed.
  388. static bool TestCasePassed(const TestCase* test_case) {
  389.   return test_case->should_run() && test_case->Passed();
  390. }
  391.  
  392. // Returns true iff the test case failed.
  393. static bool TestCaseFailed(const TestCase* test_case) {
  394.   return test_case->should_run() && test_case->Failed();
  395. }
  396.  
  397. // Returns true iff test_case contains at least one test that should
  398. // run.
  399. static bool ShouldRunTestCase(const TestCase* test_case) {
  400.   return test_case->should_run();
  401. }
  402.  
  403. // AssertHelper constructor.
  404. AssertHelper::AssertHelper(TestPartResult::Type type,
  405.                            const char* file,
  406.                            int line,
  407.                            const char* message)
  408.     : data_(new AssertHelperData(type, file, line, message)) {
  409. }
  410.  
  411. AssertHelper::~AssertHelper() {
  412.   delete data_;
  413. }
  414.  
  415. // Message assignment, for assertion streaming support.
  416. void AssertHelper::operator=(const Message& message) const {
  417.   UnitTest::GetInstance()->
  418.     AddTestPartResult(data_->type, data_->file, data_->line,
  419.                       AppendUserMessage(data_->message, message),
  420.                       UnitTest::GetInstance()->impl()
  421.                       ->CurrentOsStackTraceExceptTop(1)
  422.                       // Skips the stack frame for this function itself.
  423.                       );  // NOLINT
  424. }
  425.  
  426. // Mutex for linked pointers.
  427. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
  428.  
  429. // A copy of all command line arguments.  Set by InitGoogleTest().
  430. ::std::vector<std::string> g_argvs;
  431.  
  432. ::std::vector<std::string> GetArgvs() {
  433. #if defined(GTEST_CUSTOM_GET_ARGVS_)
  434.   // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
  435.   // ::string. This code converts it to the appropriate type.
  436.   const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
  437.   return ::std::vector<std::string>(custom.begin(), custom.end());
  438. #else   // defined(GTEST_CUSTOM_GET_ARGVS_)
  439.   return g_argvs;
  440. #endif  // defined(GTEST_CUSTOM_GET_ARGVS_)
  441. }
  442.  
  443. // Returns the current application's name, removing directory path if that
  444. // is present.
  445. FilePath GetCurrentExecutableName() {
  446.   FilePath result;
  447.  
  448. #if GTEST_OS_WINDOWS
  449.   result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
  450. #else
  451.   result.Set(FilePath(GetArgvs()[0]));
  452. #endif  // GTEST_OS_WINDOWS
  453.  
  454.   return result.RemoveDirectoryName();
  455. }
  456.  
  457. // Functions for processing the gtest_output flag.
  458.  
  459. // Returns the output format, or "" for normal printed output.
  460. std::string UnitTestOptions::GetOutputFormat() {
  461.   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  462.   if (gtest_output_flag == NULL) return std::string("");
  463.  
  464.   const char* const colon = strchr(gtest_output_flag, ':');
  465.   return (colon == NULL) ?
  466.       std::string(gtest_output_flag) :
  467.       std::string(gtest_output_flag, colon - gtest_output_flag);
  468. }
  469.  
  470. // Returns the name of the requested output file, or the default if none
  471. // was explicitly specified.
  472. // FIXME Remove GetAbsolutePathToOutputFile checking gtest_output_flag == NULL
  473. std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
  474.   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  475.   if (gtest_output_flag == NULL)
  476.     return "";
  477.  
  478.   std::string format = GetOutputFormat();
  479.   if (format.empty())
  480.     format = std::string(kDefaultOutputFormat);
  481.  
  482.   const char* const colon = strchr(gtest_output_flag, ':');
  483.   if (colon == NULL)
  484.     return internal::FilePath::MakeFileName(
  485.         internal::FilePath(
  486.             UnitTest::GetInstance()->original_working_dir()),
  487.         internal::FilePath(kDefaultOutputFile), 0,
  488.         format.c_str()).string();
  489.  
  490.   internal::FilePath output_name(colon + 1);
  491.   if (!output_name.IsAbsolutePath())
  492.     // FIXME: on Windows \some\path is not an absolute
  493.     // path (as its meaning depends on the current drive), yet the
  494.     // following logic for turning it into an absolute path is wrong.
  495.     // Fix it.
  496.     output_name = internal::FilePath::ConcatPaths(
  497.         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  498.         internal::FilePath(colon + 1));
  499.  
  500.   if (!output_name.IsDirectory())
  501.     return output_name.string();
  502.  
  503.   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  504.       output_name, internal::GetCurrentExecutableName(),
  505.       GetOutputFormat().c_str()));
  506.   return result.string();
  507. }
  508.  
  509. // Returns true iff the wildcard pattern matches the string.  The
  510. // first ':' or '\0' character in pattern marks the end of it.
  511. //
  512. // This recursive algorithm isn't very efficient, but is clear and
  513. // works well enough for matching test names, which are short.
  514. bool UnitTestOptions::PatternMatchesString(const char *pattern,
  515.                                            const char *str) {
  516.   switch (*pattern) {
  517.     case '\0':
  518.     case ':':  // Either ':' or '\0' marks the end of the pattern.
  519.       return *str == '\0';
  520.     case '?':  // Matches any single character.
  521.       return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
  522.     case '*':  // Matches any string (possibly empty) of characters.
  523.       return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
  524.           PatternMatchesString(pattern + 1, str);
  525.     default:  // Non-special character.  Matches itself.
  526.       return *pattern == *str &&
  527.           PatternMatchesString(pattern + 1, str + 1);
  528.   }
  529. }
  530.  
  531. bool UnitTestOptions::MatchesFilter(
  532.     const std::string& name, const char* filter) {
  533.   const char *cur_pattern = filter;
  534.   for (;;) {
  535.     if (PatternMatchesString(cur_pattern, name.c_str())) {
  536.       return true;
  537.     }
  538.  
  539.     // Finds the next pattern in the filter.
  540.     cur_pattern = strchr(cur_pattern, ':');
  541.  
  542.     // Returns if no more pattern can be found.
  543.     if (cur_pattern == NULL) {
  544.       return false;
  545.     }
  546.  
  547.     // Skips the pattern separater (the ':' character).
  548.     cur_pattern++;
  549.   }
  550. }
  551.  
  552. // Returns true iff the user-specified filter matches the test case
  553. // name and the test name.
  554. bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
  555.                                         const std::string &test_name) {
  556.   const std::string& full_name = test_case_name + "." + test_name.c_str();
  557.  
  558.   // Split --gtest_filter at '-', if there is one, to separate into
  559.   // positive filter and negative filter portions
  560.   const char* const p = GTEST_FLAG(filter).c_str();
  561.   const char* const dash = strchr(p, '-');
  562.   std::string positive;
  563.   std::string negative;
  564.   if (dash == NULL) {
  565.     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
  566.     negative = "";
  567.   } else {
  568.     positive = std::string(p, dash);   // Everything up to the dash
  569.     negative = std::string(dash + 1);  // Everything after the dash
  570.     if (positive.empty()) {
  571.       // Treat '-test1' as the same as '*-test1'
  572.       positive = kUniversalFilter;
  573.     }
  574.   }
  575.  
  576.   // A filter is a colon-separated list of patterns.  It matches a
  577.   // test if any pattern in it matches the test.
  578.   return (MatchesFilter(full_name, positive.c_str()) &&
  579.           !MatchesFilter(full_name, negative.c_str()));
  580. }
  581.  
  582. #if GTEST_HAS_SEH
  583. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  584. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  585. // This function is useful as an __except condition.
  586. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  587.   // Google Test should handle a SEH exception if:
  588.   //   1. the user wants it to, AND
  589.   //   2. this is not a breakpoint exception, AND
  590.   //   3. this is not a C++ exception (VC++ implements them via SEH,
  591.   //      apparently).
  592.   //
  593.   // SEH exception code for C++ exceptions.
  594.   // (see http://support.microsoft.com/kb/185294 for more information).
  595.   const DWORD kCxxExceptionCode = 0xe06d7363;
  596.  
  597.   bool should_handle = true;
  598.  
  599.   if (!GTEST_FLAG(catch_exceptions))
  600.     should_handle = false;
  601.   else if (exception_code == EXCEPTION_BREAKPOINT)
  602.     should_handle = false;
  603.   else if (exception_code == kCxxExceptionCode)
  604.     should_handle = false;
  605.  
  606.   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  607. }
  608. #endif  // GTEST_HAS_SEH
  609.  
  610. }  // namespace internal
  611.  
  612. // The c'tor sets this object as the test part result reporter used by
  613. // Google Test.  The 'result' parameter specifies where to report the
  614. // results. Intercepts only failures from the current thread.
  615. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  616.     TestPartResultArray* result)
  617.     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  618.       result_(result) {
  619.   Init();
  620. }
  621.  
  622. // The c'tor sets this object as the test part result reporter used by
  623. // Google Test.  The 'result' parameter specifies where to report the
  624. // results.
  625. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  626.     InterceptMode intercept_mode, TestPartResultArray* result)
  627.     : intercept_mode_(intercept_mode),
  628.       result_(result) {
  629.   Init();
  630. }
  631.  
  632. void ScopedFakeTestPartResultReporter::Init() {
  633.   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  634.   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  635.     old_reporter_ = impl->GetGlobalTestPartResultReporter();
  636.     impl->SetGlobalTestPartResultReporter(this);
  637.   } else {
  638.     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  639.     impl->SetTestPartResultReporterForCurrentThread(this);
  640.   }
  641. }
  642.  
  643. // The d'tor restores the test part result reporter used by Google Test
  644. // before.
  645. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  646.   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  647.   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  648.     impl->SetGlobalTestPartResultReporter(old_reporter_);
  649.   } else {
  650.     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  651.   }
  652. }
  653.  
  654. // Increments the test part result count and remembers the result.
  655. // This method is from the TestPartResultReporterInterface interface.
  656. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  657.     const TestPartResult& result) {
  658.   result_->Append(result);
  659. }
  660.  
  661. namespace internal {
  662.  
  663. // Returns the type ID of ::testing::Test.  We should always call this
  664. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  665. // testing::Test.  This is to work around a suspected linker bug when
  666. // using Google Test as a framework on Mac OS X.  The bug causes
  667. // GetTypeId< ::testing::Test>() to return different values depending
  668. // on whether the call is from the Google Test framework itself or
  669. // from user test code.  GetTestTypeId() is guaranteed to always
  670. // return the same value, as it always calls GetTypeId<>() from the
  671. // gtest.cc, which is within the Google Test framework.
  672. TypeId GetTestTypeId() {
  673.   return GetTypeId<Test>();
  674. }
  675.  
  676. // The value of GetTestTypeId() as seen from within the Google Test
  677. // library.  This is solely for testing GetTestTypeId().
  678. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  679.  
  680. // This predicate-formatter checks that 'results' contains a test part
  681. // failure of the given type and that the failure message contains the
  682. // given substring.
  683. static AssertionResult HasOneFailure(const char* /* results_expr */,
  684.                                      const char* /* type_expr */,
  685.                                      const char* /* substr_expr */,
  686.                                      const TestPartResultArray& results,
  687.                                      TestPartResult::Type type,
  688.                                      const std::string& substr) {
  689.   const std::string expected(type == TestPartResult::kFatalFailure ?
  690.                         "1 fatal failure" :
  691.                         "1 non-fatal failure");
  692.   Message msg;
  693.   if (results.size() != 1) {
  694.     msg << "Expected: " << expected << "\n"
  695.         << "  Actual: " << results.size() << " failures";
  696.     for (int i = 0; i < results.size(); i++) {
  697.       msg << "\n" << results.GetTestPartResult(i);
  698.     }
  699.     return AssertionFailure() << msg;
  700.   }
  701.  
  702.   const TestPartResult& r = results.GetTestPartResult(0);
  703.   if (r.type() != type) {
  704.     return AssertionFailure() << "Expected: " << expected << "\n"
  705.                               << "  Actual:\n"
  706.                               << r;
  707.   }
  708.  
  709.   if (strstr(r.message(), substr.c_str()) == NULL) {
  710.     return AssertionFailure() << "Expected: " << expected << " containing \""
  711.                               << substr << "\"\n"
  712.                               << "  Actual:\n"
  713.                               << r;
  714.   }
  715.  
  716.   return AssertionSuccess();
  717. }
  718.  
  719. // The constructor of SingleFailureChecker remembers where to look up
  720. // test part results, what type of failure we expect, and what
  721. // substring the failure message should contain.
  722. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
  723.                                            TestPartResult::Type type,
  724.                                            const std::string& substr)
  725.     : results_(results), type_(type), substr_(substr) {}
  726.  
  727. // The destructor of SingleFailureChecker verifies that the given
  728. // TestPartResultArray contains exactly one failure that has the given
  729. // type and contains the given substring.  If that's not the case, a
  730. // non-fatal failure will be generated.
  731. SingleFailureChecker::~SingleFailureChecker() {
  732.   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  733. }
  734.  
  735. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  736.     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  737.  
  738. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  739.     const TestPartResult& result) {
  740.   unit_test_->current_test_result()->AddTestPartResult(result);
  741.   unit_test_->listeners()->repeater()->OnTestPartResult(result);
  742. }
  743.  
  744. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  745.     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  746.  
  747. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  748.     const TestPartResult& result) {
  749.   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  750. }
  751.  
  752. // Returns the global test part result reporter.
  753. TestPartResultReporterInterface*
  754. UnitTestImpl::GetGlobalTestPartResultReporter() {
  755.   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  756.   return global_test_part_result_repoter_;
  757. }
  758.  
  759. // Sets the global test part result reporter.
  760. void UnitTestImpl::SetGlobalTestPartResultReporter(
  761.     TestPartResultReporterInterface* reporter) {
  762.   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  763.   global_test_part_result_repoter_ = reporter;
  764. }
  765.  
  766. // Returns the test part result reporter for the current thread.
  767. TestPartResultReporterInterface*
  768. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  769.   return per_thread_test_part_result_reporter_.get();
  770. }
  771.  
  772. // Sets the test part result reporter for the current thread.
  773. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  774.     TestPartResultReporterInterface* reporter) {
  775.   per_thread_test_part_result_reporter_.set(reporter);
  776. }
  777.  
  778. // Gets the number of successful test cases.
  779. int UnitTestImpl::successful_test_case_count() const {
  780.   return CountIf(test_cases_, TestCasePassed);
  781. }
  782.  
  783. // Gets the number of failed test cases.
  784. int UnitTestImpl::failed_test_case_count() const {
  785.   return CountIf(test_cases_, TestCaseFailed);
  786. }
  787.  
  788. // Gets the number of all test cases.
  789. int UnitTestImpl::total_test_case_count() const {
  790.   return static_cast<int>(test_cases_.size());
  791. }
  792.  
  793. // Gets the number of all test cases that contain at least one test
  794. // that should run.
  795. int UnitTestImpl::test_case_to_run_count() const {
  796.   return CountIf(test_cases_, ShouldRunTestCase);
  797. }
  798.  
  799. // Gets the number of successful tests.
  800. int UnitTestImpl::successful_test_count() const {
  801.   return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
  802. }
  803.  
  804. // Gets the number of failed tests.
  805. int UnitTestImpl::failed_test_count() const {
  806.   return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
  807. }
  808.  
  809. // Gets the number of disabled tests that will be reported in the XML report.
  810. int UnitTestImpl::reportable_disabled_test_count() const {
  811.   return SumOverTestCaseList(test_cases_,
  812.                              &TestCase::reportable_disabled_test_count);
  813. }
  814.  
  815. // Gets the number of disabled tests.
  816. int UnitTestImpl::disabled_test_count() const {
  817.   return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
  818. }
  819.  
  820. // Gets the number of tests to be printed in the XML report.
  821. int UnitTestImpl::reportable_test_count() const {
  822.   return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
  823. }
  824.  
  825. // Gets the number of all tests.
  826. int UnitTestImpl::total_test_count() const {
  827.   return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
  828. }
  829.  
  830. // Gets the number of tests that should run.
  831. int UnitTestImpl::test_to_run_count() const {
  832.   return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
  833. }
  834.  
  835. // Returns the current OS stack trace as an std::string.
  836. //
  837. // The maximum number of stack frames to be included is specified by
  838. // the gtest_stack_trace_depth flag.  The skip_count parameter
  839. // specifies the number of top frames to be skipped, which doesn't
  840. // count against the number of frames to be included.
  841. //
  842. // For example, if Foo() calls Bar(), which in turn calls
  843. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  844. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  845. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  846.   return os_stack_trace_getter()->CurrentStackTrace(
  847.       static_cast<int>(GTEST_FLAG(stack_trace_depth)),
  848.       skip_count + 1
  849.       // Skips the user-specified number of frames plus this function
  850.       // itself.
  851.       );  // NOLINT
  852. }
  853.  
  854. // Returns the current time in milliseconds.
  855. TimeInMillis GetTimeInMillis() {
  856. #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
  857.   // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
  858.   // http://analogous.blogspot.com/2005/04/epoch.html
  859.   const TimeInMillis kJavaEpochToWinFileTimeDelta =
  860.     static_cast<TimeInMillis>(116444736UL) * 100000UL;
  861.   const DWORD kTenthMicrosInMilliSecond = 10000;
  862.  
  863.   SYSTEMTIME now_systime;
  864.   FILETIME now_filetime;
  865.   ULARGE_INTEGER now_int64;
  866.   // FIXME: Shouldn't this just use
  867.   //   GetSystemTimeAsFileTime()?
  868.   GetSystemTime(&now_systime);
  869.   if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
  870.     now_int64.LowPart = now_filetime.dwLowDateTime;
  871.     now_int64.HighPart = now_filetime.dwHighDateTime;
  872.     now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
  873.       kJavaEpochToWinFileTimeDelta;
  874.     return now_int64.QuadPart;
  875.   }
  876.   return 0;
  877. #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
  878.   __timeb64 now;
  879.  
  880.   // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
  881.   // (deprecated function) there.
  882.   // FIXME: Use GetTickCount()?  Or use
  883.   //   SystemTimeToFileTime()
  884.   GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  885.   _ftime64(&now);
  886.   GTEST_DISABLE_MSC_DEPRECATED_POP_()
  887.  
  888.   return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
  889. #elif GTEST_HAS_GETTIMEOFDAY_
  890.   struct timeval now;
  891.   gettimeofday(&now, NULL);
  892.   return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
  893. #else
  894. # error "Don't know how to get the current time on your system."
  895. #endif
  896. }
  897.  
  898. // Utilities
  899.  
  900. // class String.
  901.  
  902. #if GTEST_OS_WINDOWS_MOBILE
  903. // Creates a UTF-16 wide string from the given ANSI string, allocating
  904. // memory using new. The caller is responsible for deleting the return
  905. // value using delete[]. Returns the wide string, or NULL if the
  906. // input is NULL.
  907. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  908.   if (!ansi) return NULL;
  909.   const int length = strlen(ansi);
  910.   const int unicode_length =
  911.       MultiByteToWideChar(CP_ACP, 0, ansi, length,
  912.                           NULL, 0);
  913.   WCHAR* unicode = new WCHAR[unicode_length + 1];
  914.   MultiByteToWideChar(CP_ACP, 0, ansi, length,
  915.                       unicode, unicode_length);
  916.   unicode[unicode_length] = 0;
  917.   return unicode;
  918. }
  919.  
  920. // Creates an ANSI string from the given wide string, allocating
  921. // memory using new. The caller is responsible for deleting the return
  922. // value using delete[]. Returns the ANSI string, or NULL if the
  923. // input is NULL.
  924. const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
  925.   if (!utf16_str) return NULL;
  926.   const int ansi_length =
  927.       WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  928.                           NULL, 0, NULL, NULL);
  929.   char* ansi = new char[ansi_length + 1];
  930.   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  931.                       ansi, ansi_length, NULL, NULL);
  932.   ansi[ansi_length] = 0;
  933.   return ansi;
  934. }
  935.  
  936. #endif  // GTEST_OS_WINDOWS_MOBILE
  937.  
  938. // Compares two C strings.  Returns true iff they have the same content.
  939. //
  940. // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
  941. // C string is considered different to any non-NULL C string,
  942. // including the empty string.
  943. bool String::CStringEquals(const char * lhs, const char * rhs) {
  944.   if ( lhs == NULL ) return rhs == NULL;
  945.  
  946.   if ( rhs == NULL ) return false;
  947.  
  948.   return strcmp(lhs, rhs) == 0;
  949. }
  950.  
  951. #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  952.  
  953. // Converts an array of wide chars to a narrow string using the UTF-8
  954. // encoding, and streams the result to the given Message object.
  955. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  956.                                      Message* msg) {
  957.   for (size_t i = 0; i != length; ) {  // NOLINT
  958.     if (wstr[i] != L'\0') {
  959.       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  960.       while (i != length && wstr[i] != L'\0')
  961.         i++;
  962.     } else {
  963.       *msg << '\0';
  964.       i++;
  965.     }
  966.   }
  967. }
  968.  
  969. #endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  970.  
  971. void SplitString(const ::std::string& str, char delimiter,
  972.                  ::std::vector< ::std::string>* dest) {
  973.   ::std::vector< ::std::string> parsed;
  974.   ::std::string::size_type pos = 0;
  975.   while (::testing::internal::AlwaysTrue()) {
  976.     const ::std::string::size_type colon = str.find(delimiter, pos);
  977.     if (colon == ::std::string::npos) {
  978.       parsed.push_back(str.substr(pos));
  979.       break;
  980.     } else {
  981.       parsed.push_back(str.substr(pos, colon - pos));
  982.       pos = colon + 1;
  983.     }
  984.   }
  985.   dest->swap(parsed);
  986. }
  987.  
  988. }  // namespace internal
  989.  
  990. // Constructs an empty Message.
  991. // We allocate the stringstream separately because otherwise each use of
  992. // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
  993. // stack frame leading to huge stack frames in some cases; gcc does not reuse
  994. // the stack space.
  995. Message::Message() : ss_(new ::std::stringstream) {
  996.   // By default, we want there to be enough precision when printing
  997.   // a double to a Message.
  998.   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
  999. }
  1000.  
  1001. // These two overloads allow streaming a wide C string to a Message
  1002. // using the UTF-8 encoding.
  1003. Message& Message::operator <<(const wchar_t* wide_c_str) {
  1004.   return *this << internal::String::ShowWideCString(wide_c_str);
  1005. }
  1006. Message& Message::operator <<(wchar_t* wide_c_str) {
  1007.   return *this << internal::String::ShowWideCString(wide_c_str);
  1008. }
  1009.  
  1010. #if GTEST_HAS_STD_WSTRING
  1011. // Converts the given wide string to a narrow string using the UTF-8
  1012. // encoding, and streams the result to this Message object.
  1013. Message& Message::operator <<(const ::std::wstring& wstr) {
  1014.   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  1015.   return *this;
  1016. }
  1017. #endif  // GTEST_HAS_STD_WSTRING
  1018.  
  1019. #if GTEST_HAS_GLOBAL_WSTRING
  1020. // Converts the given wide string to a narrow string using the UTF-8
  1021. // encoding, and streams the result to this Message object.
  1022. Message& Message::operator <<(const ::wstring& wstr) {
  1023.   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  1024.   return *this;
  1025. }
  1026. #endif  // GTEST_HAS_GLOBAL_WSTRING
  1027.  
  1028. // Gets the text streamed to this object so far as an std::string.
  1029. // Each '\0' character in the buffer is replaced with "\\0".
  1030. std::string Message::GetString() const {
  1031.   return internal::StringStreamToString(ss_.get());
  1032. }
  1033.  
  1034. // AssertionResult constructors.
  1035. // Used in EXPECT_TRUE/FALSE(assertion_result).
  1036. AssertionResult::AssertionResult(const AssertionResult& other)
  1037.     : success_(other.success_),
  1038.       message_(other.message_.get() != NULL ?
  1039.                new ::std::string(*other.message_) :
  1040.                static_cast< ::std::string*>(NULL)) {
  1041. }
  1042.  
  1043. // Swaps two AssertionResults.
  1044. void AssertionResult::swap(AssertionResult& other) {
  1045.   using std::swap;
  1046.   swap(success_, other.success_);
  1047.   swap(message_, other.message_);
  1048. }
  1049.  
  1050. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  1051. AssertionResult AssertionResult::operator!() const {
  1052.   AssertionResult negation(!success_);
  1053.   if (message_.get() != NULL)
  1054.     negation << *message_;
  1055.   return negation;
  1056. }
  1057.  
  1058. // Makes a successful assertion result.
  1059. AssertionResult AssertionSuccess() {
  1060.   return AssertionResult(true);
  1061. }
  1062.  
  1063. // Makes a failed assertion result.
  1064. AssertionResult AssertionFailure() {
  1065.   return AssertionResult(false);
  1066. }
  1067.  
  1068. // Makes a failed assertion result with the given failure message.
  1069. // Deprecated; use AssertionFailure() << message.
  1070. AssertionResult AssertionFailure(const Message& message) {
  1071.   return AssertionFailure() << message;
  1072. }
  1073.  
  1074. namespace internal {
  1075.  
  1076. namespace edit_distance {
  1077. std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
  1078.                                             const std::vector<size_t>& right) {
  1079.   std::vector<std::vector<double> > costs(
  1080.       left.size() + 1, std::vector<double>(right.size() + 1));
  1081.   std::vector<std::vector<EditType> > best_move(
  1082.       left.size() + 1, std::vector<EditType>(right.size() + 1));
  1083.  
  1084.   // Populate for empty right.
  1085.   for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
  1086.     costs[l_i][0] = static_cast<double>(l_i);
  1087.     best_move[l_i][0] = kRemove;
  1088.   }
  1089.   // Populate for empty left.
  1090.   for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
  1091.     costs[0][r_i] = static_cast<double>(r_i);
  1092.     best_move[0][r_i] = kAdd;
  1093.   }
  1094.  
  1095.   for (size_t l_i = 0; l_i < left.size(); ++l_i) {
  1096.     for (size_t r_i = 0; r_i < right.size(); ++r_i) {
  1097.       if (left[l_i] == right[r_i]) {
  1098.         // Found a match. Consume it.
  1099.         costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
  1100.         best_move[l_i + 1][r_i + 1] = kMatch;
  1101.         continue;
  1102.       }
  1103.  
  1104.       const double add = costs[l_i + 1][r_i];
  1105.       const double remove = costs[l_i][r_i + 1];
  1106.       const double replace = costs[l_i][r_i];
  1107.       if (add < remove && add < replace) {
  1108.         costs[l_i + 1][r_i + 1] = add + 1;
  1109.         best_move[l_i + 1][r_i + 1] = kAdd;
  1110.       } else if (remove < add && remove < replace) {
  1111.         costs[l_i + 1][r_i + 1] = remove + 1;
  1112.         best_move[l_i + 1][r_i + 1] = kRemove;
  1113.       } else {
  1114.         // We make replace a little more expensive than add/remove to lower
  1115.         // their priority.
  1116.         costs[l_i + 1][r_i + 1] = replace + 1.00001;
  1117.         best_move[l_i + 1][r_i + 1] = kReplace;
  1118.       }
  1119.     }
  1120.   }
  1121.  
  1122.   // Reconstruct the best path. We do it in reverse order.
  1123.   std::vector<EditType> best_path;
  1124.   for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
  1125.     EditType move = best_move[l_i][r_i];
  1126.     best_path.push_back(move);
  1127.     l_i -= move != kAdd;
  1128.     r_i -= move != kRemove;
  1129.   }
  1130.   std::reverse(best_path.begin(), best_path.end());
  1131.   return best_path;
  1132. }
  1133.  
  1134. namespace {
  1135.  
  1136. // Helper class to convert string into ids with deduplication.
  1137. class InternalStrings {
  1138.  public:
  1139.   size_t GetId(const std::string& str) {
  1140.     IdMap::iterator it = ids_.find(str);
  1141.     if (it != ids_.end()) return it->second;
  1142.     size_t id = ids_.size();
  1143.     return ids_[str] = id;
  1144.   }
  1145.  
  1146.  private:
  1147.   typedef std::map<std::string, size_t> IdMap;
  1148.   IdMap ids_;
  1149. };
  1150.  
  1151. }  // namespace
  1152.  
  1153. std::vector<EditType> CalculateOptimalEdits(
  1154.     const std::vector<std::string>& left,
  1155.     const std::vector<std::string>& right) {
  1156.   std::vector<size_t> left_ids, right_ids;
  1157.   {
  1158.     InternalStrings intern_table;
  1159.     for (size_t i = 0; i < left.size(); ++i) {
  1160.       left_ids.push_back(intern_table.GetId(left[i]));
  1161.     }
  1162.     for (size_t i = 0; i < right.size(); ++i) {
  1163.       right_ids.push_back(intern_table.GetId(right[i]));
  1164.     }
  1165.   }
  1166.   return CalculateOptimalEdits(left_ids, right_ids);
  1167. }
  1168.  
  1169. namespace {
  1170.  
  1171. // Helper class that holds the state for one hunk and prints it out to the
  1172. // stream.
  1173. // It reorders adds/removes when possible to group all removes before all
  1174. // adds. It also adds the hunk header before printint into the stream.
  1175. class Hunk {
  1176.  public:
  1177.   Hunk(size_t left_start, size_t right_start)
  1178.       : left_start_(left_start),
  1179.         right_start_(right_start),
  1180.         adds_(),
  1181.         removes_(),
  1182.         common_() {}
  1183.  
  1184.   void PushLine(char edit, const char* line) {
  1185.     switch (edit) {
  1186.       case ' ':
  1187.         ++common_;
  1188.         FlushEdits();
  1189.         hunk_.push_back(std::make_pair(' ', line));
  1190.         break;
  1191.       case '-':
  1192.         ++removes_;
  1193.         hunk_removes_.push_back(std::make_pair('-', line));
  1194.         break;
  1195.       case '+':
  1196.         ++adds_;
  1197.         hunk_adds_.push_back(std::make_pair('+', line));
  1198.         break;
  1199.     }
  1200.   }
  1201.  
  1202.   void PrintTo(std::ostream* os) {
  1203.     PrintHeader(os);
  1204.     FlushEdits();
  1205.     for (std::list<std::pair<char, const char*> >::const_iterator it =
  1206.              hunk_.begin();
  1207.          it != hunk_.end(); ++it) {
  1208.       *os << it->first << it->second << "\n";
  1209.     }
  1210.   }
  1211.  
  1212.   bool has_edits() const { return adds_ || removes_; }
  1213.  
  1214.  private:
  1215.   void FlushEdits() {
  1216.     hunk_.splice(hunk_.end(), hunk_removes_);
  1217.     hunk_.splice(hunk_.end(), hunk_adds_);
  1218.   }
  1219.  
  1220.   // Print a unified diff header for one hunk.
  1221.   // The format is
  1222.   //   "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
  1223.   // where the left/right parts are omitted if unnecessary.
  1224.   void PrintHeader(std::ostream* ss) const {
  1225.     *ss << "@@ ";
  1226.     if (removes_) {
  1227.       *ss << "-" << left_start_ << "," << (removes_ + common_);
  1228.     }
  1229.     if (removes_ && adds_) {
  1230.       *ss << " ";
  1231.     }
  1232.     if (adds_) {
  1233.       *ss << "+" << right_start_ << "," << (adds_ + common_);
  1234.     }
  1235.     *ss << " @@\n";
  1236.   }
  1237.  
  1238.   size_t left_start_, right_start_;
  1239.   size_t adds_, removes_, common_;
  1240.   std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
  1241. };
  1242.  
  1243. }  // namespace
  1244.  
  1245. // Create a list of diff hunks in Unified diff format.
  1246. // Each hunk has a header generated by PrintHeader above plus a body with
  1247. // lines prefixed with ' ' for no change, '-' for deletion and '+' for
  1248. // addition.
  1249. // 'context' represents the desired unchanged prefix/suffix around the diff.
  1250. // If two hunks are close enough that their contexts overlap, then they are
  1251. // joined into one hunk.
  1252. std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  1253.                               const std::vector<std::string>& right,
  1254.                               size_t context) {
  1255.   const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
  1256.  
  1257.   size_t l_i = 0, r_i = 0, edit_i = 0;
  1258.   std::stringstream ss;
  1259.   while (edit_i < edits.size()) {
  1260.     // Find first edit.
  1261.     while (edit_i < edits.size() && edits[edit_i] == kMatch) {
  1262.       ++l_i;
  1263.       ++r_i;
  1264.       ++edit_i;
  1265.     }
  1266.  
  1267.     // Find the first line to include in the hunk.
  1268.     const size_t prefix_context = std::min(l_i, context);
  1269.     Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
  1270.     for (size_t i = prefix_context; i > 0; --i) {
  1271.       hunk.PushLine(' ', left[l_i - i].c_str());
  1272.     }
  1273.  
  1274.     // Iterate the edits until we found enough suffix for the hunk or the input
  1275.     // is over.
  1276.     size_t n_suffix = 0;
  1277.     for (; edit_i < edits.size(); ++edit_i) {
  1278.       if (n_suffix >= context) {
  1279.         // Continue only if the next hunk is very close.
  1280.         std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
  1281.         while (it != edits.end() && *it == kMatch) ++it;
  1282.         if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
  1283.           // There is no next edit or it is too far away.
  1284.           break;
  1285.         }
  1286.       }
  1287.  
  1288.       EditType edit = edits[edit_i];
  1289.       // Reset count when a non match is found.
  1290.       n_suffix = edit == kMatch ? n_suffix + 1 : 0;
  1291.  
  1292.       if (edit == kMatch || edit == kRemove || edit == kReplace) {
  1293.         hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
  1294.       }
  1295.       if (edit == kAdd || edit == kReplace) {
  1296.         hunk.PushLine('+', right[r_i].c_str());
  1297.       }
  1298.  
  1299.       // Advance indices, depending on edit type.
  1300.       l_i += edit != kAdd;
  1301.       r_i += edit != kRemove;
  1302.     }
  1303.  
  1304.     if (!hunk.has_edits()) {
  1305.       // We are done. We don't want this hunk.
  1306.       break;
  1307.     }
  1308.  
  1309.     hunk.PrintTo(&ss);
  1310.   }
  1311.   return ss.str();
  1312. }
  1313.  
  1314. }  // namespace edit_distance
  1315.  
  1316. namespace {
  1317.  
  1318. // The string representation of the values received in EqFailure() are already
  1319. // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
  1320. // characters the same.
  1321. std::vector<std::string> SplitEscapedString(const std::string& str) {
  1322.   std::vector<std::string> lines;
  1323.   size_t start = 0, end = str.size();
  1324.   if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
  1325.     ++start;
  1326.     --end;
  1327.   }
  1328.   bool escaped = false;
  1329.   for (size_t i = start; i + 1 < end; ++i) {
  1330.     if (escaped) {
  1331.       escaped = false;
  1332.       if (str[i] == 'n') {
  1333.         lines.push_back(str.substr(start, i - start - 1));
  1334.         start = i + 1;
  1335.       }
  1336.     } else {
  1337.       escaped = str[i] == '\\';
  1338.     }
  1339.   }
  1340.   lines.push_back(str.substr(start, end - start));
  1341.   return lines;
  1342. }
  1343.  
  1344. }  // namespace
  1345.  
  1346. // Constructs and returns the message for an equality assertion
  1347. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  1348. //
  1349. // The first four parameters are the expressions used in the assertion
  1350. // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
  1351. // where foo is 5 and bar is 6, we have:
  1352. //
  1353. //   lhs_expression: "foo"
  1354. //   rhs_expression: "bar"
  1355. //   lhs_value:      "5"
  1356. //   rhs_value:      "6"
  1357. //
  1358. // The ignoring_case parameter is true iff the assertion is a
  1359. // *_STRCASEEQ*.  When it's true, the string "Ignoring case" will
  1360. // be inserted into the message.
  1361. AssertionResult EqFailure(const char* lhs_expression,
  1362.                           const char* rhs_expression,
  1363.                           const std::string& lhs_value,
  1364.                           const std::string& rhs_value,
  1365.                           bool ignoring_case) {
  1366.   Message msg;
  1367.   msg << "Expected equality of these values:";
  1368.   msg << "\n  " << lhs_expression;
  1369.   if (lhs_value != lhs_expression) {
  1370.     msg << "\n    Which is: " << lhs_value;
  1371.   }
  1372.   msg << "\n  " << rhs_expression;
  1373.   if (rhs_value != rhs_expression) {
  1374.     msg << "\n    Which is: " << rhs_value;
  1375.   }
  1376.  
  1377.   if (ignoring_case) {
  1378.     msg << "\nIgnoring case";
  1379.   }
  1380.  
  1381.   if (!lhs_value.empty() && !rhs_value.empty()) {
  1382.     const std::vector<std::string> lhs_lines =
  1383.         SplitEscapedString(lhs_value);
  1384.     const std::vector<std::string> rhs_lines =
  1385.         SplitEscapedString(rhs_value);
  1386.     if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
  1387.       msg << "\nWith diff:\n"
  1388.           << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
  1389.     }
  1390.   }
  1391.  
  1392.   return AssertionFailure() << msg;
  1393. }
  1394.  
  1395. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  1396. std::string GetBoolAssertionFailureMessage(
  1397.     const AssertionResult& assertion_result,
  1398.     const char* expression_text,
  1399.     const char* actual_predicate_value,
  1400.     const char* expected_predicate_value) {
  1401.   const char* actual_message = assertion_result.message();
  1402.   Message msg;
  1403.   msg << "Value of: " << expression_text
  1404.       << "\n  Actual: " << actual_predicate_value;
  1405.   if (actual_message[0] != '\0')
  1406.     msg << " (" << actual_message << ")";
  1407.   msg << "\nExpected: " << expected_predicate_value;
  1408.   return msg.GetString();
  1409. }
  1410.  
  1411. // Helper function for implementing ASSERT_NEAR.
  1412. AssertionResult DoubleNearPredFormat(const char* expr1,
  1413.                                      const char* expr2,
  1414.                                      const char* abs_error_expr,
  1415.                                      double val1,
  1416.                                      double val2,
  1417.                                      double abs_error) {
  1418.   const double diff = fabs(val1 - val2);
  1419.   if (diff <= abs_error) return AssertionSuccess();
  1420.  
  1421.   // FIXME: do not print the value of an expression if it's
  1422.   // already a literal.
  1423.   return AssertionFailure()
  1424.       << "The difference between " << expr1 << " and " << expr2
  1425.       << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  1426.       << expr1 << " evaluates to " << val1 << ",\n"
  1427.       << expr2 << " evaluates to " << val2 << ", and\n"
  1428.       << abs_error_expr << " evaluates to " << abs_error << ".";
  1429. }
  1430.  
  1431.  
  1432. // Helper template for implementing FloatLE() and DoubleLE().
  1433. template <typename RawType>
  1434. AssertionResult FloatingPointLE(const char* expr1,
  1435.                                 const char* expr2,
  1436.                                 RawType val1,
  1437.                                 RawType val2) {
  1438.   // Returns success if val1 is less than val2,
  1439.   if (val1 < val2) {
  1440.     return AssertionSuccess();
  1441.   }
  1442.  
  1443.   // or if val1 is almost equal to val2.
  1444.   const FloatingPoint<RawType> lhs(val1), rhs(val2);
  1445.   if (lhs.AlmostEquals(rhs)) {
  1446.     return AssertionSuccess();
  1447.   }
  1448.  
  1449.   // Note that the above two checks will both fail if either val1 or
  1450.   // val2 is NaN, as the IEEE floating-point standard requires that
  1451.   // any predicate involving a NaN must return false.
  1452.  
  1453.   ::std::stringstream val1_ss;
  1454.   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  1455.           << val1;
  1456.  
  1457.   ::std::stringstream val2_ss;
  1458.   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  1459.           << val2;
  1460.  
  1461.   return AssertionFailure()
  1462.       << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  1463.       << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
  1464.       << StringStreamToString(&val2_ss);
  1465. }
  1466.  
  1467. }  // namespace internal
  1468.  
  1469. // Asserts that val1 is less than, or almost equal to, val2.  Fails
  1470. // otherwise.  In particular, it fails if either val1 or val2 is NaN.
  1471. AssertionResult FloatLE(const char* expr1, const char* expr2,
  1472.                         float val1, float val2) {
  1473.   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  1474. }
  1475.  
  1476. // Asserts that val1 is less than, or almost equal to, val2.  Fails
  1477. // otherwise.  In particular, it fails if either val1 or val2 is NaN.
  1478. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  1479.                          double val1, double val2) {
  1480.   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  1481. }
  1482.  
  1483. namespace internal {
  1484.  
  1485. // The helper function for {ASSERT|EXPECT}_EQ with int or enum
  1486. // arguments.
  1487. AssertionResult CmpHelperEQ(const char* lhs_expression,
  1488.                             const char* rhs_expression,
  1489.                             BiggestInt lhs,
  1490.                             BiggestInt rhs) {
  1491.   if (lhs == rhs) {
  1492.     return AssertionSuccess();
  1493.   }
  1494.  
  1495.   return EqFailure(lhs_expression,
  1496.                    rhs_expression,
  1497.                    FormatForComparisonFailureMessage(lhs, rhs),
  1498.                    FormatForComparisonFailureMessage(rhs, lhs),
  1499.                    false);
  1500. }
  1501.  
  1502. // A macro for implementing the helper functions needed to implement
  1503. // ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
  1504. // just to avoid copy-and-paste of similar code.
  1505. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  1506. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  1507.                                    BiggestInt val1, BiggestInt val2) {\
  1508.   if (val1 op val2) {\
  1509.     return AssertionSuccess();\
  1510.   } else {\
  1511.     return AssertionFailure() \
  1512.         << "Expected: (" << expr1 << ") " #op " (" << expr2\
  1513.         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
  1514.         << " vs " << FormatForComparisonFailureMessage(val2, val1);\
  1515.   }\
  1516. }
  1517.  
  1518. // Implements the helper function for {ASSERT|EXPECT}_NE with int or
  1519. // enum arguments.
  1520. GTEST_IMPL_CMP_HELPER_(NE, !=)
  1521. // Implements the helper function for {ASSERT|EXPECT}_LE with int or
  1522. // enum arguments.
  1523. GTEST_IMPL_CMP_HELPER_(LE, <=)
  1524. // Implements the helper function for {ASSERT|EXPECT}_LT with int or
  1525. // enum arguments.
  1526. GTEST_IMPL_CMP_HELPER_(LT, < )
  1527. // Implements the helper function for {ASSERT|EXPECT}_GE with int or
  1528. // enum arguments.
  1529. GTEST_IMPL_CMP_HELPER_(GE, >=)
  1530. // Implements the helper function for {ASSERT|EXPECT}_GT with int or
  1531. // enum arguments.
  1532. GTEST_IMPL_CMP_HELPER_(GT, > )
  1533.  
  1534. #undef GTEST_IMPL_CMP_HELPER_
  1535.  
  1536. // The helper function for {ASSERT|EXPECT}_STREQ.
  1537. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  1538.                                const char* rhs_expression,
  1539.                                const char* lhs,
  1540.                                const char* rhs) {
  1541.   if (String::CStringEquals(lhs, rhs)) {
  1542.     return AssertionSuccess();
  1543.   }
  1544.  
  1545.   return EqFailure(lhs_expression,
  1546.                    rhs_expression,
  1547.                    PrintToString(lhs),
  1548.                    PrintToString(rhs),
  1549.                    false);
  1550. }
  1551.  
  1552. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  1553. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
  1554.                                    const char* rhs_expression,
  1555.                                    const char* lhs,
  1556.                                    const char* rhs) {
  1557.   if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
  1558.     return AssertionSuccess();
  1559.   }
  1560.  
  1561.   return EqFailure(lhs_expression,
  1562.                    rhs_expression,
  1563.                    PrintToString(lhs),
  1564.                    PrintToString(rhs),
  1565.                    true);
  1566. }
  1567.  
  1568. // The helper function for {ASSERT|EXPECT}_STRNE.
  1569. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1570.                                const char* s2_expression,
  1571.                                const char* s1,
  1572.                                const char* s2) {
  1573.   if (!String::CStringEquals(s1, s2)) {
  1574.     return AssertionSuccess();
  1575.   } else {
  1576.     return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  1577.                               << s2_expression << "), actual: \""
  1578.                               << s1 << "\" vs \"" << s2 << "\"";
  1579.   }
  1580. }
  1581.  
  1582. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  1583. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  1584.                                    const char* s2_expression,
  1585.                                    const char* s1,
  1586.                                    const char* s2) {
  1587.   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  1588.     return AssertionSuccess();
  1589.   } else {
  1590.     return AssertionFailure()
  1591.         << "Expected: (" << s1_expression << ") != ("
  1592.         << s2_expression << ") (ignoring case), actual: \""
  1593.         << s1 << "\" vs \"" << s2 << "\"";
  1594.   }
  1595. }
  1596.  
  1597. }  // namespace internal
  1598.  
  1599. namespace {
  1600.  
  1601. // Helper functions for implementing IsSubString() and IsNotSubstring().
  1602.  
  1603. // This group of overloaded functions return true iff needle is a
  1604. // substring of haystack.  NULL is considered a substring of itself
  1605. // only.
  1606.  
  1607. bool IsSubstringPred(const char* needle, const char* haystack) {
  1608.   if (needle == NULL || haystack == NULL)
  1609.     return needle == haystack;
  1610.  
  1611.   return strstr(haystack, needle) != NULL;
  1612. }
  1613.  
  1614. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  1615.   if (needle == NULL || haystack == NULL)
  1616.     return needle == haystack;
  1617.  
  1618.   return wcsstr(haystack, needle) != NULL;
  1619. }
  1620.  
  1621. // StringType here can be either ::std::string or ::std::wstring.
  1622. template <typename StringType>
  1623. bool IsSubstringPred(const StringType& needle,
  1624.                      const StringType& haystack) {
  1625.   return haystack.find(needle) != StringType::npos;
  1626. }
  1627.  
  1628. // This function implements either IsSubstring() or IsNotSubstring(),
  1629. // depending on the value of the expected_to_be_substring parameter.
  1630. // StringType here can be const char*, const wchar_t*, ::std::string,
  1631. // or ::std::wstring.
  1632. template <typename StringType>
  1633. AssertionResult IsSubstringImpl(
  1634.     bool expected_to_be_substring,
  1635.     const char* needle_expr, const char* haystack_expr,
  1636.     const StringType& needle, const StringType& haystack) {
  1637.   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  1638.     return AssertionSuccess();
  1639.  
  1640.   const bool is_wide_string = sizeof(needle[0]) > 1;
  1641.   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  1642.   return AssertionFailure()
  1643.       << "Value of: " << needle_expr << "\n"
  1644.       << "  Actual: " << begin_string_quote << needle << "\"\n"
  1645.       << "Expected: " << (expected_to_be_substring ? "" : "not ")
  1646.       << "a substring of " << haystack_expr << "\n"
  1647.       << "Which is: " << begin_string_quote << haystack << "\"";
  1648. }
  1649.  
  1650. }  // namespace
  1651.  
  1652. // IsSubstring() and IsNotSubstring() check whether needle is a
  1653. // substring of haystack (NULL is considered a substring of itself
  1654. // only), and return an appropriate error message when they fail.
  1655.  
  1656. AssertionResult IsSubstring(
  1657.     const char* needle_expr, const char* haystack_expr,
  1658.     const char* needle, const char* haystack) {
  1659.   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1660. }
  1661.  
  1662. AssertionResult IsSubstring(
  1663.     const char* needle_expr, const char* haystack_expr,
  1664.     const wchar_t* needle, const wchar_t* haystack) {
  1665.   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1666. }
  1667.  
  1668. AssertionResult IsNotSubstring(
  1669.     const char* needle_expr, const char* haystack_expr,
  1670.     const char* needle, const char* haystack) {
  1671.   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1672. }
  1673.  
  1674. AssertionResult IsNotSubstring(
  1675.     const char* needle_expr, const char* haystack_expr,
  1676.     const wchar_t* needle, const wchar_t* haystack) {
  1677.   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1678. }
  1679.  
  1680. AssertionResult IsSubstring(
  1681.     const char* needle_expr, const char* haystack_expr,
  1682.     const ::std::string& needle, const ::std::string& haystack) {
  1683.   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1684. }
  1685.  
  1686. AssertionResult IsNotSubstring(
  1687.     const char* needle_expr, const char* haystack_expr,
  1688.     const ::std::string& needle, const ::std::string& haystack) {
  1689.   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1690. }
  1691.  
  1692. #if GTEST_HAS_STD_WSTRING
  1693. AssertionResult IsSubstring(
  1694.     const char* needle_expr, const char* haystack_expr,
  1695.     const ::std::wstring& needle, const ::std::wstring& haystack) {
  1696.   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1697. }
  1698.  
  1699. AssertionResult IsNotSubstring(
  1700.     const char* needle_expr, const char* haystack_expr,
  1701.     const ::std::wstring& needle, const ::std::wstring& haystack) {
  1702.   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1703. }
  1704. #endif  // GTEST_HAS_STD_WSTRING
  1705.  
  1706. namespace internal {
  1707.  
  1708. #if GTEST_OS_WINDOWS
  1709.  
  1710. namespace {
  1711.  
  1712. // Helper function for IsHRESULT{SuccessFailure} predicates
  1713. AssertionResult HRESULTFailureHelper(const char* expr,
  1714.                                      const char* expected,
  1715.                                      long hr) {  // NOLINT
  1716. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
  1717.  
  1718.   // Windows CE doesn't support FormatMessage.
  1719.   const char error_text[] = "";
  1720.  
  1721. # else
  1722.  
  1723.   // Looks up the human-readable system message for the HRESULT code
  1724.   // and since we're not passing any params to FormatMessage, we don't
  1725.   // want inserts expanded.
  1726.   const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  1727.                        FORMAT_MESSAGE_IGNORE_INSERTS;
  1728.   const DWORD kBufSize = 4096;
  1729.   // Gets the system's human readable message string for this HRESULT.
  1730.   char error_text[kBufSize] = { '\0' };
  1731.   DWORD message_length = ::FormatMessageA(kFlags,
  1732.                                           0,  // no source, we're asking system
  1733.                                           hr,  // the error
  1734.                                           0,  // no line width restrictions
  1735.                                           error_text,  // output buffer
  1736.                                           kBufSize,  // buf size
  1737.                                           NULL);  // no arguments for inserts
  1738.   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
  1739.   for (; message_length && IsSpace(error_text[message_length - 1]);
  1740.           --message_length) {
  1741.     error_text[message_length - 1] = '\0';
  1742.   }
  1743.  
  1744. # endif  // GTEST_OS_WINDOWS_MOBILE
  1745.  
  1746.   const std::string error_hex("0x" + String::FormatHexInt(hr));
  1747.   return ::testing::AssertionFailure()
  1748.       << "Expected: " << expr << " " << expected << ".\n"
  1749.       << "  Actual: " << error_hex << " " << error_text << "\n";
  1750. }
  1751.  
  1752. }  // namespace
  1753.  
  1754. AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
  1755.   if (SUCCEEDED(hr)) {
  1756.     return AssertionSuccess();
  1757.   }
  1758.   return HRESULTFailureHelper(expr, "succeeds", hr);
  1759. }
  1760.  
  1761. AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
  1762.   if (FAILED(hr)) {
  1763.     return AssertionSuccess();
  1764.   }
  1765.   return HRESULTFailureHelper(expr, "fails", hr);
  1766. }
  1767.  
  1768. #endif  // GTEST_OS_WINDOWS
  1769.  
  1770. // Utility functions for encoding Unicode text (wide strings) in
  1771. // UTF-8.
  1772.  
  1773. // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
  1774. // like this:
  1775. //
  1776. // Code-point length   Encoding
  1777. //   0 -  7 bits       0xxxxxxx
  1778. //   8 - 11 bits       110xxxxx 10xxxxxx
  1779. //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
  1780. //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1781.  
  1782. // The maximum code-point a one-byte UTF-8 sequence can represent.
  1783. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
  1784.  
  1785. // The maximum code-point a two-byte UTF-8 sequence can represent.
  1786. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
  1787.  
  1788. // The maximum code-point a three-byte UTF-8 sequence can represent.
  1789. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
  1790.  
  1791. // The maximum code-point a four-byte UTF-8 sequence can represent.
  1792. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
  1793.  
  1794. // Chops off the n lowest bits from a bit pattern.  Returns the n
  1795. // lowest bits.  As a side effect, the original bit pattern will be
  1796. // shifted to the right by n bits.
  1797. inline UInt32 ChopLowBits(UInt32* bits, int n) {
  1798.   const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
  1799.   *bits >>= n;
  1800.   return low_bits;
  1801. }
  1802.  
  1803. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  1804. // code_point parameter is of type UInt32 because wchar_t may not be
  1805. // wide enough to contain a code point.
  1806. // If the code_point is not a valid Unicode code point
  1807. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  1808. // to "(Invalid Unicode 0xXXXXXXXX)".
  1809. std::string CodePointToUtf8(UInt32 code_point) {
  1810.   if (code_point > kMaxCodePoint4) {
  1811.     return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
  1812.   }
  1813.  
  1814.   char str[5];  // Big enough for the largest valid code point.
  1815.   if (code_point <= kMaxCodePoint1) {
  1816.     str[1] = '\0';
  1817.     str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
  1818.   } else if (code_point <= kMaxCodePoint2) {
  1819.     str[2] = '\0';
  1820.     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1821.     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
  1822.   } else if (code_point <= kMaxCodePoint3) {
  1823.     str[3] = '\0';
  1824.     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1825.     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1826.     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
  1827.   } else {  // code_point <= kMaxCodePoint4
  1828.     str[4] = '\0';
  1829.     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1830.     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1831.     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1832.     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
  1833.   }
  1834.   return str;
  1835. }
  1836.  
  1837. // The following two functions only make sense if the system
  1838. // uses UTF-16 for wide string encoding. All supported systems
  1839. // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
  1840.  
  1841. // Determines if the arguments constitute UTF-16 surrogate pair
  1842. // and thus should be combined into a single Unicode code point
  1843. // using CreateCodePointFromUtf16SurrogatePair.
  1844. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  1845.   return sizeof(wchar_t) == 2 &&
  1846.       (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  1847. }
  1848.  
  1849. // Creates a Unicode code point from UTF16 surrogate pair.
  1850. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  1851.                                                     wchar_t second) {
  1852.   const UInt32 mask = (1 << 10) - 1;
  1853.   return (sizeof(wchar_t) == 2) ?
  1854.       (((first & mask) << 10) | (second & mask)) + 0x10000 :
  1855.       // This function should not be called when the condition is
  1856.       // false, but we provide a sensible default in case it is.
  1857.       static_cast<UInt32>(first);
  1858. }
  1859.  
  1860. // Converts a wide string to a narrow string in UTF-8 encoding.
  1861. // The wide string is assumed to have the following encoding:
  1862. //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  1863. //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  1864. // Parameter str points to a null-terminated wide string.
  1865. // Parameter num_chars may additionally limit the number
  1866. // of wchar_t characters processed. -1 is used when the entire string
  1867. // should be processed.
  1868. // If the string contains code points that are not valid Unicode code points
  1869. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  1870. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  1871. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  1872. // will be encoded as individual Unicode characters from Basic Normal Plane.
  1873. std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
  1874.   if (num_chars == -1)
  1875.     num_chars = static_cast<int>(wcslen(str));
  1876.  
  1877.   ::std::stringstream stream;
  1878.   for (int i = 0; i < num_chars; ++i) {
  1879.     UInt32 unicode_code_point;
  1880.  
  1881.     if (str[i] == L'\0') {
  1882.       break;
  1883.     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  1884.       unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  1885.                                                                  str[i + 1]);
  1886.       i++;
  1887.     } else {
  1888.       unicode_code_point = static_cast<UInt32>(str[i]);
  1889.     }
  1890.  
  1891.     stream << CodePointToUtf8(unicode_code_point);
  1892.   }
  1893.   return StringStreamToString(&stream);
  1894. }
  1895.  
  1896. // Converts a wide C string to an std::string using the UTF-8 encoding.
  1897. // NULL will be converted to "(null)".
  1898. std::string String::ShowWideCString(const wchar_t * wide_c_str) {
  1899.   if (wide_c_str == NULL)  return "(null)";
  1900.  
  1901.   return internal::WideStringToUtf8(wide_c_str, -1);
  1902. }
  1903.  
  1904. // Compares two wide C strings.  Returns true iff they have the same
  1905. // content.
  1906. //
  1907. // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
  1908. // C string is considered different to any non-NULL C string,
  1909. // including the empty string.
  1910. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  1911.   if (lhs == NULL) return rhs == NULL;
  1912.  
  1913.   if (rhs == NULL) return false;
  1914.  
  1915.   return wcscmp(lhs, rhs) == 0;
  1916. }
  1917.  
  1918. // Helper function for *_STREQ on wide strings.
  1919. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  1920.                                const char* rhs_expression,
  1921.                                const wchar_t* lhs,
  1922.                                const wchar_t* rhs) {
  1923.   if (String::WideCStringEquals(lhs, rhs)) {
  1924.     return AssertionSuccess();
  1925.   }
  1926.  
  1927.   return EqFailure(lhs_expression,
  1928.                    rhs_expression,
  1929.                    PrintToString(lhs),
  1930.                    PrintToString(rhs),
  1931.                    false);
  1932. }
  1933.  
  1934. // Helper function for *_STRNE on wide strings.
  1935. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1936.                                const char* s2_expression,
  1937.                                const wchar_t* s1,
  1938.                                const wchar_t* s2) {
  1939.   if (!String::WideCStringEquals(s1, s2)) {
  1940.     return AssertionSuccess();
  1941.   }
  1942.  
  1943.   return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  1944.                             << s2_expression << "), actual: "
  1945.                             << PrintToString(s1)
  1946.                             << " vs " << PrintToString(s2);
  1947. }
  1948.  
  1949. // Compares two C strings, ignoring case.  Returns true iff they have
  1950. // the same content.
  1951. //
  1952. // Unlike strcasecmp(), this function can handle NULL argument(s).  A
  1953. // NULL C string is considered different to any non-NULL C string,
  1954. // including the empty string.
  1955. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  1956.   if (lhs == NULL)
  1957.     return rhs == NULL;
  1958.   if (rhs == NULL)
  1959.     return false;
  1960.   return posix::StrCaseCmp(lhs, rhs) == 0;
  1961. }
  1962.  
  1963.   // Compares two wide C strings, ignoring case.  Returns true iff they
  1964.   // have the same content.
  1965.   //
  1966.   // Unlike wcscasecmp(), this function can handle NULL argument(s).
  1967.   // A NULL C string is considered different to any non-NULL wide C string,
  1968.   // including the empty string.
  1969.   // NB: The implementations on different platforms slightly differ.
  1970.   // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  1971.   // environment variable. On GNU platform this method uses wcscasecmp
  1972.   // which compares according to LC_CTYPE category of the current locale.
  1973.   // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  1974.   // current locale.
  1975. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  1976.                                               const wchar_t* rhs) {
  1977.   if (lhs == NULL) return rhs == NULL;
  1978.  
  1979.   if (rhs == NULL) return false;
  1980.  
  1981. #if GTEST_OS_WINDOWS
  1982.   return _wcsicmp(lhs, rhs) == 0;
  1983. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  1984.   return wcscasecmp(lhs, rhs) == 0;
  1985. #else
  1986.   // Android, Mac OS X and Cygwin don't define wcscasecmp.
  1987.   // Other unknown OSes may not define it either.
  1988.   wint_t left, right;
  1989.   do {
  1990.     left = towlower(*lhs++);
  1991.     right = towlower(*rhs++);
  1992.   } while (left && left == right);
  1993.   return left == right;
  1994. #endif  // OS selector
  1995. }
  1996.  
  1997. // Returns true iff str ends with the given suffix, ignoring case.
  1998. // Any string is considered to end with an empty suffix.
  1999. bool String::EndsWithCaseInsensitive(
  2000.     const std::string& str, const std::string& suffix) {
  2001.   const size_t str_len = str.length();
  2002.   const size_t suffix_len = suffix.length();
  2003.   return (str_len >= suffix_len) &&
  2004.          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
  2005.                                       suffix.c_str());
  2006. }
  2007.  
  2008. // Formats an int value as "%02d".
  2009. std::string String::FormatIntWidth2(int value) {
  2010.   std::stringstream ss;
  2011.   ss << std::setfill('0') << std::setw(2) << value;
  2012.   return ss.str();
  2013. }
  2014.  
  2015. // Formats an int value as "%X".
  2016. std::string String::FormatHexInt(int value) {
  2017.   std::stringstream ss;
  2018.   ss << std::hex << std::uppercase << value;
  2019.   return ss.str();
  2020. }
  2021.  
  2022. // Formats a byte as "%02X".
  2023. std::string String::FormatByte(unsigned char value) {
  2024.   std::stringstream ss;
  2025.   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
  2026.      << static_cast<unsigned int>(value);
  2027.   return ss.str();
  2028. }
  2029.  
  2030. // Converts the buffer in a stringstream to an std::string, converting NUL
  2031. // bytes to "\\0" along the way.
  2032. std::string StringStreamToString(::std::stringstream* ss) {
  2033.   const ::std::string& str = ss->str();
  2034.   const char* const start = str.c_str();
  2035.   const char* const end = start + str.length();
  2036.  
  2037.   std::string result;
  2038.   result.reserve(2 * (end - start));
  2039.   for (const char* ch = start; ch != end; ++ch) {
  2040.     if (*ch == '\0') {
  2041.       result += "\\0";  // Replaces NUL with "\\0";
  2042.     } else {
  2043.       result += *ch;
  2044.     }
  2045.   }
  2046.  
  2047.   return result;
  2048. }
  2049.  
  2050. // Appends the user-supplied message to the Google-Test-generated message.
  2051. std::string AppendUserMessage(const std::string& gtest_msg,
  2052.                               const Message& user_msg) {
  2053.   // Appends the user message if it's non-empty.
  2054.   const std::string user_msg_string = user_msg.GetString();
  2055.   if (user_msg_string.empty()) {
  2056.     return gtest_msg;
  2057.   }
  2058.  
  2059.   return gtest_msg + "\n" + user_msg_string;
  2060. }
  2061.  
  2062. }  // namespace internal
  2063.  
  2064. // class TestResult
  2065.  
  2066. // Creates an empty TestResult.
  2067. TestResult::TestResult()
  2068.     : death_test_count_(0),
  2069.       elapsed_time_(0) {
  2070. }
  2071.  
  2072. // D'tor.
  2073. TestResult::~TestResult() {
  2074. }
  2075.  
  2076. // Returns the i-th test part result among all the results. i can
  2077. // range from 0 to total_part_count() - 1. If i is not in that range,
  2078. // aborts the program.
  2079. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  2080.   if (i < 0 || i >= total_part_count())
  2081.     internal::posix::Abort();
  2082.   return test_part_results_.at(i);
  2083. }
  2084.  
  2085. // Returns the i-th test property. i can range from 0 to
  2086. // test_property_count() - 1. If i is not in that range, aborts the
  2087. // program.
  2088. const TestProperty& TestResult::GetTestProperty(int i) const {
  2089.   if (i < 0 || i >= test_property_count())
  2090.     internal::posix::Abort();
  2091.   return test_properties_.at(i);
  2092. }
  2093.  
  2094. // Clears the test part results.
  2095. void TestResult::ClearTestPartResults() {
  2096.   test_part_results_.clear();
  2097. }
  2098.  
  2099. // Adds a test part result to the list.
  2100. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  2101.   test_part_results_.push_back(test_part_result);
  2102. }
  2103.  
  2104. // Adds a test property to the list. If a property with the same key as the
  2105. // supplied property is already represented, the value of this test_property
  2106. // replaces the old value for that key.
  2107. void TestResult::RecordProperty(const std::string& xml_element,
  2108.                                 const TestProperty& test_property) {
  2109.   if (!ValidateTestProperty(xml_element, test_property)) {
  2110.     return;
  2111.   }
  2112.   internal::MutexLock lock(&test_properites_mutex_);
  2113.   const std::vector<TestProperty>::iterator property_with_matching_key =
  2114.       std::find_if(test_properties_.begin(), test_properties_.end(),
  2115.                    internal::TestPropertyKeyIs(test_property.key()));
  2116.   if (property_with_matching_key == test_properties_.end()) {
  2117.     test_properties_.push_back(test_property);
  2118.     return;
  2119.   }
  2120.   property_with_matching_key->SetValue(test_property.value());
  2121. }
  2122.  
  2123. // The list of reserved attributes used in the <testsuites> element of XML
  2124. // output.
  2125. static const char* const kReservedTestSuitesAttributes[] = {
  2126.   "disabled",
  2127.   "errors",
  2128.   "failures",
  2129.   "name",
  2130.   "random_seed",
  2131.   "tests",
  2132.   "time",
  2133.   "timestamp"
  2134. };
  2135.  
  2136. // The list of reserved attributes used in the <testsuite> element of XML
  2137. // output.
  2138. static const char* const kReservedTestSuiteAttributes[] = {
  2139.   "disabled",
  2140.   "errors",
  2141.   "failures",
  2142.   "name",
  2143.   "tests",
  2144.   "time"
  2145. };
  2146.  
  2147. // The list of reserved attributes used in the <testcase> element of XML output.
  2148. static const char* const kReservedTestCaseAttributes[] = {
  2149.     "classname",  "name",        "status", "time",
  2150.     "type_param", "value_param", "file",   "line"};
  2151.  
  2152. template <int kSize>
  2153. std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
  2154.   return std::vector<std::string>(array, array + kSize);
  2155. }
  2156.  
  2157. static std::vector<std::string> GetReservedAttributesForElement(
  2158.     const std::string& xml_element) {
  2159.   if (xml_element == "testsuites") {
  2160.     return ArrayAsVector(kReservedTestSuitesAttributes);
  2161.   } else if (xml_element == "testsuite") {
  2162.     return ArrayAsVector(kReservedTestSuiteAttributes);
  2163.   } else if (xml_element == "testcase") {
  2164.     return ArrayAsVector(kReservedTestCaseAttributes);
  2165.   } else {
  2166.     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  2167.   }
  2168.   // This code is unreachable but some compilers may not realizes that.
  2169.   return std::vector<std::string>();
  2170. }
  2171.  
  2172. static std::string FormatWordList(const std::vector<std::string>& words) {
  2173.   Message word_list;
  2174.   for (size_t i = 0; i < words.size(); ++i) {
  2175.     if (i > 0 && words.size() > 2) {
  2176.       word_list << ", ";
  2177.     }
  2178.     if (i == words.size() - 1) {
  2179.       word_list << "and ";
  2180.     }
  2181.     word_list << "'" << words[i] << "'";
  2182.   }
  2183.   return word_list.GetString();
  2184. }
  2185.  
  2186. static bool ValidateTestPropertyName(
  2187.     const std::string& property_name,
  2188.     const std::vector<std::string>& reserved_names) {
  2189.   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
  2190.           reserved_names.end()) {
  2191.     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
  2192.                   << " (" << FormatWordList(reserved_names)
  2193.                   << " are reserved by " << GTEST_NAME_ << ")";
  2194.     return false;
  2195.   }
  2196.   return true;
  2197. }
  2198.  
  2199. // Adds a failure if the key is a reserved attribute of the element named
  2200. // xml_element.  Returns true if the property is valid.
  2201. bool TestResult::ValidateTestProperty(const std::string& xml_element,
  2202.                                       const TestProperty& test_property) {
  2203.   return ValidateTestPropertyName(test_property.key(),
  2204.                                   GetReservedAttributesForElement(xml_element));
  2205. }
  2206.  
  2207. // Clears the object.
  2208. void TestResult::Clear() {
  2209.   test_part_results_.clear();
  2210.   test_properties_.clear();
  2211.   death_test_count_ = 0;
  2212.   elapsed_time_ = 0;
  2213. }
  2214.  
  2215. // Returns true iff the test failed.
  2216. bool TestResult::Failed() const {
  2217.   for (int i = 0; i < total_part_count(); ++i) {
  2218.     if (GetTestPartResult(i).failed())
  2219.       return true;
  2220.   }
  2221.   return false;
  2222. }
  2223.  
  2224. // Returns true iff the test part fatally failed.
  2225. static bool TestPartFatallyFailed(const TestPartResult& result) {
  2226.   return result.fatally_failed();
  2227. }
  2228.  
  2229. // Returns true iff the test fatally failed.
  2230. bool TestResult::HasFatalFailure() const {
  2231.   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  2232. }
  2233.  
  2234. // Returns true iff the test part non-fatally failed.
  2235. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  2236.   return result.nonfatally_failed();
  2237. }
  2238.  
  2239. // Returns true iff the test has a non-fatal failure.
  2240. bool TestResult::HasNonfatalFailure() const {
  2241.   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  2242. }
  2243.  
  2244. // Gets the number of all test parts.  This is the sum of the number
  2245. // of successful test parts and the number of failed test parts.
  2246. int TestResult::total_part_count() const {
  2247.   return static_cast<int>(test_part_results_.size());
  2248. }
  2249.  
  2250. // Returns the number of the test properties.
  2251. int TestResult::test_property_count() const {
  2252.   return static_cast<int>(test_properties_.size());
  2253. }
  2254.  
  2255. // class Test
  2256.  
  2257. // Creates a Test object.
  2258.  
  2259. // The c'tor saves the states of all flags.
  2260. Test::Test()
  2261.     : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
  2262. }
  2263.  
  2264. // The d'tor restores the states of all flags.  The actual work is
  2265. // done by the d'tor of the gtest_flag_saver_ field, and thus not
  2266. // visible here.
  2267. Test::~Test() {
  2268. }
  2269.  
  2270. // Sets up the test fixture.
  2271. //
  2272. // A sub-class may override this.
  2273. void Test::SetUp() {
  2274. }
  2275.  
  2276. // Tears down the test fixture.
  2277. //
  2278. // A sub-class may override this.
  2279. void Test::TearDown() {
  2280. }
  2281.  
  2282. // Allows user supplied key value pairs to be recorded for later output.
  2283. void Test::RecordProperty(const std::string& key, const std::string& value) {
  2284.   UnitTest::GetInstance()->RecordProperty(key, value);
  2285. }
  2286.  
  2287. // Allows user supplied key value pairs to be recorded for later output.
  2288. void Test::RecordProperty(const std::string& key, int value) {
  2289.   Message value_message;
  2290.   value_message << value;
  2291.   RecordProperty(key, value_message.GetString().c_str());
  2292. }
  2293.  
  2294. namespace internal {
  2295.  
  2296. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  2297.                                     const std::string& message) {
  2298.   // This function is a friend of UnitTest and as such has access to
  2299.   // AddTestPartResult.
  2300.   UnitTest::GetInstance()->AddTestPartResult(
  2301.       result_type,
  2302.       NULL,  // No info about the source file where the exception occurred.
  2303.       -1,    // We have no info on which line caused the exception.
  2304.       message,
  2305.       "");   // No stack trace, either.
  2306. }
  2307.  
  2308. }  // namespace internal
  2309.  
  2310. // Google Test requires all tests in the same test case to use the same test
  2311. // fixture class.  This function checks if the current test has the
  2312. // same fixture class as the first test in the current test case.  If
  2313. // yes, it returns true; otherwise it generates a Google Test failure and
  2314. // returns false.
  2315. bool Test::HasSameFixtureClass() {
  2316.   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2317.   const TestCase* const test_case = impl->current_test_case();
  2318.  
  2319.   // Info about the first test in the current test case.
  2320.   const TestInfo* const first_test_info = test_case->test_info_list()[0];
  2321.   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  2322.   const char* const first_test_name = first_test_info->name();
  2323.  
  2324.   // Info about the current test.
  2325.   const TestInfo* const this_test_info = impl->current_test_info();
  2326.   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  2327.   const char* const this_test_name = this_test_info->name();
  2328.  
  2329.   if (this_fixture_id != first_fixture_id) {
  2330.     // Is the first test defined using TEST?
  2331.     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  2332.     // Is this test defined using TEST?
  2333.     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  2334.  
  2335.     if (first_is_TEST || this_is_TEST) {
  2336.       // Both TEST and TEST_F appear in same test case, which is incorrect.
  2337.       // Tell the user how to fix this.
  2338.  
  2339.       // Gets the name of the TEST and the name of the TEST_F.  Note
  2340.       // that first_is_TEST and this_is_TEST cannot both be true, as
  2341.       // the fixture IDs are different for the two tests.
  2342.       const char* const TEST_name =
  2343.           first_is_TEST ? first_test_name : this_test_name;
  2344.       const char* const TEST_F_name =
  2345.           first_is_TEST ? this_test_name : first_test_name;
  2346.  
  2347.       ADD_FAILURE()
  2348.           << "All tests in the same test case must use the same test fixture\n"
  2349.           << "class, so mixing TEST_F and TEST in the same test case is\n"
  2350.           << "illegal.  In test case " << this_test_info->test_case_name()
  2351.           << ",\n"
  2352.           << "test " << TEST_F_name << " is defined using TEST_F but\n"
  2353.           << "test " << TEST_name << " is defined using TEST.  You probably\n"
  2354.           << "want to change the TEST to TEST_F or move it to another test\n"
  2355.           << "case.";
  2356.     } else {
  2357.       // Two fixture classes with the same name appear in two different
  2358.       // namespaces, which is not allowed. Tell the user how to fix this.
  2359.       ADD_FAILURE()
  2360.           << "All tests in the same test case must use the same test fixture\n"
  2361.           << "class.  However, in test case "
  2362.           << this_test_info->test_case_name() << ",\n"
  2363.           << "you defined test " << first_test_name
  2364.           << " and test " << this_test_name << "\n"
  2365.           << "using two different test fixture classes.  This can happen if\n"
  2366.           << "the two classes are from different namespaces or translation\n"
  2367.           << "units and have the same name.  You should probably rename one\n"
  2368.           << "of the classes to put the tests into different test cases.";
  2369.     }
  2370.     return false;
  2371.   }
  2372.  
  2373.   return true;
  2374. }
  2375.  
  2376. #if GTEST_HAS_SEH
  2377.  
  2378. // Adds an "exception thrown" fatal failure to the current test.  This
  2379. // function returns its result via an output parameter pointer because VC++
  2380. // prohibits creation of objects with destructors on stack in functions
  2381. // using __try (see error C2712).
  2382. static std::string* FormatSehExceptionMessage(DWORD exception_code,
  2383.                                               const char* location) {
  2384.   Message message;
  2385.   message << "SEH exception with code 0x" << std::setbase(16) <<
  2386.     exception_code << std::setbase(10) << " thrown in " << location << ".";
  2387.  
  2388.   return new std::string(message.GetString());
  2389. }
  2390.  
  2391. #endif  // GTEST_HAS_SEH
  2392.  
  2393. namespace internal {
  2394.  
  2395. #if GTEST_HAS_EXCEPTIONS
  2396.  
  2397. // Adds an "exception thrown" fatal failure to the current test.
  2398. static std::string FormatCxxExceptionMessage(const char* description,
  2399.                                              const char* location) {
  2400.   Message message;
  2401.   if (description != NULL) {
  2402.     message << "C++ exception with description \"" << description << "\"";
  2403.   } else {
  2404.     message << "Unknown C++ exception";
  2405.   }
  2406.   message << " thrown in " << location << ".";
  2407.  
  2408.   return message.GetString();
  2409. }
  2410.  
  2411. static std::string PrintTestPartResultToString(
  2412.     const TestPartResult& test_part_result);
  2413.  
  2414. GoogleTestFailureException::GoogleTestFailureException(
  2415.     const TestPartResult& failure)
  2416.     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  2417.  
  2418. #endif  // GTEST_HAS_EXCEPTIONS
  2419.  
  2420. // We put these helper functions in the internal namespace as IBM's xlC
  2421. // compiler rejects the code if they were declared static.
  2422.  
  2423. // Runs the given method and handles SEH exceptions it throws, when
  2424. // SEH is supported; returns the 0-value for type Result in case of an
  2425. // SEH exception.  (Microsoft compilers cannot handle SEH and C++
  2426. // exceptions in the same function.  Therefore, we provide a separate
  2427. // wrapper function for handling SEH exceptions.)
  2428. template <class T, typename Result>
  2429. Result HandleSehExceptionsInMethodIfSupported(
  2430.     T* object, Result (T::*method)(), const char* location) {
  2431. #if GTEST_HAS_SEH
  2432.   __try {
  2433.     return (object->*method)();
  2434.   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
  2435.       GetExceptionCode())) {
  2436.     // We create the exception message on the heap because VC++ prohibits
  2437.     // creation of objects with destructors on stack in functions using __try
  2438.     // (see error C2712).
  2439.     std::string* exception_message = FormatSehExceptionMessage(
  2440.         GetExceptionCode(), location);
  2441.     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  2442.                                              *exception_message);
  2443.     delete exception_message;
  2444.     return static_cast<Result>(0);
  2445.   }
  2446. #else
  2447.   (void)location;
  2448.   return (object->*method)();
  2449. #endif  // GTEST_HAS_SEH
  2450. }
  2451.  
  2452. // Runs the given method and catches and reports C++ and/or SEH-style
  2453. // exceptions, if they are supported; returns the 0-value for type
  2454. // Result in case of an SEH exception.
  2455. template <class T, typename Result>
  2456. Result HandleExceptionsInMethodIfSupported(
  2457.     T* object, Result (T::*method)(), const char* location) {
  2458.   // NOTE: The user code can affect the way in which Google Test handles
  2459.   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  2460.   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  2461.   // after the exception is caught and either report or re-throw the
  2462.   // exception based on the flag's value:
  2463.   //
  2464.   // try {
  2465.   //   // Perform the test method.
  2466.   // } catch (...) {
  2467.   //   if (GTEST_FLAG(catch_exceptions))
  2468.   //     // Report the exception as failure.
  2469.   //   else
  2470.   //     throw;  // Re-throws the original exception.
  2471.   // }
  2472.   //
  2473.   // However, the purpose of this flag is to allow the program to drop into
  2474.   // the debugger when the exception is thrown. On most platforms, once the
  2475.   // control enters the catch block, the exception origin information is
  2476.   // lost and the debugger will stop the program at the point of the
  2477.   // re-throw in this function -- instead of at the point of the original
  2478.   // throw statement in the code under test.  For this reason, we perform
  2479.   // the check early, sacrificing the ability to affect Google Test's
  2480.   // exception handling in the method where the exception is thrown.
  2481.   if (internal::GetUnitTestImpl()->catch_exceptions()) {
  2482. #if GTEST_HAS_EXCEPTIONS
  2483.     try {
  2484.       return HandleSehExceptionsInMethodIfSupported(object, method, location);
  2485.     } catch (const AssertionException&) {  // NOLINT
  2486.       // This failure was reported already.
  2487.     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
  2488.       // This exception type can only be thrown by a failed Google
  2489.       // Test assertion with the intention of letting another testing
  2490.       // framework catch it.  Therefore we just re-throw it.
  2491.       throw;
  2492.     } catch (const std::exception& e) {  // NOLINT
  2493.       internal::ReportFailureInUnknownLocation(
  2494.           TestPartResult::kFatalFailure,
  2495.           FormatCxxExceptionMessage(e.what(), location));
  2496.     } catch (...) {  // NOLINT
  2497.       internal::ReportFailureInUnknownLocation(
  2498.           TestPartResult::kFatalFailure,
  2499.           FormatCxxExceptionMessage(NULL, location));
  2500.     }
  2501.     return static_cast<Result>(0);
  2502. #else
  2503.     return HandleSehExceptionsInMethodIfSupported(object, method, location);
  2504. #endif  // GTEST_HAS_EXCEPTIONS
  2505.   } else {
  2506.     return (object->*method)();
  2507.   }
  2508. }
  2509.  
  2510. }  // namespace internal
  2511.  
  2512. // Runs the test and updates the test result.
  2513. void Test::Run() {
  2514.   if (!HasSameFixtureClass()) return;
  2515.  
  2516.   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2517.   impl->os_stack_trace_getter()->UponLeavingGTest();
  2518.   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  2519.   // We will run the test only if SetUp() was successful.
  2520.   if (!HasFatalFailure()) {
  2521.     impl->os_stack_trace_getter()->UponLeavingGTest();
  2522.     internal::HandleExceptionsInMethodIfSupported(
  2523.         this, &Test::TestBody, "the test body");
  2524.   }
  2525.  
  2526.   // However, we want to clean up as much as possible.  Hence we will
  2527.   // always call TearDown(), even if SetUp() or the test body has
  2528.   // failed.
  2529.   impl->os_stack_trace_getter()->UponLeavingGTest();
  2530.   internal::HandleExceptionsInMethodIfSupported(
  2531.       this, &Test::TearDown, "TearDown()");
  2532. }
  2533.  
  2534. // Returns true iff the current test has a fatal failure.
  2535. bool Test::HasFatalFailure() {
  2536.   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  2537. }
  2538.  
  2539. // Returns true iff the current test has a non-fatal failure.
  2540. bool Test::HasNonfatalFailure() {
  2541.   return internal::GetUnitTestImpl()->current_test_result()->
  2542.       HasNonfatalFailure();
  2543. }
  2544.  
  2545. // class TestInfo
  2546.  
  2547. // Constructs a TestInfo object. It assumes ownership of the test factory
  2548. // object.
  2549. TestInfo::TestInfo(const std::string& a_test_case_name,
  2550.                    const std::string& a_name,
  2551.                    const char* a_type_param,
  2552.                    const char* a_value_param,
  2553.                    internal::CodeLocation a_code_location,
  2554.                    internal::TypeId fixture_class_id,
  2555.                    internal::TestFactoryBase* factory)
  2556.     : test_case_name_(a_test_case_name),
  2557.       name_(a_name),
  2558.       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  2559.       value_param_(a_value_param ? new std::string(a_value_param) : NULL),
  2560.       location_(a_code_location),
  2561.       fixture_class_id_(fixture_class_id),
  2562.       should_run_(false),
  2563.       is_disabled_(false),
  2564.       matches_filter_(false),
  2565.       factory_(factory),
  2566.       result_() {}
  2567.  
  2568. // Destructs a TestInfo object.
  2569. TestInfo::~TestInfo() { delete factory_; }
  2570.  
  2571. namespace internal {
  2572.  
  2573. // Creates a new TestInfo object and registers it with Google Test;
  2574. // returns the created object.
  2575. //
  2576. // Arguments:
  2577. //
  2578. //   test_case_name:   name of the test case
  2579. //   name:             name of the test
  2580. //   type_param:       the name of the test's type parameter, or NULL if
  2581. //                     this is not a typed or a type-parameterized test.
  2582. //   value_param:      text representation of the test's value parameter,
  2583. //                     or NULL if this is not a value-parameterized test.
  2584. //   code_location:    code location where the test is defined
  2585. //   fixture_class_id: ID of the test fixture class
  2586. //   set_up_tc:        pointer to the function that sets up the test case
  2587. //   tear_down_tc:     pointer to the function that tears down the test case
  2588. //   factory:          pointer to the factory that creates a test object.
  2589. //                     The newly created TestInfo instance will assume
  2590. //                     ownership of the factory object.
  2591. TestInfo* MakeAndRegisterTestInfo(
  2592.     const char* test_case_name,
  2593.     const char* name,
  2594.     const char* type_param,
  2595.     const char* value_param,
  2596.     CodeLocation code_location,
  2597.     TypeId fixture_class_id,
  2598.     SetUpTestCaseFunc set_up_tc,
  2599.     TearDownTestCaseFunc tear_down_tc,
  2600.     TestFactoryBase* factory) {
  2601.   TestInfo* const test_info =
  2602.       new TestInfo(test_case_name, name, type_param, value_param,
  2603.                    code_location, fixture_class_id, factory);
  2604.   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  2605.   return test_info;
  2606. }
  2607.  
  2608. void ReportInvalidTestCaseType(const char* test_case_name,
  2609.                                CodeLocation code_location) {
  2610.   Message errors;
  2611.   errors
  2612.       << "Attempted redefinition of test case " << test_case_name << ".\n"
  2613.       << "All tests in the same test case must use the same test fixture\n"
  2614.       << "class.  However, in test case " << test_case_name << ", you tried\n"
  2615.       << "to define a test using a fixture class different from the one\n"
  2616.       << "used earlier. This can happen if the two fixture classes are\n"
  2617.       << "from different namespaces and have the same name. You should\n"
  2618.       << "probably rename one of the classes to put the tests into different\n"
  2619.       << "test cases.";
  2620.  
  2621.   GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
  2622.                                           code_location.line)
  2623.                     << " " << errors.GetString();
  2624. }
  2625. }  // namespace internal
  2626.  
  2627. namespace {
  2628.  
  2629. // A predicate that checks the test name of a TestInfo against a known
  2630. // value.
  2631. //
  2632. // This is used for implementation of the TestCase class only.  We put
  2633. // it in the anonymous namespace to prevent polluting the outer
  2634. // namespace.
  2635. //
  2636. // TestNameIs is copyable.
  2637. class TestNameIs {
  2638.  public:
  2639.   // Constructor.
  2640.   //
  2641.   // TestNameIs has NO default constructor.
  2642.   explicit TestNameIs(const char* name)
  2643.       : name_(name) {}
  2644.  
  2645.   // Returns true iff the test name of test_info matches name_.
  2646.   bool operator()(const TestInfo * test_info) const {
  2647.     return test_info && test_info->name() == name_;
  2648.   }
  2649.  
  2650.  private:
  2651.   std::string name_;
  2652. };
  2653.  
  2654. }  // namespace
  2655.  
  2656. namespace internal {
  2657.  
  2658. // This method expands all parameterized tests registered with macros TEST_P
  2659. // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
  2660. // This will be done just once during the program runtime.
  2661. void UnitTestImpl::RegisterParameterizedTests() {
  2662.   if (!parameterized_tests_registered_) {
  2663.     parameterized_test_registry_.RegisterTests();
  2664.     parameterized_tests_registered_ = true;
  2665.   }
  2666. }
  2667.  
  2668. }  // namespace internal
  2669.  
  2670. // Creates the test object, runs it, records its result, and then
  2671. // deletes it.
  2672. void TestInfo::Run() {
  2673.   if (!should_run_) return;
  2674.  
  2675.   // Tells UnitTest where to store test result.
  2676.   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2677.   impl->set_current_test_info(this);
  2678.  
  2679.   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  2680.  
  2681.   // Notifies the unit test event listeners that a test is about to start.
  2682.   repeater->OnTestStart(*this);
  2683.  
  2684.   const TimeInMillis start = internal::GetTimeInMillis();
  2685.  
  2686.   impl->os_stack_trace_getter()->UponLeavingGTest();
  2687.  
  2688.   // Creates the test object.
  2689.   Test* const test = internal::HandleExceptionsInMethodIfSupported(
  2690.       factory_, &internal::TestFactoryBase::CreateTest,
  2691.       "the test fixture's constructor");
  2692.  
  2693.   // Runs the test if the constructor didn't generate a fatal failure.
  2694.   // Note that the object will not be null
  2695.   if (!Test::HasFatalFailure()) {
  2696.     // This doesn't throw as all user code that can throw are wrapped into
  2697.     // exception handling code.
  2698.     test->Run();
  2699.   }
  2700.  
  2701.     // Deletes the test object.
  2702.     impl->os_stack_trace_getter()->UponLeavingGTest();
  2703.     internal::HandleExceptionsInMethodIfSupported(
  2704.         test, &Test::DeleteSelf_, "the test fixture's destructor");
  2705.  
  2706.   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
  2707.  
  2708.   // Notifies the unit test event listener that a test has just finished.
  2709.   repeater->OnTestEnd(*this);
  2710.  
  2711.   // Tells UnitTest to stop associating assertion results to this
  2712.   // test.
  2713.   impl->set_current_test_info(NULL);
  2714. }
  2715.  
  2716. // class TestCase
  2717.  
  2718. // Gets the number of successful tests in this test case.
  2719. int TestCase::successful_test_count() const {
  2720.   return CountIf(test_info_list_, TestPassed);
  2721. }
  2722.  
  2723. // Gets the number of failed tests in this test case.
  2724. int TestCase::failed_test_count() const {
  2725.   return CountIf(test_info_list_, TestFailed);
  2726. }
  2727.  
  2728. // Gets the number of disabled tests that will be reported in the XML report.
  2729. int TestCase::reportable_disabled_test_count() const {
  2730.   return CountIf(test_info_list_, TestReportableDisabled);
  2731. }
  2732.  
  2733. // Gets the number of disabled tests in this test case.
  2734. int TestCase::disabled_test_count() const {
  2735.   return CountIf(test_info_list_, TestDisabled);
  2736. }
  2737.  
  2738. // Gets the number of tests to be printed in the XML report.
  2739. int TestCase::reportable_test_count() const {
  2740.   return CountIf(test_info_list_, TestReportable);
  2741. }
  2742.  
  2743. // Get the number of tests in this test case that should run.
  2744. int TestCase::test_to_run_count() const {
  2745.   return CountIf(test_info_list_, ShouldRunTest);
  2746. }
  2747.  
  2748. // Gets the number of all tests.
  2749. int TestCase::total_test_count() const {
  2750.   return static_cast<int>(test_info_list_.size());
  2751. }
  2752.  
  2753. // Creates a TestCase with the given name.
  2754. //
  2755. // Arguments:
  2756. //
  2757. //   name:         name of the test case
  2758. //   a_type_param: the name of the test case's type parameter, or NULL if
  2759. //                 this is not a typed or a type-parameterized test case.
  2760. //   set_up_tc:    pointer to the function that sets up the test case
  2761. //   tear_down_tc: pointer to the function that tears down the test case
  2762. TestCase::TestCase(const char* a_name, const char* a_type_param,
  2763.                    Test::SetUpTestCaseFunc set_up_tc,
  2764.                    Test::TearDownTestCaseFunc tear_down_tc)
  2765.     : name_(a_name),
  2766.       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  2767.       set_up_tc_(set_up_tc),
  2768.       tear_down_tc_(tear_down_tc),
  2769.       should_run_(false),
  2770.       elapsed_time_(0) {
  2771. }
  2772.  
  2773. // Destructor of TestCase.
  2774. TestCase::~TestCase() {
  2775.   // Deletes every Test in the collection.
  2776.   ForEach(test_info_list_, internal::Delete<TestInfo>);
  2777. }
  2778.  
  2779. // Returns the i-th test among all the tests. i can range from 0 to
  2780. // total_test_count() - 1. If i is not in that range, returns NULL.
  2781. const TestInfo* TestCase::GetTestInfo(int i) const {
  2782.   const int index = GetElementOr(test_indices_, i, -1);
  2783.   return index < 0 ? NULL : test_info_list_[index];
  2784. }
  2785.  
  2786. // Returns the i-th test among all the tests. i can range from 0 to
  2787. // total_test_count() - 1. If i is not in that range, returns NULL.
  2788. TestInfo* TestCase::GetMutableTestInfo(int i) {
  2789.   const int index = GetElementOr(test_indices_, i, -1);
  2790.   return index < 0 ? NULL : test_info_list_[index];
  2791. }
  2792.  
  2793. // Adds a test to this test case.  Will delete the test upon
  2794. // destruction of the TestCase object.
  2795. void TestCase::AddTestInfo(TestInfo * test_info) {
  2796.   test_info_list_.push_back(test_info);
  2797.   test_indices_.push_back(static_cast<int>(test_indices_.size()));
  2798. }
  2799.  
  2800. // Runs every test in this TestCase.
  2801. void TestCase::Run() {
  2802.   if (!should_run_) return;
  2803.  
  2804.   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2805.   impl->set_current_test_case(this);
  2806.  
  2807.   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  2808.  
  2809.   repeater->OnTestCaseStart(*this);
  2810.   impl->os_stack_trace_getter()->UponLeavingGTest();
  2811.   internal::HandleExceptionsInMethodIfSupported(
  2812.       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
  2813.  
  2814.   const internal::TimeInMillis start = internal::GetTimeInMillis();
  2815.   for (int i = 0; i < total_test_count(); i++) {
  2816.     GetMutableTestInfo(i)->Run();
  2817.   }
  2818.   elapsed_time_ = internal::GetTimeInMillis() - start;
  2819.  
  2820.   impl->os_stack_trace_getter()->UponLeavingGTest();
  2821.   internal::HandleExceptionsInMethodIfSupported(
  2822.       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
  2823.  
  2824.   repeater->OnTestCaseEnd(*this);
  2825.   impl->set_current_test_case(NULL);
  2826. }
  2827.  
  2828. // Clears the results of all tests in this test case.
  2829. void TestCase::ClearResult() {
  2830.   ad_hoc_test_result_.Clear();
  2831.   ForEach(test_info_list_, TestInfo::ClearTestResult);
  2832. }
  2833.  
  2834. // Shuffles the tests in this test case.
  2835. void TestCase::ShuffleTests(internal::Random* random) {
  2836.   Shuffle(random, &test_indices_);
  2837. }
  2838.  
  2839. // Restores the test order to before the first shuffle.
  2840. void TestCase::UnshuffleTests() {
  2841.   for (size_t i = 0; i < test_indices_.size(); i++) {
  2842.     test_indices_[i] = static_cast<int>(i);
  2843.   }
  2844. }
  2845.  
  2846. // Formats a countable noun.  Depending on its quantity, either the
  2847. // singular form or the plural form is used. e.g.
  2848. //
  2849. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  2850. // FormatCountableNoun(5, "book", "books") returns "5 books".
  2851. static std::string FormatCountableNoun(int count,
  2852.                                        const char * singular_form,
  2853.                                        const char * plural_form) {
  2854.   return internal::StreamableToString(count) + " " +
  2855.       (count == 1 ? singular_form : plural_form);
  2856. }
  2857.  
  2858. // Formats the count of tests.
  2859. static std::string FormatTestCount(int test_count) {
  2860.   return FormatCountableNoun(test_count, "test", "tests");
  2861. }
  2862.  
  2863. // Formats the count of test cases.
  2864. static std::string FormatTestCaseCount(int test_case_count) {
  2865.   return FormatCountableNoun(test_case_count, "test case", "test cases");
  2866. }
  2867.  
  2868. // Converts a TestPartResult::Type enum to human-friendly string
  2869. // representation.  Both kNonFatalFailure and kFatalFailure are translated
  2870. // to "Failure", as the user usually doesn't care about the difference
  2871. // between the two when viewing the test result.
  2872. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  2873.   switch (type) {
  2874.     case TestPartResult::kSuccess:
  2875.       return "Success";
  2876.  
  2877.     case TestPartResult::kNonFatalFailure:
  2878.     case TestPartResult::kFatalFailure:
  2879. #ifdef _MSC_VER
  2880.       return "error: ";
  2881. #else
  2882.       return "Failure\n";
  2883. #endif
  2884.     default:
  2885.       return "Unknown result type";
  2886.   }
  2887. }
  2888.  
  2889. namespace internal {
  2890.  
  2891. // Prints a TestPartResult to an std::string.
  2892. static std::string PrintTestPartResultToString(
  2893.     const TestPartResult& test_part_result) {
  2894.   return (Message()
  2895.           << internal::FormatFileLocation(test_part_result.file_name(),
  2896.                                           test_part_result.line_number())
  2897.           << " " << TestPartResultTypeToString(test_part_result.type())
  2898.           << test_part_result.message()).GetString();
  2899. }
  2900.  
  2901. // Prints a TestPartResult.
  2902. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  2903.   const std::string& result =
  2904.       PrintTestPartResultToString(test_part_result);
  2905.   printf("%s\n", result.c_str());
  2906.   fflush(stdout);
  2907.   // If the test program runs in Visual Studio or a debugger, the
  2908.   // following statements add the test part result message to the Output
  2909.   // window such that the user can double-click on it to jump to the
  2910.   // corresponding source code location; otherwise they do nothing.
  2911. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2912.   // We don't call OutputDebugString*() on Windows Mobile, as printing
  2913.   // to stdout is done by OutputDebugString() there already - we don't
  2914.   // want the same message printed twice.
  2915.   ::OutputDebugStringA(result.c_str());
  2916.   ::OutputDebugStringA("\n");
  2917. #endif
  2918. }
  2919.  
  2920. // class PrettyUnitTestResultPrinter
  2921.  
  2922. enum GTestColor {
  2923.   COLOR_DEFAULT,
  2924.   COLOR_RED,
  2925.   COLOR_GREEN,
  2926.   COLOR_YELLOW
  2927. };
  2928.  
  2929. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  2930.     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  2931.  
  2932. // Returns the character attribute for the given color.
  2933. static WORD GetColorAttribute(GTestColor color) {
  2934.   switch (color) {
  2935.     case COLOR_RED:    return FOREGROUND_RED;
  2936.     case COLOR_GREEN:  return FOREGROUND_GREEN;
  2937.     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
  2938.     default:           return 0;
  2939.   }
  2940. }
  2941.  
  2942. static int GetBitOffset(WORD color_mask) {
  2943.   if (color_mask == 0) return 0;
  2944.  
  2945.   int bitOffset = 0;
  2946.   while ((color_mask & 1) == 0) {
  2947.     color_mask >>= 1;
  2948.     ++bitOffset;
  2949.   }
  2950.   return bitOffset;
  2951. }
  2952.  
  2953. static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
  2954.   // Let's reuse the BG
  2955.   static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  2956.                                       BACKGROUND_RED | BACKGROUND_INTENSITY;
  2957.   static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  2958.                                       FOREGROUND_RED | FOREGROUND_INTENSITY;
  2959.   const WORD existing_bg = old_color_attrs & background_mask;
  2960.  
  2961.   WORD new_color =
  2962.       GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
  2963.   static const int bg_bitOffset = GetBitOffset(background_mask);
  2964.   static const int fg_bitOffset = GetBitOffset(foreground_mask);
  2965.  
  2966.   if (((new_color & background_mask) >> bg_bitOffset) ==
  2967.       ((new_color & foreground_mask) >> fg_bitOffset)) {
  2968.     new_color ^= FOREGROUND_INTENSITY;  // invert intensity
  2969.   }
  2970.   return new_color;
  2971. }
  2972.  
  2973. #else
  2974.  
  2975. // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
  2976. // an invalid input.
  2977. static const char* GetAnsiColorCode(GTestColor color) {
  2978.   switch (color) {
  2979.     case COLOR_RED:     return "1";
  2980.     case COLOR_GREEN:   return "2";
  2981.     case COLOR_YELLOW:  return "3";
  2982.     default:            return NULL;
  2983.   };
  2984. }
  2985.  
  2986. #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2987.  
  2988. // Returns true iff Google Test should use colors in the output.
  2989. bool ShouldUseColor(bool stdout_is_tty) {
  2990.   const char* const gtest_color = GTEST_FLAG(color).c_str();
  2991.  
  2992.   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  2993. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  2994.     // On Windows the TERM variable is usually not set, but the
  2995.     // console there does support colors.
  2996.     return stdout_is_tty;
  2997. #else
  2998.     // On non-Windows platforms, we rely on the TERM variable.
  2999.     const char* const term = posix::GetEnv("TERM");
  3000.     const bool term_supports_color =
  3001.         String::CStringEquals(term, "xterm") ||
  3002.         String::CStringEquals(term, "xterm-color") ||
  3003.         String::CStringEquals(term, "xterm-256color") ||
  3004.         String::CStringEquals(term, "screen") ||
  3005.         String::CStringEquals(term, "screen-256color") ||
  3006.         String::CStringEquals(term, "tmux") ||
  3007.         String::CStringEquals(term, "tmux-256color") ||
  3008.         String::CStringEquals(term, "rxvt-unicode") ||
  3009.         String::CStringEquals(term, "rxvt-unicode-256color") ||
  3010.         String::CStringEquals(term, "linux") ||
  3011.         String::CStringEquals(term, "cygwin");
  3012.     return stdout_is_tty && term_supports_color;
  3013. #endif  // GTEST_OS_WINDOWS
  3014.   }
  3015.  
  3016.   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  3017.       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  3018.       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  3019.       String::CStringEquals(gtest_color, "1");
  3020.   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
  3021.   // value is neither one of these nor "auto", we treat it as "no" to
  3022.   // be conservative.
  3023. }
  3024.  
  3025. // Helpers for printing colored strings to stdout. Note that on Windows, we
  3026. // cannot simply emit special characters and have the terminal change colors.
  3027. // This routine must actually emit the characters rather than return a string
  3028. // that would be colored when printed, as can be done on Linux.
  3029. static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  3030.   va_list args;
  3031.   va_start(args, fmt);
  3032.  
  3033. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
  3034.     GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
  3035.   const bool use_color = AlwaysFalse();
  3036. #else
  3037.   static const bool in_color_mode =
  3038.       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  3039.   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
  3040. #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  3041.   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
  3042.  
  3043.   if (!use_color) {
  3044.     vprintf(fmt, args);
  3045.     va_end(args);
  3046.     return;
  3047.   }
  3048.  
  3049. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  3050.     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  3051.   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  3052.  
  3053.   // Gets the current text color.
  3054.   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  3055.   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  3056.   const WORD old_color_attrs = buffer_info.wAttributes;
  3057.   const WORD new_color = GetNewColor(color, old_color_attrs);
  3058.  
  3059.   // We need to flush the stream buffers into the console before each
  3060.   // SetConsoleTextAttribute call lest it affect the text that is already
  3061.   // printed but has not yet reached the console.
  3062.   fflush(stdout);
  3063.   SetConsoleTextAttribute(stdout_handle, new_color);
  3064.  
  3065.   vprintf(fmt, args);
  3066.  
  3067.   fflush(stdout);
  3068.   // Restores the text color.
  3069.   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  3070. #else
  3071.   printf("\033[0;3%sm", GetAnsiColorCode(color));
  3072.   vprintf(fmt, args);
  3073.   printf("\033[m");  // Resets the terminal to default.
  3074. #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3075.   va_end(args);
  3076. }
  3077.  
  3078. // Text printed in Google Test's text output and --gtest_list_tests
  3079. // output to label the type parameter and value parameter for a test.
  3080. static const char kTypeParamLabel[] = "TypeParam";
  3081. static const char kValueParamLabel[] = "GetParam()";
  3082.  
  3083. static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  3084.   const char* const type_param = test_info.type_param();
  3085.   const char* const value_param = test_info.value_param();
  3086.  
  3087.   if (type_param != NULL || value_param != NULL) {
  3088.     printf(", where ");
  3089.     if (type_param != NULL) {
  3090.       printf("%s = %s", kTypeParamLabel, type_param);
  3091.       if (value_param != NULL)
  3092.         printf(" and ");
  3093.     }
  3094.     if (value_param != NULL) {
  3095.       printf("%s = %s", kValueParamLabel, value_param);
  3096.     }
  3097.   }
  3098. }
  3099.  
  3100. // This class implements the TestEventListener interface.
  3101. //
  3102. // Class PrettyUnitTestResultPrinter is copyable.
  3103. class PrettyUnitTestResultPrinter : public TestEventListener {
  3104.  public:
  3105.   PrettyUnitTestResultPrinter() {}
  3106.   static void PrintTestName(const char * test_case, const char * test) {
  3107.     printf("%s.%s", test_case, test);
  3108.   }
  3109.  
  3110.   // The following methods override what's in the TestEventListener class.
  3111.   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  3112.   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3113.   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3114.   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
  3115.   virtual void OnTestCaseStart(const TestCase& test_case);
  3116.   virtual void OnTestStart(const TestInfo& test_info);
  3117.   virtual void OnTestPartResult(const TestPartResult& result);
  3118.   virtual void OnTestEnd(const TestInfo& test_info);
  3119.   virtual void OnTestCaseEnd(const TestCase& test_case);
  3120.   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3121.   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  3122.   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3123.   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
  3124.  
  3125.  private:
  3126.   static void PrintFailedTests(const UnitTest& unit_test);
  3127. };
  3128.  
  3129.   // Fired before each iteration of tests starts.
  3130. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  3131.     const UnitTest& unit_test, int iteration) {
  3132.   if (GTEST_FLAG(repeat) != 1)
  3133.     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  3134.  
  3135.   const char* const filter = GTEST_FLAG(filter).c_str();
  3136.  
  3137.   // Prints the filter if it's not *.  This reminds the user that some
  3138.   // tests may be skipped.
  3139.   if (!String::CStringEquals(filter, kUniversalFilter)) {
  3140.     ColoredPrintf(COLOR_YELLOW,
  3141.                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
  3142.   }
  3143.  
  3144.   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  3145.     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  3146.     ColoredPrintf(COLOR_YELLOW,
  3147.                   "Note: This is test shard %d of %s.\n",
  3148.                   static_cast<int>(shard_index) + 1,
  3149.                   internal::posix::GetEnv(kTestTotalShards));
  3150.   }
  3151.  
  3152.   if (GTEST_FLAG(shuffle)) {
  3153.     ColoredPrintf(COLOR_YELLOW,
  3154.                   "Note: Randomizing tests' orders with a seed of %d .\n",
  3155.                   unit_test.random_seed());
  3156.   }
  3157.  
  3158.   ColoredPrintf(COLOR_GREEN,  "[==========] ");
  3159.   printf("Running %s from %s.\n",
  3160.          FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3161.          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3162.   fflush(stdout);
  3163. }
  3164.  
  3165. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  3166.     const UnitTest& /*unit_test*/) {
  3167.   ColoredPrintf(COLOR_GREEN,  "[----------] ");
  3168.   printf("Global test environment set-up.\n");
  3169.   fflush(stdout);
  3170. }
  3171.  
  3172. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  3173.   const std::string counts =
  3174.       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3175.   ColoredPrintf(COLOR_GREEN, "[----------] ");
  3176.   printf("%s from %s", counts.c_str(), test_case.name());
  3177.   if (test_case.type_param() == NULL) {
  3178.     printf("\n");
  3179.   } else {
  3180.     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
  3181.   }
  3182.   fflush(stdout);
  3183. }
  3184.  
  3185. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  3186.   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
  3187.   PrintTestName(test_info.test_case_name(), test_info.name());
  3188.   printf("\n");
  3189.   fflush(stdout);
  3190. }
  3191.  
  3192. // Called after an assertion failure.
  3193. void PrettyUnitTestResultPrinter::OnTestPartResult(
  3194.     const TestPartResult& result) {
  3195.   // If the test part succeeded, we don't need to do anything.
  3196.   if (result.type() == TestPartResult::kSuccess)
  3197.     return;
  3198.  
  3199.   // Print failure message from the assertion (e.g. expected this and got that).
  3200.   PrintTestPartResult(result);
  3201.   fflush(stdout);
  3202. }
  3203.  
  3204. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  3205.   if (test_info.result()->Passed()) {
  3206.     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
  3207.   } else {
  3208.     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
  3209.   }
  3210.   PrintTestName(test_info.test_case_name(), test_info.name());
  3211.   if (test_info.result()->Failed())
  3212.     PrintFullTestCommentIfPresent(test_info);
  3213.  
  3214.   if (GTEST_FLAG(print_time)) {
  3215.     printf(" (%s ms)\n", internal::StreamableToString(
  3216.            test_info.result()->elapsed_time()).c_str());
  3217.   } else {
  3218.     printf("\n");
  3219.   }
  3220.   fflush(stdout);
  3221. }
  3222.  
  3223. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  3224.   if (!GTEST_FLAG(print_time)) return;
  3225.  
  3226.   const std::string counts =
  3227.       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3228.   ColoredPrintf(COLOR_GREEN, "[----------] ");
  3229.   printf("%s from %s (%s ms total)\n\n",
  3230.          counts.c_str(), test_case.name(),
  3231.          internal::StreamableToString(test_case.elapsed_time()).c_str());
  3232.   fflush(stdout);
  3233. }
  3234.  
  3235. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  3236.     const UnitTest& /*unit_test*/) {
  3237.   ColoredPrintf(COLOR_GREEN,  "[----------] ");
  3238.   printf("Global test environment tear-down\n");
  3239.   fflush(stdout);
  3240. }
  3241.  
  3242. // Internal helper for printing the list of failed tests.
  3243. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  3244.   const int failed_test_count = unit_test.failed_test_count();
  3245.   if (failed_test_count == 0) {
  3246.     return;
  3247.   }
  3248.  
  3249.   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  3250.     const TestCase& test_case = *unit_test.GetTestCase(i);
  3251.     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
  3252.       continue;
  3253.     }
  3254.     for (int j = 0; j < test_case.total_test_count(); ++j) {
  3255.       const TestInfo& test_info = *test_case.GetTestInfo(j);
  3256.       if (!test_info.should_run() || test_info.result()->Passed()) {
  3257.         continue;
  3258.       }
  3259.       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
  3260.       printf("%s.%s", test_case.name(), test_info.name());
  3261.       PrintFullTestCommentIfPresent(test_info);
  3262.       printf("\n");
  3263.     }
  3264.   }
  3265. }
  3266.  
  3267. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3268.                                                      int /*iteration*/) {
  3269.   ColoredPrintf(COLOR_GREEN,  "[==========] ");
  3270.   printf("%s from %s ran.",
  3271.          FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3272.          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3273.   if (GTEST_FLAG(print_time)) {
  3274.     printf(" (%s ms total)",
  3275.            internal::StreamableToString(unit_test.elapsed_time()).c_str());
  3276.   }
  3277.   printf("\n");
  3278.   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
  3279.   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  3280.  
  3281.   int num_failures = unit_test.failed_test_count();
  3282.   if (!unit_test.Passed()) {
  3283.     const int failed_test_count = unit_test.failed_test_count();
  3284.     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
  3285.     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  3286.     PrintFailedTests(unit_test);
  3287.     printf("\n%2d FAILED %s\n", num_failures,
  3288.                         num_failures == 1 ? "TEST" : "TESTS");
  3289.   }
  3290.  
  3291.   int num_disabled = unit_test.reportable_disabled_test_count();
  3292.   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  3293.     if (!num_failures) {
  3294.       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
  3295.     }
  3296.     ColoredPrintf(COLOR_YELLOW,
  3297.                   "  YOU HAVE %d DISABLED %s\n\n",
  3298.                   num_disabled,
  3299.                   num_disabled == 1 ? "TEST" : "TESTS");
  3300.   }
  3301.   // Ensure that Google Test output is printed before, e.g., heapchecker output.
  3302.   fflush(stdout);
  3303. }
  3304.  
  3305. // End PrettyUnitTestResultPrinter
  3306.  
  3307. // class TestEventRepeater
  3308. //
  3309. // This class forwards events to other event listeners.
  3310. class TestEventRepeater : public TestEventListener {
  3311.  public:
  3312.   TestEventRepeater() : forwarding_enabled_(true) {}
  3313.   virtual ~TestEventRepeater();
  3314.   void Append(TestEventListener *listener);
  3315.   TestEventListener* Release(TestEventListener* listener);
  3316.  
  3317.   // Controls whether events will be forwarded to listeners_. Set to false
  3318.   // in death test child processes.
  3319.   bool forwarding_enabled() const { return forwarding_enabled_; }
  3320.   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  3321.  
  3322.   virtual void OnTestProgramStart(const UnitTest& unit_test);
  3323.   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3324.   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3325.   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
  3326.   virtual void OnTestCaseStart(const TestCase& test_case);
  3327.   virtual void OnTestStart(const TestInfo& test_info);
  3328.   virtual void OnTestPartResult(const TestPartResult& result);
  3329.   virtual void OnTestEnd(const TestInfo& test_info);
  3330.   virtual void OnTestCaseEnd(const TestCase& test_case);
  3331.   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3332.   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
  3333.   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3334.   virtual void OnTestProgramEnd(const UnitTest& unit_test);
  3335.  
  3336.  private:
  3337.   // Controls whether events will be forwarded to listeners_. Set to false
  3338.   // in death test child processes.
  3339.   bool forwarding_enabled_;
  3340.   // The list of listeners that receive events.
  3341.   std::vector<TestEventListener*> listeners_;
  3342.  
  3343.   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  3344. };
  3345.  
  3346. TestEventRepeater::~TestEventRepeater() {
  3347.   ForEach(listeners_, Delete<TestEventListener>);
  3348. }
  3349.  
  3350. void TestEventRepeater::Append(TestEventListener *listener) {
  3351.   listeners_.push_back(listener);
  3352. }
  3353.  
  3354. // FIXME: Factor the search functionality into Vector::Find.
  3355. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  3356.   for (size_t i = 0; i < listeners_.size(); ++i) {
  3357.     if (listeners_[i] == listener) {
  3358.       listeners_.erase(listeners_.begin() + i);
  3359.       return listener;
  3360.     }
  3361.   }
  3362.  
  3363.   return NULL;
  3364. }
  3365.  
  3366. // Since most methods are very similar, use macros to reduce boilerplate.
  3367. // This defines a member that forwards the call to all listeners.
  3368. #define GTEST_REPEATER_METHOD_(Name, Type) \
  3369. void TestEventRepeater::Name(const Type& parameter) { \
  3370.   if (forwarding_enabled_) { \
  3371.     for (size_t i = 0; i < listeners_.size(); i++) { \
  3372.       listeners_[i]->Name(parameter); \
  3373.     } \
  3374.   } \
  3375. }
  3376. // This defines a member that forwards the call to all listeners in reverse
  3377. // order.
  3378. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  3379. void TestEventRepeater::Name(const Type& parameter) { \
  3380.   if (forwarding_enabled_) { \
  3381.     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
  3382.       listeners_[i]->Name(parameter); \
  3383.     } \
  3384.   } \
  3385. }
  3386.  
  3387. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  3388. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  3389. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
  3390. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  3391. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  3392. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  3393. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  3394. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  3395. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  3396. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
  3397. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  3398.  
  3399. #undef GTEST_REPEATER_METHOD_
  3400. #undef GTEST_REVERSE_REPEATER_METHOD_
  3401.  
  3402. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  3403.                                              int iteration) {
  3404.   if (forwarding_enabled_) {
  3405.     for (size_t i = 0; i < listeners_.size(); i++) {
  3406.       listeners_[i]->OnTestIterationStart(unit_test, iteration);
  3407.     }
  3408.   }
  3409. }
  3410.  
  3411. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  3412.                                            int iteration) {
  3413.   if (forwarding_enabled_) {
  3414.     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
  3415.       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
  3416.     }
  3417.   }
  3418. }
  3419.  
  3420. // End TestEventRepeater
  3421.  
  3422. // This class generates an XML output file.
  3423. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  3424.  public:
  3425.   explicit XmlUnitTestResultPrinter(const char* output_file);
  3426.  
  3427.   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3428.   void ListTestsMatchingFilter(const std::vector<TestCase*>& test_cases);
  3429.  
  3430.   // Prints an XML summary of all unit tests.
  3431.   static void PrintXmlTestsList(std::ostream* stream,
  3432.                                 const std::vector<TestCase*>& test_cases);
  3433.  
  3434.  private:
  3435.   // Is c a whitespace character that is normalized to a space character
  3436.   // when it appears in an XML attribute value?
  3437.   static bool IsNormalizableWhitespace(char c) {
  3438.     return c == 0x9 || c == 0xA || c == 0xD;
  3439.   }
  3440.  
  3441.   // May c appear in a well-formed XML document?
  3442.   static bool IsValidXmlCharacter(char c) {
  3443.     return IsNormalizableWhitespace(c) || c >= 0x20;
  3444.   }
  3445.  
  3446.   // Returns an XML-escaped copy of the input string str.  If
  3447.   // is_attribute is true, the text is meant to appear as an attribute
  3448.   // value, and normalizable whitespace is preserved by replacing it
  3449.   // with character references.
  3450.   static std::string EscapeXml(const std::string& str, bool is_attribute);
  3451.  
  3452.   // Returns the given string with all characters invalid in XML removed.
  3453.   static std::string RemoveInvalidXmlCharacters(const std::string& str);
  3454.  
  3455.   // Convenience wrapper around EscapeXml when str is an attribute value.
  3456.   static std::string EscapeXmlAttribute(const std::string& str) {
  3457.     return EscapeXml(str, true);
  3458.   }
  3459.  
  3460.   // Convenience wrapper around EscapeXml when str is not an attribute value.
  3461.   static std::string EscapeXmlText(const char* str) {
  3462.     return EscapeXml(str, false);
  3463.   }
  3464.  
  3465.   // Verifies that the given attribute belongs to the given element and
  3466.   // streams the attribute as XML.
  3467.   static void OutputXmlAttribute(std::ostream* stream,
  3468.                                  const std::string& element_name,
  3469.                                  const std::string& name,
  3470.                                  const std::string& value);
  3471.  
  3472.   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  3473.   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  3474.  
  3475.   // Streams an XML representation of a TestInfo object.
  3476.   static void OutputXmlTestInfo(::std::ostream* stream,
  3477.                                 const char* test_case_name,
  3478.                                 const TestInfo& test_info);
  3479.  
  3480.   // Prints an XML representation of a TestCase object
  3481.   static void PrintXmlTestCase(::std::ostream* stream,
  3482.                                const TestCase& test_case);
  3483.  
  3484.   // Prints an XML summary of unit_test to output stream out.
  3485.   static void PrintXmlUnitTest(::std::ostream* stream,
  3486.                                const UnitTest& unit_test);
  3487.  
  3488.   // Produces a string representing the test properties in a result as space
  3489.   // delimited XML attributes based on the property key="value" pairs.
  3490.   // When the std::string is not empty, it includes a space at the beginning,
  3491.   // to delimit this attribute from prior attributes.
  3492.   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
  3493.  
  3494.   // Streams an XML representation of the test properties of a TestResult
  3495.   // object.
  3496.   static void OutputXmlTestProperties(std::ostream* stream,
  3497.                                       const TestResult& result);
  3498.  
  3499.   // The output file.
  3500.   const std::string output_file_;
  3501.  
  3502.   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  3503. };
  3504.  
  3505. // Creates a new XmlUnitTestResultPrinter.
  3506. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  3507.     : output_file_(output_file) {
  3508.   if (output_file_.c_str() == NULL || output_file_.empty()) {
  3509.     GTEST_LOG_(FATAL) << "XML output file may not be null";
  3510.   }
  3511. }
  3512.  
  3513. // Called after the unit test ends.
  3514. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3515.                                                   int /*iteration*/) {
  3516.   FILE* xmlout = OpenFileForWriting(output_file_);
  3517.   std::stringstream stream;
  3518.   PrintXmlUnitTest(&stream, unit_test);
  3519.   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  3520.   fclose(xmlout);
  3521. }
  3522.  
  3523. void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
  3524.     const std::vector<TestCase*>& test_cases) {
  3525.   FILE* xmlout = OpenFileForWriting(output_file_);
  3526.   std::stringstream stream;
  3527.   PrintXmlTestsList(&stream, test_cases);
  3528.   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  3529.   fclose(xmlout);
  3530. }
  3531.  
  3532. // Returns an XML-escaped copy of the input string str.  If is_attribute
  3533. // is true, the text is meant to appear as an attribute value, and
  3534. // normalizable whitespace is preserved by replacing it with character
  3535. // references.
  3536. //
  3537. // Invalid XML characters in str, if any, are stripped from the output.
  3538. // It is expected that most, if not all, of the text processed by this
  3539. // module will consist of ordinary English text.
  3540. // If this module is ever modified to produce version 1.1 XML output,
  3541. // most invalid characters can be retained using character references.
  3542. // FIXME: It might be nice to have a minimally invasive, human-readable
  3543. // escaping scheme for invalid characters, rather than dropping them.
  3544. std::string XmlUnitTestResultPrinter::EscapeXml(
  3545.     const std::string& str, bool is_attribute) {
  3546.   Message m;
  3547.  
  3548.   for (size_t i = 0; i < str.size(); ++i) {
  3549.     const char ch = str[i];
  3550.     switch (ch) {
  3551.       case '<':
  3552.         m << "&lt;";
  3553.         break;
  3554.       case '>':
  3555.         m << "&gt;";
  3556.         break;
  3557.       case '&':
  3558.         m << "&amp;";
  3559.         break;
  3560.       case '\'':
  3561.         if (is_attribute)
  3562.           m << "&apos;";
  3563.         else
  3564.           m << '\'';
  3565.         break;
  3566.       case '"':
  3567.         if (is_attribute)
  3568.           m << "&quot;";
  3569.         else
  3570.           m << '"';
  3571.         break;
  3572.       default:
  3573.         if (IsValidXmlCharacter(ch)) {
  3574.           if (is_attribute && IsNormalizableWhitespace(ch))
  3575.             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
  3576.               << ";";
  3577.           else
  3578.             m << ch;
  3579.         }
  3580.         break;
  3581.     }
  3582.   }
  3583.  
  3584.   return m.GetString();
  3585. }
  3586.  
  3587. // Returns the given string with all characters invalid in XML removed.
  3588. // Currently invalid characters are dropped from the string. An
  3589. // alternative is to replace them with certain characters such as . or ?.
  3590. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
  3591.     const std::string& str) {
  3592.   std::string output;
  3593.   output.reserve(str.size());
  3594.   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  3595.     if (IsValidXmlCharacter(*it))
  3596.       output.push_back(*it);
  3597.  
  3598.   return output;
  3599. }
  3600.  
  3601. // The following routines generate an XML representation of a UnitTest
  3602. // object.
  3603. // GOOGLETEST_CM0009 DO NOT DELETE
  3604. //
  3605. // This is how Google Test concepts map to the DTD:
  3606. //
  3607. // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
  3608. //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
  3609. //     <testcase name="test-name">     <-- corresponds to a TestInfo object
  3610. //       <failure message="...">...</failure>
  3611. //       <failure message="...">...</failure>
  3612. //       <failure message="...">...</failure>
  3613. //                                     <-- individual assertion failures
  3614. //     </testcase>
  3615. //   </testsuite>
  3616. // </testsuites>
  3617.  
  3618. // Formats the given time in milliseconds as seconds.
  3619. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  3620.   ::std::stringstream ss;
  3621.   ss << (static_cast<double>(ms) * 1e-3);
  3622.   return ss.str();
  3623. }
  3624.  
  3625. static bool PortableLocaltime(time_t seconds, struct tm* out) {
  3626. #if defined(_MSC_VER)
  3627.   return localtime_s(out, &seconds) == 0;
  3628. #elif defined(__MINGW32__) || defined(__MINGW64__)
  3629.   // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
  3630.   // Windows' localtime(), which has a thread-local tm buffer.
  3631.   struct tm* tm_ptr = localtime(&seconds);  // NOLINT
  3632.   if (tm_ptr == NULL)
  3633.     return false;
  3634.   *out = *tm_ptr;
  3635.   return true;
  3636. #else
  3637.   return localtime_r(&seconds, out) != NULL;
  3638. #endif
  3639. }
  3640.  
  3641. // Converts the given epoch time in milliseconds to a date string in the ISO
  3642. // 8601 format, without the timezone information.
  3643. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  3644.   struct tm time_struct;
  3645.   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  3646.     return "";
  3647.   // YYYY-MM-DDThh:mm:ss
  3648.   return StreamableToString(time_struct.tm_year + 1900) + "-" +
  3649.       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  3650.       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  3651.       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  3652.       String::FormatIntWidth2(time_struct.tm_min) + ":" +
  3653.       String::FormatIntWidth2(time_struct.tm_sec);
  3654. }
  3655.  
  3656. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  3657. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  3658.                                                      const char* data) {
  3659.   const char* segment = data;
  3660.   *stream << "<![CDATA[";
  3661.   for (;;) {
  3662.     const char* const next_segment = strstr(segment, "]]>");
  3663.     if (next_segment != NULL) {
  3664.       stream->write(
  3665.           segment, static_cast<std::streamsize>(next_segment - segment));
  3666.       *stream << "]]>]]&gt;<![CDATA[";
  3667.       segment = next_segment + strlen("]]>");
  3668.     } else {
  3669.       *stream << segment;
  3670.       break;
  3671.     }
  3672.   }
  3673.   *stream << "]]>";
  3674. }
  3675.  
  3676. void XmlUnitTestResultPrinter::OutputXmlAttribute(
  3677.     std::ostream* stream,
  3678.     const std::string& element_name,
  3679.     const std::string& name,
  3680.     const std::string& value) {
  3681.   const std::vector<std::string>& allowed_names =
  3682.       GetReservedAttributesForElement(element_name);
  3683.  
  3684.   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  3685.                    allowed_names.end())
  3686.       << "Attribute " << name << " is not allowed for element <" << element_name
  3687.       << ">.";
  3688.  
  3689.   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
  3690. }
  3691.  
  3692. // Prints an XML representation of a TestInfo object.
  3693. // FIXME: There is also value in printing properties with the plain printer.
  3694. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  3695.                                                  const char* test_case_name,
  3696.                                                  const TestInfo& test_info) {
  3697.   const TestResult& result = *test_info.result();
  3698.   const std::string kTestcase = "testcase";
  3699.  
  3700.   if (test_info.is_in_another_shard()) {
  3701.     return;
  3702.   }
  3703.  
  3704.   *stream << "    <testcase";
  3705.   OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
  3706.  
  3707.   if (test_info.value_param() != NULL) {
  3708.     OutputXmlAttribute(stream, kTestcase, "value_param",
  3709.                        test_info.value_param());
  3710.   }
  3711.   if (test_info.type_param() != NULL) {
  3712.     OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
  3713.   }
  3714.   if (GTEST_FLAG(list_tests)) {
  3715.     OutputXmlAttribute(stream, kTestcase, "file", test_info.file());
  3716.     OutputXmlAttribute(stream, kTestcase, "line",
  3717.                        StreamableToString(test_info.line()));
  3718.     *stream << " />\n";
  3719.     return;
  3720.   }
  3721.  
  3722.   OutputXmlAttribute(stream, kTestcase, "status",
  3723.                      test_info.should_run() ? "run" : "notrun");
  3724.   OutputXmlAttribute(stream, kTestcase, "time",
  3725.                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
  3726.   OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
  3727.  
  3728.   int failures = 0;
  3729.   for (int i = 0; i < result.total_part_count(); ++i) {
  3730.     const TestPartResult& part = result.GetTestPartResult(i);
  3731.     if (part.failed()) {
  3732.       if (++failures == 1) {
  3733.         *stream << ">\n";
  3734.       }
  3735.       const std::string location =
  3736.           internal::FormatCompilerIndependentFileLocation(part.file_name(),
  3737.                                                           part.line_number());
  3738.       const std::string summary = location + "\n" + part.summary();
  3739.       *stream << "      <failure message=\""
  3740.               << EscapeXmlAttribute(summary.c_str())
  3741.               << "\" type=\"\">";
  3742.       const std::string detail = location + "\n" + part.message();
  3743.       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  3744.       *stream << "</failure>\n";
  3745.     }
  3746.   }
  3747.  
  3748.   if (failures == 0 && result.test_property_count() == 0) {
  3749.     *stream << " />\n";
  3750.   } else {
  3751.     if (failures == 0) {
  3752.       *stream << ">\n";
  3753.     }
  3754.     OutputXmlTestProperties(stream, result);
  3755.     *stream << "    </testcase>\n";
  3756.   }
  3757. }
  3758.  
  3759. // Prints an XML representation of a TestCase object
  3760. void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
  3761.                                                 const TestCase& test_case) {
  3762.   const std::string kTestsuite = "testsuite";
  3763.   *stream << "  <" << kTestsuite;
  3764.   OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
  3765.   OutputXmlAttribute(stream, kTestsuite, "tests",
  3766.                      StreamableToString(test_case.reportable_test_count()));
  3767.   if (!GTEST_FLAG(list_tests)) {
  3768.     OutputXmlAttribute(stream, kTestsuite, "failures",
  3769.                        StreamableToString(test_case.failed_test_count()));
  3770.     OutputXmlAttribute(
  3771.         stream, kTestsuite, "disabled",
  3772.         StreamableToString(test_case.reportable_disabled_test_count()));
  3773.     OutputXmlAttribute(stream, kTestsuite, "errors", "0");
  3774.     OutputXmlAttribute(stream, kTestsuite, "time",
  3775.                        FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
  3776.     *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result());
  3777.   }
  3778.   *stream << ">\n";
  3779.   for (int i = 0; i < test_case.total_test_count(); ++i) {
  3780.     if (test_case.GetTestInfo(i)->is_reportable())
  3781.       OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
  3782.   }
  3783.   *stream << "  </" << kTestsuite << ">\n";
  3784. }
  3785.  
  3786. // Prints an XML summary of unit_test to output stream out.
  3787. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
  3788.                                                 const UnitTest& unit_test) {
  3789.   const std::string kTestsuites = "testsuites";
  3790.  
  3791.   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  3792.   *stream << "<" << kTestsuites;
  3793.  
  3794.   OutputXmlAttribute(stream, kTestsuites, "tests",
  3795.                      StreamableToString(unit_test.reportable_test_count()));
  3796.   OutputXmlAttribute(stream, kTestsuites, "failures",
  3797.                      StreamableToString(unit_test.failed_test_count()));
  3798.   OutputXmlAttribute(
  3799.       stream, kTestsuites, "disabled",
  3800.       StreamableToString(unit_test.reportable_disabled_test_count()));
  3801.   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
  3802.   OutputXmlAttribute(
  3803.       stream, kTestsuites, "timestamp",
  3804.       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
  3805.   OutputXmlAttribute(stream, kTestsuites, "time",
  3806.                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
  3807.  
  3808.   if (GTEST_FLAG(shuffle)) {
  3809.     OutputXmlAttribute(stream, kTestsuites, "random_seed",
  3810.                        StreamableToString(unit_test.random_seed()));
  3811.   }
  3812.   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
  3813.  
  3814.   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  3815.   *stream << ">\n";
  3816.  
  3817.   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  3818.     if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
  3819.       PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
  3820.   }
  3821.   *stream << "</" << kTestsuites << ">\n";
  3822. }
  3823.  
  3824. void XmlUnitTestResultPrinter::PrintXmlTestsList(
  3825.     std::ostream* stream, const std::vector<TestCase*>& test_cases) {
  3826.   const std::string kTestsuites = "testsuites";
  3827.  
  3828.   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  3829.   *stream << "<" << kTestsuites;
  3830.  
  3831.   int total_tests = 0;
  3832.   for (size_t i = 0; i < test_cases.size(); ++i) {
  3833.     total_tests += test_cases[i]->total_test_count();
  3834.   }
  3835.   OutputXmlAttribute(stream, kTestsuites, "tests",
  3836.                      StreamableToString(total_tests));
  3837.   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  3838.   *stream << ">\n";
  3839.  
  3840.   for (size_t i = 0; i < test_cases.size(); ++i) {
  3841.     PrintXmlTestCase(stream, *test_cases[i]);
  3842.   }
  3843.   *stream << "</" << kTestsuites << ">\n";
  3844. }
  3845.  
  3846. // Produces a string representing the test properties in a result as space
  3847. // delimited XML attributes based on the property key="value" pairs.
  3848. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  3849.     const TestResult& result) {
  3850.   Message attributes;
  3851.   for (int i = 0; i < result.test_property_count(); ++i) {
  3852.     const TestProperty& property = result.GetTestProperty(i);
  3853.     attributes << " " << property.key() << "="
  3854.         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  3855.   }
  3856.   return attributes.GetString();
  3857. }
  3858.  
  3859. void XmlUnitTestResultPrinter::OutputXmlTestProperties(
  3860.     std::ostream* stream, const TestResult& result) {
  3861.   const std::string kProperties = "properties";
  3862.   const std::string kProperty = "property";
  3863.  
  3864.   if (result.test_property_count() <= 0) {
  3865.     return;
  3866.   }
  3867.  
  3868.   *stream << "<" << kProperties << ">\n";
  3869.   for (int i = 0; i < result.test_property_count(); ++i) {
  3870.     const TestProperty& property = result.GetTestProperty(i);
  3871.     *stream << "<" << kProperty;
  3872.     *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
  3873.     *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
  3874.     *stream << "/>\n";
  3875.   }
  3876.   *stream << "</" << kProperties << ">\n";
  3877. }
  3878.  
  3879. // End XmlUnitTestResultPrinter
  3880.  
  3881. // This class generates an JSON output file.
  3882. class JsonUnitTestResultPrinter : public EmptyTestEventListener {
  3883.  public:
  3884.   explicit JsonUnitTestResultPrinter(const char* output_file);
  3885.  
  3886.   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3887.  
  3888.   // Prints an JSON summary of all unit tests.
  3889.   static void PrintJsonTestList(::std::ostream* stream,
  3890.                                 const std::vector<TestCase*>& test_cases);
  3891.  
  3892.  private:
  3893.   // Returns an JSON-escaped copy of the input string str.
  3894.   static std::string EscapeJson(const std::string& str);
  3895.  
  3896.   //// Verifies that the given attribute belongs to the given element and
  3897.   //// streams the attribute as JSON.
  3898.   static void OutputJsonKey(std::ostream* stream,
  3899.                             const std::string& element_name,
  3900.                             const std::string& name,
  3901.                             const std::string& value,
  3902.                             const std::string& indent,
  3903.                             bool comma = true);
  3904.   static void OutputJsonKey(std::ostream* stream,
  3905.                             const std::string& element_name,
  3906.                             const std::string& name,
  3907.                             int value,
  3908.                             const std::string& indent,
  3909.                             bool comma = true);
  3910.  
  3911.   // Streams a JSON representation of a TestInfo object.
  3912.   static void OutputJsonTestInfo(::std::ostream* stream,
  3913.                                  const char* test_case_name,
  3914.                                  const TestInfo& test_info);
  3915.  
  3916.   // Prints a JSON representation of a TestCase object
  3917.   static void PrintJsonTestCase(::std::ostream* stream,
  3918.                                 const TestCase& test_case);
  3919.  
  3920.   // Prints a JSON summary of unit_test to output stream out.
  3921.   static void PrintJsonUnitTest(::std::ostream* stream,
  3922.                                 const UnitTest& unit_test);
  3923.  
  3924.   // Produces a string representing the test properties in a result as
  3925.   // a JSON dictionary.
  3926.   static std::string TestPropertiesAsJson(const TestResult& result,
  3927.                                           const std::string& indent);
  3928.  
  3929.   // The output file.
  3930.   const std::string output_file_;
  3931.  
  3932.   GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
  3933. };
  3934.  
  3935. // Creates a new JsonUnitTestResultPrinter.
  3936. JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
  3937.     : output_file_(output_file) {
  3938.   if (output_file_.empty()) {
  3939.     GTEST_LOG_(FATAL) << "JSON output file may not be null";
  3940.   }
  3941. }
  3942.  
  3943. void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3944.                                                   int /*iteration*/) {
  3945.   FILE* jsonout = OpenFileForWriting(output_file_);
  3946.   std::stringstream stream;
  3947.   PrintJsonUnitTest(&stream, unit_test);
  3948.   fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
  3949.   fclose(jsonout);
  3950. }
  3951.  
  3952. // Returns an JSON-escaped copy of the input string str.
  3953. std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
  3954.   Message m;
  3955.  
  3956.   for (size_t i = 0; i < str.size(); ++i) {
  3957.     const char ch = str[i];
  3958.     switch (ch) {
  3959.       case '\\':
  3960.       case '"':
  3961.       case '/':
  3962.         m << '\\' << ch;
  3963.         break;
  3964.       case '\b':
  3965.         m << "\\b";
  3966.         break;
  3967.       case '\t':
  3968.         m << "\\t";
  3969.         break;
  3970.       case '\n':
  3971.         m << "\\n";
  3972.         break;
  3973.       case '\f':
  3974.         m << "\\f";
  3975.         break;
  3976.       case '\r':
  3977.         m << "\\r";
  3978.         break;
  3979.       default:
  3980.         if (ch < ' ') {
  3981.           m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
  3982.         } else {
  3983.           m << ch;
  3984.         }
  3985.         break;
  3986.     }
  3987.   }
  3988.  
  3989.   return m.GetString();
  3990. }
  3991.  
  3992. // The following routines generate an JSON representation of a UnitTest
  3993. // object.
  3994.  
  3995. // Formats the given time in milliseconds as seconds.
  3996. static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
  3997.   ::std::stringstream ss;
  3998.   ss << (static_cast<double>(ms) * 1e-3) << "s";
  3999.   return ss.str();
  4000. }
  4001.  
  4002. // Converts the given epoch time in milliseconds to a date string in the
  4003. // RFC3339 format, without the timezone information.
  4004. static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
  4005.   struct tm time_struct;
  4006.   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  4007.     return "";
  4008.   // YYYY-MM-DDThh:mm:ss
  4009.   return StreamableToString(time_struct.tm_year + 1900) + "-" +
  4010.       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  4011.       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  4012.       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  4013.       String::FormatIntWidth2(time_struct.tm_min) + ":" +
  4014.       String::FormatIntWidth2(time_struct.tm_sec) + "Z";
  4015. }
  4016.  
  4017. static inline std::string Indent(int width) {
  4018.   return std::string(width, ' ');
  4019. }
  4020.  
  4021. void JsonUnitTestResultPrinter::OutputJsonKey(
  4022.     std::ostream* stream,
  4023.     const std::string& element_name,
  4024.     const std::string& name,
  4025.     const std::string& value,
  4026.     const std::string& indent,
  4027.     bool comma) {
  4028.   const std::vector<std::string>& allowed_names =
  4029.       GetReservedAttributesForElement(element_name);
  4030.  
  4031.   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4032.                    allowed_names.end())
  4033.       << "Key \"" << name << "\" is not allowed for value \"" << element_name
  4034.       << "\".";
  4035.  
  4036.   *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
  4037.   if (comma)
  4038.     *stream << ",\n";
  4039. }
  4040.  
  4041. void JsonUnitTestResultPrinter::OutputJsonKey(
  4042.     std::ostream* stream,
  4043.     const std::string& element_name,
  4044.     const std::string& name,
  4045.     int value,
  4046.     const std::string& indent,
  4047.     bool comma) {
  4048.   const std::vector<std::string>& allowed_names =
  4049.       GetReservedAttributesForElement(element_name);
  4050.  
  4051.   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4052.                    allowed_names.end())
  4053.       << "Key \"" << name << "\" is not allowed for value \"" << element_name
  4054.       << "\".";
  4055.  
  4056.   *stream << indent << "\"" << name << "\": " << StreamableToString(value);
  4057.   if (comma)
  4058.     *stream << ",\n";
  4059. }
  4060.  
  4061. // Prints a JSON representation of a TestInfo object.
  4062. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
  4063.                                                    const char* test_case_name,
  4064.                                                    const TestInfo& test_info) {
  4065.   const TestResult& result = *test_info.result();
  4066.   const std::string kTestcase = "testcase";
  4067.   const std::string kIndent = Indent(10);
  4068.  
  4069.   *stream << Indent(8) << "{\n";
  4070.   OutputJsonKey(stream, kTestcase, "name", test_info.name(), kIndent);
  4071.  
  4072.   if (test_info.value_param() != NULL) {
  4073.     OutputJsonKey(stream, kTestcase, "value_param",
  4074.                   test_info.value_param(), kIndent);
  4075.   }
  4076.   if (test_info.type_param() != NULL) {
  4077.     OutputJsonKey(stream, kTestcase, "type_param", test_info.type_param(),
  4078.                   kIndent);
  4079.   }
  4080.   if (GTEST_FLAG(list_tests)) {
  4081.     OutputJsonKey(stream, kTestcase, "file", test_info.file(), kIndent);
  4082.     OutputJsonKey(stream, kTestcase, "line", test_info.line(), kIndent, false);
  4083.     *stream << "\n" << Indent(8) << "}";
  4084.     return;
  4085.   }
  4086.  
  4087.   OutputJsonKey(stream, kTestcase, "status",
  4088.                 test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
  4089.   OutputJsonKey(stream, kTestcase, "time",
  4090.                 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
  4091.   OutputJsonKey(stream, kTestcase, "classname", test_case_name, kIndent, false);
  4092.   *stream << TestPropertiesAsJson(result, kIndent);
  4093.  
  4094.   int failures = 0;
  4095.   for (int i = 0; i < result.total_part_count(); ++i) {
  4096.     const TestPartResult& part = result.GetTestPartResult(i);
  4097.     if (part.failed()) {
  4098.       *stream << ",\n";
  4099.       if (++failures == 1) {
  4100.         *stream << kIndent << "\"" << "failures" << "\": [\n";
  4101.       }
  4102.       const std::string location =
  4103.           internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4104.                                                           part.line_number());
  4105.       const std::string message = EscapeJson(location + "\n" + part.message());
  4106.       *stream << kIndent << "  {\n"
  4107.               << kIndent << "    \"failure\": \"" << message << "\",\n"
  4108.               << kIndent << "    \"type\": \"\"\n"
  4109.               << kIndent << "  }";
  4110.     }
  4111.   }
  4112.  
  4113.   if (failures > 0)
  4114.     *stream << "\n" << kIndent << "]";
  4115.   *stream << "\n" << Indent(8) << "}";
  4116. }
  4117.  
  4118. // Prints an JSON representation of a TestCase object
  4119. void JsonUnitTestResultPrinter::PrintJsonTestCase(std::ostream* stream,
  4120.                                                   const TestCase& test_case) {
  4121.   const std::string kTestsuite = "testsuite";
  4122.   const std::string kIndent = Indent(6);
  4123.  
  4124.   *stream << Indent(4) << "{\n";
  4125.   OutputJsonKey(stream, kTestsuite, "name", test_case.name(), kIndent);
  4126.   OutputJsonKey(stream, kTestsuite, "tests", test_case.reportable_test_count(),
  4127.                 kIndent);
  4128.   if (!GTEST_FLAG(list_tests)) {
  4129.     OutputJsonKey(stream, kTestsuite, "failures", test_case.failed_test_count(),
  4130.                   kIndent);
  4131.     OutputJsonKey(stream, kTestsuite, "disabled",
  4132.                   test_case.reportable_disabled_test_count(), kIndent);
  4133.     OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
  4134.     OutputJsonKey(stream, kTestsuite, "time",
  4135.                   FormatTimeInMillisAsDuration(test_case.elapsed_time()),
  4136.                   kIndent, false);
  4137.     *stream << TestPropertiesAsJson(test_case.ad_hoc_test_result(), kIndent)
  4138.             << ",\n";
  4139.   }
  4140.  
  4141.   *stream << kIndent << "\"" << kTestsuite << "\": [\n";
  4142.  
  4143.   bool comma = false;
  4144.   for (int i = 0; i < test_case.total_test_count(); ++i) {
  4145.     if (test_case.GetTestInfo(i)->is_reportable()) {
  4146.       if (comma) {
  4147.         *stream << ",\n";
  4148.       } else {
  4149.         comma = true;
  4150.       }
  4151.       OutputJsonTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
  4152.     }
  4153.   }
  4154.   *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
  4155. }
  4156.  
  4157. // Prints a JSON summary of unit_test to output stream out.
  4158. void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
  4159.                                                   const UnitTest& unit_test) {
  4160.   const std::string kTestsuites = "testsuites";
  4161.   const std::string kIndent = Indent(2);
  4162.   *stream << "{\n";
  4163.  
  4164.   OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
  4165.                 kIndent);
  4166.   OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
  4167.                 kIndent);
  4168.   OutputJsonKey(stream, kTestsuites, "disabled",
  4169.                 unit_test.reportable_disabled_test_count(), kIndent);
  4170.   OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
  4171.   if (GTEST_FLAG(shuffle)) {
  4172.     OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
  4173.                   kIndent);
  4174.   }
  4175.   OutputJsonKey(stream, kTestsuites, "timestamp",
  4176.                 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
  4177.                 kIndent);
  4178.   OutputJsonKey(stream, kTestsuites, "time",
  4179.                 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
  4180.                 false);
  4181.  
  4182.   *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
  4183.           << ",\n";
  4184.  
  4185.   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4186.   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4187.  
  4188.   bool comma = false;
  4189.   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  4190.     if (unit_test.GetTestCase(i)->reportable_test_count() > 0) {
  4191.       if (comma) {
  4192.         *stream << ",\n";
  4193.       } else {
  4194.         comma = true;
  4195.       }
  4196.       PrintJsonTestCase(stream, *unit_test.GetTestCase(i));
  4197.     }
  4198.   }
  4199.  
  4200.   *stream << "\n" << kIndent << "]\n" << "}\n";
  4201. }
  4202.  
  4203. void JsonUnitTestResultPrinter::PrintJsonTestList(
  4204.     std::ostream* stream, const std::vector<TestCase*>& test_cases) {
  4205.   const std::string kTestsuites = "testsuites";
  4206.   const std::string kIndent = Indent(2);
  4207.   *stream << "{\n";
  4208.   int total_tests = 0;
  4209.   for (size_t i = 0; i < test_cases.size(); ++i) {
  4210.     total_tests += test_cases[i]->total_test_count();
  4211.   }
  4212.   OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
  4213.  
  4214.   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4215.   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4216.  
  4217.   for (size_t i = 0; i < test_cases.size(); ++i) {
  4218.     if (i != 0) {
  4219.       *stream << ",\n";
  4220.     }
  4221.     PrintJsonTestCase(stream, *test_cases[i]);
  4222.   }
  4223.  
  4224.   *stream << "\n"
  4225.           << kIndent << "]\n"
  4226.           << "}\n";
  4227. }
  4228. // Produces a string representing the test properties in a result as
  4229. // a JSON dictionary.
  4230. std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
  4231.     const TestResult& result, const std::string& indent) {
  4232.   Message attributes;
  4233.   for (int i = 0; i < result.test_property_count(); ++i) {
  4234.     const TestProperty& property = result.GetTestProperty(i);
  4235.     attributes << ",\n" << indent << "\"" << property.key() << "\": "
  4236.                << "\"" << EscapeJson(property.value()) << "\"";
  4237.   }
  4238.   return attributes.GetString();
  4239. }
  4240.  
  4241. // End JsonUnitTestResultPrinter
  4242.  
  4243. #if GTEST_CAN_STREAM_RESULTS_
  4244.  
  4245. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  4246. // replaces them by "%xx" where xx is their hexadecimal value. For
  4247. // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
  4248. // in both time and space -- important as the input str may contain an
  4249. // arbitrarily long test failure message and stack trace.
  4250. std::string StreamingListener::UrlEncode(const char* str) {
  4251.   std::string result;
  4252.   result.reserve(strlen(str) + 1);
  4253.   for (char ch = *str; ch != '\0'; ch = *++str) {
  4254.     switch (ch) {
  4255.       case '%':
  4256.       case '=':
  4257.       case '&':
  4258.       case '\n':
  4259.         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
  4260.         break;
  4261.       default:
  4262.         result.push_back(ch);
  4263.         break;
  4264.     }
  4265.   }
  4266.   return result;
  4267. }
  4268.  
  4269. void StreamingListener::SocketWriter::MakeConnection() {
  4270.   GTEST_CHECK_(sockfd_ == -1)
  4271.       << "MakeConnection() can't be called when there is already a connection.";
  4272.  
  4273.   addrinfo hints;
  4274.   memset(&hints, 0, sizeof(hints));
  4275.   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
  4276.   hints.ai_socktype = SOCK_STREAM;
  4277.   addrinfo* servinfo = NULL;
  4278.  
  4279.   // Use the getaddrinfo() to get a linked list of IP addresses for
  4280.   // the given host name.
  4281.   const int error_num = getaddrinfo(
  4282.       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  4283.   if (error_num != 0) {
  4284.     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  4285.                         << gai_strerror(error_num);
  4286.   }
  4287.  
  4288.   // Loop through all the results and connect to the first we can.
  4289.   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
  4290.        cur_addr = cur_addr->ai_next) {
  4291.     sockfd_ = socket(
  4292.         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  4293.     if (sockfd_ != -1) {
  4294.       // Connect the client socket to the server socket.
  4295.       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  4296.         close(sockfd_);
  4297.         sockfd_ = -1;
  4298.       }
  4299.     }
  4300.   }
  4301.  
  4302.   freeaddrinfo(servinfo);  // all done with this structure
  4303.  
  4304.   if (sockfd_ == -1) {
  4305.     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  4306.                         << host_name_ << ":" << port_num_;
  4307.   }
  4308. }
  4309.  
  4310. // End of class Streaming Listener
  4311. #endif  // GTEST_CAN_STREAM_RESULTS__
  4312.  
  4313. // class OsStackTraceGetter
  4314.  
  4315. const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
  4316.     "... " GTEST_NAME_ " internal frames ...";
  4317.  
  4318. std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
  4319.     GTEST_LOCK_EXCLUDED_(mutex_) {
  4320. #if GTEST_HAS_ABSL
  4321.   std::string result;
  4322.  
  4323.   if (max_depth <= 0) {
  4324.     return result;
  4325.   }
  4326.  
  4327.   max_depth = std::min(max_depth, kMaxStackTraceDepth);
  4328.  
  4329.   std::vector<void*> raw_stack(max_depth);
  4330.   // Skips the frames requested by the caller, plus this function.
  4331.   const int raw_stack_size =
  4332.       absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
  4333.  
  4334.   void* caller_frame = nullptr;
  4335.   {
  4336.     MutexLock lock(&mutex_);
  4337.     caller_frame = caller_frame_;
  4338.   }
  4339.  
  4340.   for (int i = 0; i < raw_stack_size; ++i) {
  4341.     if (raw_stack[i] == caller_frame &&
  4342.         !GTEST_FLAG(show_internal_stack_frames)) {
  4343.       // Add a marker to the trace and stop adding frames.
  4344.       absl::StrAppend(&result, kElidedFramesMarker, "\n");
  4345.       break;
  4346.     }
  4347.  
  4348.     char tmp[1024];
  4349.     const char* symbol = "(unknown)";
  4350.     if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
  4351.       symbol = tmp;
  4352.     }
  4353.  
  4354.     char line[1024];
  4355.     snprintf(line, sizeof(line), "  %p: %s\n", raw_stack[i], symbol);
  4356.     result += line;
  4357.   }
  4358.  
  4359.   return result;
  4360.  
  4361. #else  // !GTEST_HAS_ABSL
  4362.   static_cast<void>(max_depth);
  4363.   static_cast<void>(skip_count);
  4364.   return "";
  4365. #endif  // GTEST_HAS_ABSL
  4366. }
  4367.  
  4368. void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
  4369. #if GTEST_HAS_ABSL
  4370.   void* caller_frame = nullptr;
  4371.   if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
  4372.     caller_frame = nullptr;
  4373.   }
  4374.  
  4375.   MutexLock lock(&mutex_);
  4376.   caller_frame_ = caller_frame;
  4377. #endif  // GTEST_HAS_ABSL
  4378. }
  4379.  
  4380. // A helper class that creates the premature-exit file in its
  4381. // constructor and deletes the file in its destructor.
  4382. class ScopedPrematureExitFile {
  4383.  public:
  4384.   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
  4385.       : premature_exit_filepath_(premature_exit_filepath ?
  4386.                                  premature_exit_filepath : "") {
  4387.     // If a path to the premature-exit file is specified...
  4388.     if (!premature_exit_filepath_.empty()) {
  4389.       // create the file with a single "0" character in it.  I/O
  4390.       // errors are ignored as there's nothing better we can do and we
  4391.       // don't want to fail the test because of this.
  4392.       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
  4393.       fwrite("0", 1, 1, pfile);
  4394.       fclose(pfile);
  4395.     }
  4396.   }
  4397.  
  4398.   ~ScopedPrematureExitFile() {
  4399.     if (!premature_exit_filepath_.empty()) {
  4400.       int retval = remove(premature_exit_filepath_.c_str());
  4401.       if (retval) {
  4402.         GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
  4403.                           << premature_exit_filepath_ << "\" with error "
  4404.                           << retval;
  4405.       }
  4406.     }
  4407.   }
  4408.  
  4409.  private:
  4410.   const std::string premature_exit_filepath_;
  4411.  
  4412.   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
  4413. };
  4414.  
  4415. }  // namespace internal
  4416.  
  4417. // class TestEventListeners
  4418.  
  4419. TestEventListeners::TestEventListeners()
  4420.     : repeater_(new internal::TestEventRepeater()),
  4421.       default_result_printer_(NULL),
  4422.       default_xml_generator_(NULL) {
  4423. }
  4424.  
  4425. TestEventListeners::~TestEventListeners() { delete repeater_; }
  4426.  
  4427. // Returns the standard listener responsible for the default console
  4428. // output.  Can be removed from the listeners list to shut down default
  4429. // console output.  Note that removing this object from the listener list
  4430. // with Release transfers its ownership to the user.
  4431. void TestEventListeners::Append(TestEventListener* listener) {
  4432.   repeater_->Append(listener);
  4433. }
  4434.  
  4435. // Removes the given event listener from the list and returns it.  It then
  4436. // becomes the caller's responsibility to delete the listener. Returns
  4437. // NULL if the listener is not found in the list.
  4438. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  4439.   if (listener == default_result_printer_)
  4440.     default_result_printer_ = NULL;
  4441.   else if (listener == default_xml_generator_)
  4442.     default_xml_generator_ = NULL;
  4443.   return repeater_->Release(listener);
  4444. }
  4445.  
  4446. // Returns repeater that broadcasts the TestEventListener events to all
  4447. // subscribers.
  4448. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  4449.  
  4450. // Sets the default_result_printer attribute to the provided listener.
  4451. // The listener is also added to the listener list and previous
  4452. // default_result_printer is removed from it and deleted. The listener can
  4453. // also be NULL in which case it will not be added to the list. Does
  4454. // nothing if the previous and the current listener objects are the same.
  4455. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  4456.   if (default_result_printer_ != listener) {
  4457.     // It is an error to pass this method a listener that is already in the
  4458.     // list.
  4459.     delete Release(default_result_printer_);
  4460.     default_result_printer_ = listener;
  4461.     if (listener != NULL)
  4462.       Append(listener);
  4463.   }
  4464. }
  4465.  
  4466. // Sets the default_xml_generator attribute to the provided listener.  The
  4467. // listener is also added to the listener list and previous
  4468. // default_xml_generator is removed from it and deleted. The listener can
  4469. // also be NULL in which case it will not be added to the list. Does
  4470. // nothing if the previous and the current listener objects are the same.
  4471. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  4472.   if (default_xml_generator_ != listener) {
  4473.     // It is an error to pass this method a listener that is already in the
  4474.     // list.
  4475.     delete Release(default_xml_generator_);
  4476.     default_xml_generator_ = listener;
  4477.     if (listener != NULL)
  4478.       Append(listener);
  4479.   }
  4480. }
  4481.  
  4482. // Controls whether events will be forwarded by the repeater to the
  4483. // listeners in the list.
  4484. bool TestEventListeners::EventForwardingEnabled() const {
  4485.   return repeater_->forwarding_enabled();
  4486. }
  4487.  
  4488. void TestEventListeners::SuppressEventForwarding() {
  4489.   repeater_->set_forwarding_enabled(false);
  4490. }
  4491.  
  4492. // class UnitTest
  4493.  
  4494. // Gets the singleton UnitTest object.  The first time this method is
  4495. // called, a UnitTest object is constructed and returned.  Consecutive
  4496. // calls will return the same object.
  4497. //
  4498. // We don't protect this under mutex_ as a user is not supposed to
  4499. // call this before main() starts, from which point on the return
  4500. // value will never change.
  4501. UnitTest* UnitTest::GetInstance() {
  4502.   // When compiled with MSVC 7.1 in optimized mode, destroying the
  4503.   // UnitTest object upon exiting the program messes up the exit code,
  4504.   // causing successful tests to appear failed.  We have to use a
  4505.   // different implementation in this case to bypass the compiler bug.
  4506.   // This implementation makes the compiler happy, at the cost of
  4507.   // leaking the UnitTest object.
  4508.  
  4509.   // CodeGear C++Builder insists on a public destructor for the
  4510.   // default implementation.  Use this implementation to keep good OO
  4511.   // design with private destructor.
  4512.  
  4513. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  4514.   static UnitTest* const instance = new UnitTest;
  4515.   return instance;
  4516. #else
  4517.   static UnitTest instance;
  4518.   return &instance;
  4519. #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  4520. }
  4521.  
  4522. // Gets the number of successful test cases.
  4523. int UnitTest::successful_test_case_count() const {
  4524.   return impl()->successful_test_case_count();
  4525. }
  4526.  
  4527. // Gets the number of failed test cases.
  4528. int UnitTest::failed_test_case_count() const {
  4529.   return impl()->failed_test_case_count();
  4530. }
  4531.  
  4532. // Gets the number of all test cases.
  4533. int UnitTest::total_test_case_count() const {
  4534.   return impl()->total_test_case_count();
  4535. }
  4536.  
  4537. // Gets the number of all test cases that contain at least one test
  4538. // that should run.
  4539. int UnitTest::test_case_to_run_count() const {
  4540.   return impl()->test_case_to_run_count();
  4541. }
  4542.  
  4543. // Gets the number of successful tests.
  4544. int UnitTest::successful_test_count() const {
  4545.   return impl()->successful_test_count();
  4546. }
  4547.  
  4548. // Gets the number of failed tests.
  4549. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  4550.  
  4551. // Gets the number of disabled tests that will be reported in the XML report.
  4552. int UnitTest::reportable_disabled_test_count() const {
  4553.   return impl()->reportable_disabled_test_count();
  4554. }
  4555.  
  4556. // Gets the number of disabled tests.
  4557. int UnitTest::disabled_test_count() const {
  4558.   return impl()->disabled_test_count();
  4559. }
  4560.  
  4561. // Gets the number of tests to be printed in the XML report.
  4562. int UnitTest::reportable_test_count() const {
  4563.   return impl()->reportable_test_count();
  4564. }
  4565.  
  4566. // Gets the number of all tests.
  4567. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  4568.  
  4569. // Gets the number of tests that should run.
  4570. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  4571.  
  4572. // Gets the time of the test program start, in ms from the start of the
  4573. // UNIX epoch.
  4574. internal::TimeInMillis UnitTest::start_timestamp() const {
  4575.     return impl()->start_timestamp();
  4576. }
  4577.  
  4578. // Gets the elapsed time, in milliseconds.
  4579. internal::TimeInMillis UnitTest::elapsed_time() const {
  4580.   return impl()->elapsed_time();
  4581. }
  4582.  
  4583. // Returns true iff the unit test passed (i.e. all test cases passed).
  4584. bool UnitTest::Passed() const { return impl()->Passed(); }
  4585.  
  4586. // Returns true iff the unit test failed (i.e. some test case failed
  4587. // or something outside of all tests failed).
  4588. bool UnitTest::Failed() const { return impl()->Failed(); }
  4589.  
  4590. // Gets the i-th test case among all the test cases. i can range from 0 to
  4591. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  4592. const TestCase* UnitTest::GetTestCase(int i) const {
  4593.   return impl()->GetTestCase(i);
  4594. }
  4595.  
  4596. // Returns the TestResult containing information on test failures and
  4597. // properties logged outside of individual test cases.
  4598. const TestResult& UnitTest::ad_hoc_test_result() const {
  4599.   return *impl()->ad_hoc_test_result();
  4600. }
  4601.  
  4602. // Gets the i-th test case among all the test cases. i can range from 0 to
  4603. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  4604. TestCase* UnitTest::GetMutableTestCase(int i) {
  4605.   return impl()->GetMutableTestCase(i);
  4606. }
  4607.  
  4608. // Returns the list of event listeners that can be used to track events
  4609. // inside Google Test.
  4610. TestEventListeners& UnitTest::listeners() {
  4611.   return *impl()->listeners();
  4612. }
  4613.  
  4614. // Registers and returns a global test environment.  When a test
  4615. // program is run, all global test environments will be set-up in the
  4616. // order they were registered.  After all tests in the program have
  4617. // finished, all global test environments will be torn-down in the
  4618. // *reverse* order they were registered.
  4619. //
  4620. // The UnitTest object takes ownership of the given environment.
  4621. //
  4622. // We don't protect this under mutex_, as we only support calling it
  4623. // from the main thread.
  4624. Environment* UnitTest::AddEnvironment(Environment* env) {
  4625.   if (env == NULL) {
  4626.     return NULL;
  4627.   }
  4628.  
  4629.   impl_->environments().push_back(env);
  4630.   return env;
  4631. }
  4632.  
  4633. // Adds a TestPartResult to the current TestResult object.  All Google Test
  4634. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  4635. // this to report their results.  The user code should use the
  4636. // assertion macros instead of calling this directly.
  4637. void UnitTest::AddTestPartResult(
  4638.     TestPartResult::Type result_type,
  4639.     const char* file_name,
  4640.     int line_number,
  4641.     const std::string& message,
  4642.     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
  4643.   Message msg;
  4644.   msg << message;
  4645.  
  4646.   internal::MutexLock lock(&mutex_);
  4647.   if (impl_->gtest_trace_stack().size() > 0) {
  4648.     msg << "\n" << GTEST_NAME_ << " trace:";
  4649.  
  4650.     for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
  4651.          i > 0; --i) {
  4652.       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  4653.       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  4654.           << " " << trace.message;
  4655.     }
  4656.   }
  4657.  
  4658.   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
  4659.     msg << internal::kStackTraceMarker << os_stack_trace;
  4660.   }
  4661.  
  4662.   const TestPartResult result =
  4663.     TestPartResult(result_type, file_name, line_number,
  4664.                    msg.GetString().c_str());
  4665.   impl_->GetTestPartResultReporterForCurrentThread()->
  4666.       ReportTestPartResult(result);
  4667.  
  4668.   if (result_type != TestPartResult::kSuccess) {
  4669.     // gtest_break_on_failure takes precedence over
  4670.     // gtest_throw_on_failure.  This allows a user to set the latter
  4671.     // in the code (perhaps in order to use Google Test assertions
  4672.     // with another testing framework) and specify the former on the
  4673.     // command line for debugging.
  4674.     if (GTEST_FLAG(break_on_failure)) {
  4675. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  4676.       // Using DebugBreak on Windows allows gtest to still break into a debugger
  4677.       // when a failure happens and both the --gtest_break_on_failure and
  4678.       // the --gtest_catch_exceptions flags are specified.
  4679.       DebugBreak();
  4680. #elif (!defined(__native_client__)) &&            \
  4681.     ((defined(__clang__) || defined(__GNUC__)) && \
  4682.      (defined(__x86_64__) || defined(__i386__)))
  4683.       // with clang/gcc we can achieve the same effect on x86 by invoking int3
  4684.       asm("int3");
  4685. #else
  4686.       // Dereference NULL through a volatile pointer to prevent the compiler
  4687.       // from removing. We use this rather than abort() or __builtin_trap() for
  4688.       // portability: Symbian doesn't implement abort() well, and some debuggers
  4689.       // don't correctly trap abort().
  4690.       *static_cast<volatile int*>(NULL) = 1;
  4691. #endif  // GTEST_OS_WINDOWS
  4692.     } else if (GTEST_FLAG(throw_on_failure)) {
  4693. #if GTEST_HAS_EXCEPTIONS
  4694.       throw internal::GoogleTestFailureException(result);
  4695. #else
  4696.       // We cannot call abort() as it generates a pop-up in debug mode
  4697.       // that cannot be suppressed in VC 7.1 or below.
  4698.       exit(1);
  4699. #endif
  4700.     }
  4701.   }
  4702. }
  4703.  
  4704. // Adds a TestProperty to the current TestResult object when invoked from
  4705. // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
  4706. // from SetUpTestCase or TearDownTestCase, or to the global property set
  4707. // when invoked elsewhere.  If the result already contains a property with
  4708. // the same key, the value will be updated.
  4709. void UnitTest::RecordProperty(const std::string& key,
  4710.                               const std::string& value) {
  4711.   impl_->RecordProperty(TestProperty(key, value));
  4712. }
  4713.  
  4714. // Runs all tests in this UnitTest object and prints the result.
  4715. // Returns 0 if successful, or 1 otherwise.
  4716. //
  4717. // We don't protect this under mutex_, as we only support calling it
  4718. // from the main thread.
  4719. int UnitTest::Run() {
  4720.   const bool in_death_test_child_process =
  4721.       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  4722.  
  4723.   // Google Test implements this protocol for catching that a test
  4724.   // program exits before returning control to Google Test:
  4725.   //
  4726.   //   1. Upon start, Google Test creates a file whose absolute path
  4727.   //      is specified by the environment variable
  4728.   //      TEST_PREMATURE_EXIT_FILE.
  4729.   //   2. When Google Test has finished its work, it deletes the file.
  4730.   //
  4731.   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
  4732.   // running a Google-Test-based test program and check the existence
  4733.   // of the file at the end of the test execution to see if it has
  4734.   // exited prematurely.
  4735.  
  4736.   // If we are in the child process of a death test, don't
  4737.   // create/delete the premature exit file, as doing so is unnecessary
  4738.   // and will confuse the parent process.  Otherwise, create/delete
  4739.   // the file upon entering/leaving this function.  If the program
  4740.   // somehow exits before this function has a chance to return, the
  4741.   // premature-exit file will be left undeleted, causing a test runner
  4742.   // that understands the premature-exit-file protocol to report the
  4743.   // test as having failed.
  4744.   const internal::ScopedPrematureExitFile premature_exit_file(
  4745.       in_death_test_child_process ?
  4746.       NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
  4747.  
  4748.   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
  4749.   // used for the duration of the program.
  4750.   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  4751.  
  4752. #if GTEST_OS_WINDOWS
  4753.   // Either the user wants Google Test to catch exceptions thrown by the
  4754.   // tests or this is executing in the context of death test child
  4755.   // process. In either case the user does not want to see pop-up dialogs
  4756.   // about crashes - they are expected.
  4757.   if (impl()->catch_exceptions() || in_death_test_child_process) {
  4758. # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  4759.     // SetErrorMode doesn't exist on CE.
  4760.     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  4761.                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  4762. # endif  // !GTEST_OS_WINDOWS_MOBILE
  4763.  
  4764. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  4765.     // Death test children can be terminated with _abort().  On Windows,
  4766.     // _abort() can show a dialog with a warning message.  This forces the
  4767.     // abort message to go to stderr instead.
  4768.     _set_error_mode(_OUT_TO_STDERR);
  4769. # endif
  4770.  
  4771. # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
  4772.     // In the debug version, Visual Studio pops up a separate dialog
  4773.     // offering a choice to debug the aborted program. We need to suppress
  4774.     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  4775.     // executed. Google Test will notify the user of any unexpected
  4776.     // failure via stderr.
  4777.     //
  4778.     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
  4779.     // Users of prior VC versions shall suffer the agony and pain of
  4780.     // clicking through the countless debug dialogs.
  4781.     // FIXME: find a way to suppress the abort dialog() in the
  4782.     // debug mode when compiled with VC 7.1 or lower.
  4783.     if (!GTEST_FLAG(break_on_failure))
  4784.       _set_abort_behavior(
  4785.           0x0,                                    // Clear the following flags:
  4786.           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
  4787. # endif
  4788.   }
  4789. #endif  // GTEST_OS_WINDOWS
  4790.  
  4791.   return internal::HandleExceptionsInMethodIfSupported(
  4792.       impl(),
  4793.       &internal::UnitTestImpl::RunAllTests,
  4794.       "auxiliary test code (environments or event listeners)") ? 0 : 1;
  4795. }
  4796.  
  4797. // Returns the working directory when the first TEST() or TEST_F() was
  4798. // executed.
  4799. const char* UnitTest::original_working_dir() const {
  4800.   return impl_->original_working_dir_.c_str();
  4801. }
  4802.  
  4803. // Returns the TestCase object for the test that's currently running,
  4804. // or NULL if no test is running.
  4805. const TestCase* UnitTest::current_test_case() const
  4806.     GTEST_LOCK_EXCLUDED_(mutex_) {
  4807.   internal::MutexLock lock(&mutex_);
  4808.   return impl_->current_test_case();
  4809. }
  4810.  
  4811. // Returns the TestInfo object for the test that's currently running,
  4812. // or NULL if no test is running.
  4813. const TestInfo* UnitTest::current_test_info() const
  4814.     GTEST_LOCK_EXCLUDED_(mutex_) {
  4815.   internal::MutexLock lock(&mutex_);
  4816.   return impl_->current_test_info();
  4817. }
  4818.  
  4819. // Returns the random seed used at the start of the current test run.
  4820. int UnitTest::random_seed() const { return impl_->random_seed(); }
  4821.  
  4822. // Returns ParameterizedTestCaseRegistry object used to keep track of
  4823. // value-parameterized tests and instantiate and register them.
  4824. internal::ParameterizedTestCaseRegistry&
  4825.     UnitTest::parameterized_test_registry()
  4826.         GTEST_LOCK_EXCLUDED_(mutex_) {
  4827.   return impl_->parameterized_test_registry();
  4828. }
  4829.  
  4830. // Creates an empty UnitTest.
  4831. UnitTest::UnitTest() {
  4832.   impl_ = new internal::UnitTestImpl(this);
  4833. }
  4834.  
  4835. // Destructor of UnitTest.
  4836. UnitTest::~UnitTest() {
  4837.   delete impl_;
  4838. }
  4839.  
  4840. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  4841. // Google Test trace stack.
  4842. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  4843.     GTEST_LOCK_EXCLUDED_(mutex_) {
  4844.   internal::MutexLock lock(&mutex_);
  4845.   impl_->gtest_trace_stack().push_back(trace);
  4846. }
  4847.  
  4848. // Pops a trace from the per-thread Google Test trace stack.
  4849. void UnitTest::PopGTestTrace()
  4850.     GTEST_LOCK_EXCLUDED_(mutex_) {
  4851.   internal::MutexLock lock(&mutex_);
  4852.   impl_->gtest_trace_stack().pop_back();
  4853. }
  4854.  
  4855. namespace internal {
  4856.  
  4857. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  4858.     : parent_(parent),
  4859.       GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
  4860.       default_global_test_part_result_reporter_(this),
  4861.       default_per_thread_test_part_result_reporter_(this),
  4862.       GTEST_DISABLE_MSC_WARNINGS_POP_()
  4863.       global_test_part_result_repoter_(
  4864.           &default_global_test_part_result_reporter_),
  4865.       per_thread_test_part_result_reporter_(
  4866.           &default_per_thread_test_part_result_reporter_),
  4867.       parameterized_test_registry_(),
  4868.       parameterized_tests_registered_(false),
  4869.       last_death_test_case_(-1),
  4870.       current_test_case_(NULL),
  4871.       current_test_info_(NULL),
  4872.       ad_hoc_test_result_(),
  4873.       os_stack_trace_getter_(NULL),
  4874.       post_flag_parse_init_performed_(false),
  4875.       random_seed_(0),  // Will be overridden by the flag before first use.
  4876.       random_(0),  // Will be reseeded before first use.
  4877.       start_timestamp_(0),
  4878.       elapsed_time_(0),
  4879. #if GTEST_HAS_DEATH_TEST
  4880.       death_test_factory_(new DefaultDeathTestFactory),
  4881. #endif
  4882.       // Will be overridden by the flag before first use.
  4883.       catch_exceptions_(false) {
  4884.   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  4885. }
  4886.  
  4887. UnitTestImpl::~UnitTestImpl() {
  4888.   // Deletes every TestCase.
  4889.   ForEach(test_cases_, internal::Delete<TestCase>);
  4890.  
  4891.   // Deletes every Environment.
  4892.   ForEach(environments_, internal::Delete<Environment>);
  4893.  
  4894.   delete os_stack_trace_getter_;
  4895. }
  4896.  
  4897. // Adds a TestProperty to the current TestResult object when invoked in a
  4898. // context of a test, to current test case's ad_hoc_test_result when invoke
  4899. // from SetUpTestCase/TearDownTestCase, or to the global property set
  4900. // otherwise.  If the result already contains a property with the same key,
  4901. // the value will be updated.
  4902. void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
  4903.   std::string xml_element;
  4904.   TestResult* test_result;  // TestResult appropriate for property recording.
  4905.  
  4906.   if (current_test_info_ != NULL) {
  4907.     xml_element = "testcase";
  4908.     test_result = &(current_test_info_->result_);
  4909.   } else if (current_test_case_ != NULL) {
  4910.     xml_element = "testsuite";
  4911.     test_result = &(current_test_case_->ad_hoc_test_result_);
  4912.   } else {
  4913.     xml_element = "testsuites";
  4914.     test_result = &ad_hoc_test_result_;
  4915.   }
  4916.   test_result->RecordProperty(xml_element, test_property);
  4917. }
  4918.  
  4919. #if GTEST_HAS_DEATH_TEST
  4920. // Disables event forwarding if the control is currently in a death test
  4921. // subprocess. Must not be called before InitGoogleTest.
  4922. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  4923.   if (internal_run_death_test_flag_.get() != NULL)
  4924.     listeners()->SuppressEventForwarding();
  4925. }
  4926. #endif  // GTEST_HAS_DEATH_TEST
  4927.  
  4928. // Initializes event listeners performing XML output as specified by
  4929. // UnitTestOptions. Must not be called before InitGoogleTest.
  4930. void UnitTestImpl::ConfigureXmlOutput() {
  4931.   const std::string& output_format = UnitTestOptions::GetOutputFormat();
  4932.   if (output_format == "xml") {
  4933.     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  4934.         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  4935.   } else if (output_format == "json") {
  4936.     listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
  4937.         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  4938.   } else if (output_format != "") {
  4939.     GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
  4940.                         << output_format << "\" ignored.";
  4941.   }
  4942. }
  4943.  
  4944. #if GTEST_CAN_STREAM_RESULTS_
  4945. // Initializes event listeners for streaming test results in string form.
  4946. // Must not be called before InitGoogleTest.
  4947. void UnitTestImpl::ConfigureStreamingOutput() {
  4948.   const std::string& target = GTEST_FLAG(stream_result_to);
  4949.   if (!target.empty()) {
  4950.     const size_t pos = target.find(':');
  4951.     if (pos != std::string::npos) {
  4952.       listeners()->Append(new StreamingListener(target.substr(0, pos),
  4953.                                                 target.substr(pos+1)));
  4954.     } else {
  4955.       GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
  4956.                           << "\" ignored.";
  4957.     }
  4958.   }
  4959. }
  4960. #endif  // GTEST_CAN_STREAM_RESULTS_
  4961.  
  4962. // Performs initialization dependent upon flag values obtained in
  4963. // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
  4964. // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
  4965. // this function is also called from RunAllTests.  Since this function can be
  4966. // called more than once, it has to be idempotent.
  4967. void UnitTestImpl::PostFlagParsingInit() {
  4968.   // Ensures that this function does not execute more than once.
  4969.   if (!post_flag_parse_init_performed_) {
  4970.     post_flag_parse_init_performed_ = true;
  4971.  
  4972. #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  4973.     // Register to send notifications about key process state changes.
  4974.     listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
  4975. #endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  4976.  
  4977. #if GTEST_HAS_DEATH_TEST
  4978.     InitDeathTestSubprocessControlInfo();
  4979.     SuppressTestEventsIfInSubprocess();
  4980. #endif  // GTEST_HAS_DEATH_TEST
  4981.  
  4982.     // Registers parameterized tests. This makes parameterized tests
  4983.     // available to the UnitTest reflection API without running
  4984.     // RUN_ALL_TESTS.
  4985.     RegisterParameterizedTests();
  4986.  
  4987.     // Configures listeners for XML output. This makes it possible for users
  4988.     // to shut down the default XML output before invoking RUN_ALL_TESTS.
  4989.     ConfigureXmlOutput();
  4990.  
  4991. #if GTEST_CAN_STREAM_RESULTS_
  4992.     // Configures listeners for streaming test results to the specified server.
  4993.     ConfigureStreamingOutput();
  4994. #endif  // GTEST_CAN_STREAM_RESULTS_
  4995.  
  4996. #if GTEST_HAS_ABSL
  4997.     if (GTEST_FLAG(install_failure_signal_handler)) {
  4998.       absl::FailureSignalHandlerOptions options;
  4999.       absl::InstallFailureSignalHandler(options);
  5000.     }
  5001. #endif  // GTEST_HAS_ABSL
  5002.   }
  5003. }
  5004.  
  5005. // A predicate that checks the name of a TestCase against a known
  5006. // value.
  5007. //
  5008. // This is used for implementation of the UnitTest class only.  We put
  5009. // it in the anonymous namespace to prevent polluting the outer
  5010. // namespace.
  5011. //
  5012. // TestCaseNameIs is copyable.
  5013. class TestCaseNameIs {
  5014.  public:
  5015.   // Constructor.
  5016.   explicit TestCaseNameIs(const std::string& name)
  5017.       : name_(name) {}
  5018.  
  5019.   // Returns true iff the name of test_case matches name_.
  5020.   bool operator()(const TestCase* test_case) const {
  5021.     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
  5022.   }
  5023.  
  5024.  private:
  5025.   std::string name_;
  5026. };
  5027.  
  5028. // Finds and returns a TestCase with the given name.  If one doesn't
  5029. // exist, creates one and returns it.  It's the CALLER'S
  5030. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  5031. // TESTS ARE NOT SHUFFLED.
  5032. //
  5033. // Arguments:
  5034. //
  5035. //   test_case_name: name of the test case
  5036. //   type_param:     the name of the test case's type parameter, or NULL if
  5037. //                   this is not a typed or a type-parameterized test case.
  5038. //   set_up_tc:      pointer to the function that sets up the test case
  5039. //   tear_down_tc:   pointer to the function that tears down the test case
  5040. TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
  5041.                                     const char* type_param,
  5042.                                     Test::SetUpTestCaseFunc set_up_tc,
  5043.                                     Test::TearDownTestCaseFunc tear_down_tc) {
  5044.   // Can we find a TestCase with the given name?
  5045.   const std::vector<TestCase*>::const_reverse_iterator test_case =
  5046.       std::find_if(test_cases_.rbegin(), test_cases_.rend(),
  5047.                    TestCaseNameIs(test_case_name));
  5048.  
  5049.   if (test_case != test_cases_.rend())
  5050.     return *test_case;
  5051.  
  5052.   // No.  Let's create one.
  5053.   TestCase* const new_test_case =
  5054.       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
  5055.  
  5056.   // Is this a death test case?
  5057.   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
  5058.                                                kDeathTestCaseFilter)) {
  5059.     // Yes.  Inserts the test case after the last death test case
  5060.     // defined so far.  This only works when the test cases haven't
  5061.     // been shuffled.  Otherwise we may end up running a death test
  5062.     // after a non-death test.
  5063.     ++last_death_test_case_;
  5064.     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
  5065.                        new_test_case);
  5066.   } else {
  5067.     // No.  Appends to the end of the list.
  5068.     test_cases_.push_back(new_test_case);
  5069.   }
  5070.  
  5071.   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  5072.   return new_test_case;
  5073. }
  5074.  
  5075. // Helpers for setting up / tearing down the given environment.  They
  5076. // are for use in the ForEach() function.
  5077. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  5078. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  5079.  
  5080. // Runs all tests in this UnitTest object, prints the result, and
  5081. // returns true if all tests are successful.  If any exception is
  5082. // thrown during a test, the test is considered to be failed, but the
  5083. // rest of the tests will still be run.
  5084. //
  5085. // When parameterized tests are enabled, it expands and registers
  5086. // parameterized tests first in RegisterParameterizedTests().
  5087. // All other functions called from RunAllTests() may safely assume that
  5088. // parameterized tests are ready to be counted and run.
  5089. bool UnitTestImpl::RunAllTests() {
  5090.   // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
  5091.   const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
  5092.  
  5093.   // Do not run any test if the --help flag was specified.
  5094.   if (g_help_flag)
  5095.     return true;
  5096.  
  5097.   // Repeats the call to the post-flag parsing initialization in case the
  5098.   // user didn't call InitGoogleTest.
  5099.   PostFlagParsingInit();
  5100.  
  5101.   // Even if sharding is not on, test runners may want to use the
  5102.   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  5103.   // protocol.
  5104.   internal::WriteToShardStatusFileIfNeeded();
  5105.  
  5106.   // True iff we are in a subprocess for running a thread-safe-style
  5107.   // death test.
  5108.   bool in_subprocess_for_death_test = false;
  5109.  
  5110. #if GTEST_HAS_DEATH_TEST
  5111.   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
  5112. # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  5113.   if (in_subprocess_for_death_test) {
  5114.     GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
  5115.   }
  5116. # endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  5117. #endif  // GTEST_HAS_DEATH_TEST
  5118.  
  5119.   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  5120.                                         in_subprocess_for_death_test);
  5121.  
  5122.   // Compares the full test names with the filter to decide which
  5123.   // tests to run.
  5124.   const bool has_tests_to_run = FilterTests(should_shard
  5125.                                               ? HONOR_SHARDING_PROTOCOL
  5126.                                               : IGNORE_SHARDING_PROTOCOL) > 0;
  5127.  
  5128.   // Lists the tests and exits if the --gtest_list_tests flag was specified.
  5129.   if (GTEST_FLAG(list_tests)) {
  5130.     // This must be called *after* FilterTests() has been called.
  5131.     ListTestsMatchingFilter();
  5132.     return true;
  5133.   }
  5134.  
  5135.   random_seed_ = GTEST_FLAG(shuffle) ?
  5136.       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  5137.  
  5138.   // True iff at least one test has failed.
  5139.   bool failed = false;
  5140.  
  5141.   TestEventListener* repeater = listeners()->repeater();
  5142.  
  5143.   start_timestamp_ = GetTimeInMillis();
  5144.   repeater->OnTestProgramStart(*parent_);
  5145.  
  5146.   // How many times to repeat the tests?  We don't want to repeat them
  5147.   // when we are inside the subprocess of a death test.
  5148.   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  5149.   // Repeats forever if the repeat count is negative.
  5150.   const bool forever = repeat < 0;
  5151.   for (int i = 0; forever || i != repeat; i++) {
  5152.     // We want to preserve failures generated by ad-hoc test
  5153.     // assertions executed before RUN_ALL_TESTS().
  5154.     ClearNonAdHocTestResult();
  5155.  
  5156.     const TimeInMillis start = GetTimeInMillis();
  5157.  
  5158.     // Shuffles test cases and tests if requested.
  5159.     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  5160.       random()->Reseed(random_seed_);
  5161.       // This should be done before calling OnTestIterationStart(),
  5162.       // such that a test event listener can see the actual test order
  5163.       // in the event.
  5164.       ShuffleTests();
  5165.     }
  5166.  
  5167.     // Tells the unit test event listeners that the tests are about to start.
  5168.     repeater->OnTestIterationStart(*parent_, i);
  5169.  
  5170.     // Runs each test case if there is at least one test to run.
  5171.     if (has_tests_to_run) {
  5172.       // Sets up all environments beforehand.
  5173.       repeater->OnEnvironmentsSetUpStart(*parent_);
  5174.       ForEach(environments_, SetUpEnvironment);
  5175.       repeater->OnEnvironmentsSetUpEnd(*parent_);
  5176.  
  5177.       // Runs the tests only if there was no fatal failure during global
  5178.       // set-up.
  5179.       if (!Test::HasFatalFailure()) {
  5180.         for (int test_index = 0; test_index < total_test_case_count();
  5181.              test_index++) {
  5182.           GetMutableTestCase(test_index)->Run();
  5183.         }
  5184.       }
  5185.  
  5186.       // Tears down all environments in reverse order afterwards.
  5187.       repeater->OnEnvironmentsTearDownStart(*parent_);
  5188.       std::for_each(environments_.rbegin(), environments_.rend(),
  5189.                     TearDownEnvironment);
  5190.       repeater->OnEnvironmentsTearDownEnd(*parent_);
  5191.     }
  5192.  
  5193.     elapsed_time_ = GetTimeInMillis() - start;
  5194.  
  5195.     // Tells the unit test event listener that the tests have just finished.
  5196.     repeater->OnTestIterationEnd(*parent_, i);
  5197.  
  5198.     // Gets the result and clears it.
  5199.     if (!Passed()) {
  5200.       failed = true;
  5201.     }
  5202.  
  5203.     // Restores the original test order after the iteration.  This
  5204.     // allows the user to quickly repro a failure that happens in the
  5205.     // N-th iteration without repeating the first (N - 1) iterations.
  5206.     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  5207.     // case the user somehow changes the value of the flag somewhere
  5208.     // (it's always safe to unshuffle the tests).
  5209.     UnshuffleTests();
  5210.  
  5211.     if (GTEST_FLAG(shuffle)) {
  5212.       // Picks a new random seed for each iteration.
  5213.       random_seed_ = GetNextRandomSeed(random_seed_);
  5214.     }
  5215.   }
  5216.  
  5217.   repeater->OnTestProgramEnd(*parent_);
  5218.  
  5219.   if (!gtest_is_initialized_before_run_all_tests) {
  5220.     ColoredPrintf(
  5221.         COLOR_RED,
  5222.         "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
  5223.         "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
  5224.         "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
  5225.         " will start to enforce the valid usage. "
  5226.         "Please fix it ASAP, or IT WILL START TO FAIL.\n");  // NOLINT
  5227. #if GTEST_FOR_GOOGLE_
  5228.     ColoredPrintf(COLOR_RED,
  5229.                   "For more details, see http://wiki/Main/ValidGUnitMain.\n");
  5230. #endif  // GTEST_FOR_GOOGLE_
  5231.   }
  5232.  
  5233.   return !failed;
  5234. }
  5235.  
  5236. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  5237. // if the variable is present. If a file already exists at this location, this
  5238. // function will write over it. If the variable is present, but the file cannot
  5239. // be created, prints an error and exits.
  5240. void WriteToShardStatusFileIfNeeded() {
  5241.   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  5242.   if (test_shard_file != NULL) {
  5243.     FILE* const file = posix::FOpen(test_shard_file, "w");
  5244.     if (file == NULL) {
  5245.       ColoredPrintf(COLOR_RED,
  5246.                     "Could not write to the test shard status file \"%s\" "
  5247.                     "specified by the %s environment variable.\n",
  5248.                     test_shard_file, kTestShardStatusFile);
  5249.       fflush(stdout);
  5250.       exit(EXIT_FAILURE);
  5251.     }
  5252.     fclose(file);
  5253.   }
  5254. }
  5255.  
  5256. // Checks whether sharding is enabled by examining the relevant
  5257. // environment variable values. If the variables are present,
  5258. // but inconsistent (i.e., shard_index >= total_shards), prints
  5259. // an error and exits. If in_subprocess_for_death_test, sharding is
  5260. // disabled because it must only be applied to the original test
  5261. // process. Otherwise, we could filter out death tests we intended to execute.
  5262. bool ShouldShard(const char* total_shards_env,
  5263.                  const char* shard_index_env,
  5264.                  bool in_subprocess_for_death_test) {
  5265.   if (in_subprocess_for_death_test) {
  5266.     return false;
  5267.   }
  5268.  
  5269.   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  5270.   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  5271.  
  5272.   if (total_shards == -1 && shard_index == -1) {
  5273.     return false;
  5274.   } else if (total_shards == -1 && shard_index != -1) {
  5275.     const Message msg = Message()
  5276.       << "Invalid environment variables: you have "
  5277.       << kTestShardIndex << " = " << shard_index
  5278.       << ", but have left " << kTestTotalShards << " unset.\n";
  5279.     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5280.     fflush(stdout);
  5281.     exit(EXIT_FAILURE);
  5282.   } else if (total_shards != -1 && shard_index == -1) {
  5283.     const Message msg = Message()
  5284.       << "Invalid environment variables: you have "
  5285.       << kTestTotalShards << " = " << total_shards
  5286.       << ", but have left " << kTestShardIndex << " unset.\n";
  5287.     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5288.     fflush(stdout);
  5289.     exit(EXIT_FAILURE);
  5290.   } else if (shard_index < 0 || shard_index >= total_shards) {
  5291.     const Message msg = Message()
  5292.       << "Invalid environment variables: we require 0 <= "
  5293.       << kTestShardIndex << " < " << kTestTotalShards
  5294.       << ", but you have " << kTestShardIndex << "=" << shard_index
  5295.       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  5296.     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5297.     fflush(stdout);
  5298.     exit(EXIT_FAILURE);
  5299.   }
  5300.  
  5301.   return total_shards > 1;
  5302. }
  5303.  
  5304. // Parses the environment variable var as an Int32. If it is unset,
  5305. // returns default_val. If it is not an Int32, prints an error
  5306. // and aborts.
  5307. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
  5308.   const char* str_val = posix::GetEnv(var);
  5309.   if (str_val == NULL) {
  5310.     return default_val;
  5311.   }
  5312.  
  5313.   Int32 result;
  5314.   if (!ParseInt32(Message() << "The value of environment variable " << var,
  5315.                   str_val, &result)) {
  5316.     exit(EXIT_FAILURE);
  5317.   }
  5318.   return result;
  5319. }
  5320.  
  5321. // Given the total number of shards, the shard index, and the test id,
  5322. // returns true iff the test should be run on this shard. The test id is
  5323. // some arbitrary but unique non-negative integer assigned to each test
  5324. // method. Assumes that 0 <= shard_index < total_shards.
  5325. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  5326.   return (test_id % total_shards) == shard_index;
  5327. }
  5328.  
  5329. // Compares the name of each test with the user-specified filter to
  5330. // decide whether the test should be run, then records the result in
  5331. // each TestCase and TestInfo object.
  5332. // If shard_tests == true, further filters tests based on sharding
  5333. // variables in the environment - see
  5334. // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
  5335. // . Returns the number of tests that should run.
  5336. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  5337.   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5338.       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  5339.   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5340.       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  5341.  
  5342.   // num_runnable_tests are the number of tests that will
  5343.   // run across all shards (i.e., match filter and are not disabled).
  5344.   // num_selected_tests are the number of tests to be run on
  5345.   // this shard.
  5346.   int num_runnable_tests = 0;
  5347.   int num_selected_tests = 0;
  5348.   for (size_t i = 0; i < test_cases_.size(); i++) {
  5349.     TestCase* const test_case = test_cases_[i];
  5350.     const std::string &test_case_name = test_case->name();
  5351.     test_case->set_should_run(false);
  5352.  
  5353.     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5354.       TestInfo* const test_info = test_case->test_info_list()[j];
  5355.       const std::string test_name(test_info->name());
  5356.       // A test is disabled if test case name or test name matches
  5357.       // kDisableTestFilter.
  5358.       const bool is_disabled =
  5359.           internal::UnitTestOptions::MatchesFilter(test_case_name,
  5360.                                                    kDisableTestFilter) ||
  5361.           internal::UnitTestOptions::MatchesFilter(test_name,
  5362.                                                    kDisableTestFilter);
  5363.       test_info->is_disabled_ = is_disabled;
  5364.  
  5365.       const bool matches_filter =
  5366.           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
  5367.                                                        test_name);
  5368.       test_info->matches_filter_ = matches_filter;
  5369.  
  5370.       const bool is_runnable =
  5371.           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  5372.           matches_filter;
  5373.  
  5374.       const bool is_in_another_shard =
  5375.           shard_tests != IGNORE_SHARDING_PROTOCOL &&
  5376.           !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
  5377.       test_info->is_in_another_shard_ = is_in_another_shard;
  5378.       const bool is_selected = is_runnable && !is_in_another_shard;
  5379.  
  5380.       num_runnable_tests += is_runnable;
  5381.       num_selected_tests += is_selected;
  5382.  
  5383.       test_info->should_run_ = is_selected;
  5384.       test_case->set_should_run(test_case->should_run() || is_selected);
  5385.     }
  5386.   }
  5387.   return num_selected_tests;
  5388. }
  5389.  
  5390. // Prints the given C-string on a single line by replacing all '\n'
  5391. // characters with string "\\n".  If the output takes more than
  5392. // max_length characters, only prints the first max_length characters
  5393. // and "...".
  5394. static void PrintOnOneLine(const char* str, int max_length) {
  5395.   if (str != NULL) {
  5396.     for (int i = 0; *str != '\0'; ++str) {
  5397.       if (i >= max_length) {
  5398.         printf("...");
  5399.         break;
  5400.       }
  5401.       if (*str == '\n') {
  5402.         printf("\\n");
  5403.         i += 2;
  5404.       } else {
  5405.         printf("%c", *str);
  5406.         ++i;
  5407.       }
  5408.     }
  5409.   }
  5410. }
  5411.  
  5412. // Prints the names of the tests matching the user-specified filter flag.
  5413. void UnitTestImpl::ListTestsMatchingFilter() {
  5414.   // Print at most this many characters for each type/value parameter.
  5415.   const int kMaxParamLength = 250;
  5416.  
  5417.   for (size_t i = 0; i < test_cases_.size(); i++) {
  5418.     const TestCase* const test_case = test_cases_[i];
  5419.     bool printed_test_case_name = false;
  5420.  
  5421.     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5422.       const TestInfo* const test_info =
  5423.           test_case->test_info_list()[j];
  5424.       if (test_info->matches_filter_) {
  5425.         if (!printed_test_case_name) {
  5426.           printed_test_case_name = true;
  5427.           printf("%s.", test_case->name());
  5428.           if (test_case->type_param() != NULL) {
  5429.             printf("  # %s = ", kTypeParamLabel);
  5430.             // We print the type parameter on a single line to make
  5431.             // the output easy to parse by a program.
  5432.             PrintOnOneLine(test_case->type_param(), kMaxParamLength);
  5433.           }
  5434.           printf("\n");
  5435.         }
  5436.         printf("  %s", test_info->name());
  5437.         if (test_info->value_param() != NULL) {
  5438.           printf("  # %s = ", kValueParamLabel);
  5439.           // We print the value parameter on a single line to make the
  5440.           // output easy to parse by a program.
  5441.           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
  5442.         }
  5443.         printf("\n");
  5444.       }
  5445.     }
  5446.   }
  5447.   fflush(stdout);
  5448.   const std::string& output_format = UnitTestOptions::GetOutputFormat();
  5449.   if (output_format == "xml" || output_format == "json") {
  5450.     FILE* fileout = OpenFileForWriting(
  5451.         UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
  5452.     std::stringstream stream;
  5453.     if (output_format == "xml") {
  5454.       XmlUnitTestResultPrinter(
  5455.           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5456.           .PrintXmlTestsList(&stream, test_cases_);
  5457.     } else if (output_format == "json") {
  5458.       JsonUnitTestResultPrinter(
  5459.           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5460.           .PrintJsonTestList(&stream, test_cases_);
  5461.     }
  5462.     fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
  5463.     fclose(fileout);
  5464.   }
  5465. }
  5466.  
  5467. // Sets the OS stack trace getter.
  5468. //
  5469. // Does nothing if the input and the current OS stack trace getter are
  5470. // the same; otherwise, deletes the old getter and makes the input the
  5471. // current getter.
  5472. void UnitTestImpl::set_os_stack_trace_getter(
  5473.     OsStackTraceGetterInterface* getter) {
  5474.   if (os_stack_trace_getter_ != getter) {
  5475.     delete os_stack_trace_getter_;
  5476.     os_stack_trace_getter_ = getter;
  5477.   }
  5478. }
  5479.  
  5480. // Returns the current OS stack trace getter if it is not NULL;
  5481. // otherwise, creates an OsStackTraceGetter, makes it the current
  5482. // getter, and returns it.
  5483. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  5484.   if (os_stack_trace_getter_ == NULL) {
  5485. #ifdef GTEST_OS_STACK_TRACE_GETTER_
  5486.     os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
  5487. #else
  5488.     os_stack_trace_getter_ = new OsStackTraceGetter;
  5489. #endif  // GTEST_OS_STACK_TRACE_GETTER_
  5490.   }
  5491.  
  5492.   return os_stack_trace_getter_;
  5493. }
  5494.  
  5495. // Returns the most specific TestResult currently running.
  5496. TestResult* UnitTestImpl::current_test_result() {
  5497.   if (current_test_info_ != NULL) {
  5498.     return &current_test_info_->result_;
  5499.   }
  5500.   if (current_test_case_ != NULL) {
  5501.     return &current_test_case_->ad_hoc_test_result_;
  5502.   }
  5503.   return &ad_hoc_test_result_;
  5504. }
  5505.  
  5506. // Shuffles all test cases, and the tests within each test case,
  5507. // making sure that death tests are still run first.
  5508. void UnitTestImpl::ShuffleTests() {
  5509.   // Shuffles the death test cases.
  5510.   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
  5511.  
  5512.   // Shuffles the non-death test cases.
  5513.   ShuffleRange(random(), last_death_test_case_ + 1,
  5514.                static_cast<int>(test_cases_.size()), &test_case_indices_);
  5515.  
  5516.   // Shuffles the tests inside each test case.
  5517.   for (size_t i = 0; i < test_cases_.size(); i++) {
  5518.     test_cases_[i]->ShuffleTests(random());
  5519.   }
  5520. }
  5521.  
  5522. // Restores the test cases and tests to their order before the first shuffle.
  5523. void UnitTestImpl::UnshuffleTests() {
  5524.   for (size_t i = 0; i < test_cases_.size(); i++) {
  5525.     // Unshuffles the tests in each test case.
  5526.     test_cases_[i]->UnshuffleTests();
  5527.     // Resets the index of each test case.
  5528.     test_case_indices_[i] = static_cast<int>(i);
  5529.   }
  5530. }
  5531.  
  5532. // Returns the current OS stack trace as an std::string.
  5533. //
  5534. // The maximum number of stack frames to be included is specified by
  5535. // the gtest_stack_trace_depth flag.  The skip_count parameter
  5536. // specifies the number of top frames to be skipped, which doesn't
  5537. // count against the number of frames to be included.
  5538. //
  5539. // For example, if Foo() calls Bar(), which in turn calls
  5540. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  5541. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  5542. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  5543.                                             int skip_count) {
  5544.   // We pass skip_count + 1 to skip this wrapper function in addition
  5545.   // to what the user really wants to skip.
  5546.   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  5547. }
  5548.  
  5549. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  5550. // suppress unreachable code warnings.
  5551. namespace {
  5552. class ClassUniqueToAlwaysTrue {};
  5553. }
  5554.  
  5555. bool IsTrue(bool condition) { return condition; }
  5556.  
  5557. bool AlwaysTrue() {
  5558. #if GTEST_HAS_EXCEPTIONS
  5559.   // This condition is always false so AlwaysTrue() never actually throws,
  5560.   // but it makes the compiler think that it may throw.
  5561.   if (IsTrue(false))
  5562.     throw ClassUniqueToAlwaysTrue();
  5563. #endif  // GTEST_HAS_EXCEPTIONS
  5564.   return true;
  5565. }
  5566.  
  5567. // If *pstr starts with the given prefix, modifies *pstr to be right
  5568. // past the prefix and returns true; otherwise leaves *pstr unchanged
  5569. // and returns false.  None of pstr, *pstr, and prefix can be NULL.
  5570. bool SkipPrefix(const char* prefix, const char** pstr) {
  5571.   const size_t prefix_len = strlen(prefix);
  5572.   if (strncmp(*pstr, prefix, prefix_len) == 0) {
  5573.     *pstr += prefix_len;
  5574.     return true;
  5575.   }
  5576.   return false;
  5577. }
  5578.  
  5579. // Parses a string as a command line flag.  The string should have
  5580. // the format "--flag=value".  When def_optional is true, the "=value"
  5581. // part can be omitted.
  5582. //
  5583. // Returns the value of the flag, or NULL if the parsing failed.
  5584. static const char* ParseFlagValue(const char* str, const char* flag,
  5585.                                   bool def_optional) {
  5586.   // str and flag must not be NULL.
  5587.   if (str == NULL || flag == NULL) return NULL;
  5588.  
  5589.   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  5590.   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
  5591.   const size_t flag_len = flag_str.length();
  5592.   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
  5593.  
  5594.   // Skips the flag name.
  5595.   const char* flag_end = str + flag_len;
  5596.  
  5597.   // When def_optional is true, it's OK to not have a "=value" part.
  5598.   if (def_optional && (flag_end[0] == '\0')) {
  5599.     return flag_end;
  5600.   }
  5601.  
  5602.   // If def_optional is true and there are more characters after the
  5603.   // flag name, or if def_optional is false, there must be a '=' after
  5604.   // the flag name.
  5605.   if (flag_end[0] != '=') return NULL;
  5606.  
  5607.   // Returns the string after "=".
  5608.   return flag_end + 1;
  5609. }
  5610.  
  5611. // Parses a string for a bool flag, in the form of either
  5612. // "--flag=value" or "--flag".
  5613. //
  5614. // In the former case, the value is taken as true as long as it does
  5615. // not start with '0', 'f', or 'F'.
  5616. //
  5617. // In the latter case, the value is taken as true.
  5618. //
  5619. // On success, stores the value of the flag in *value, and returns
  5620. // true.  On failure, returns false without changing *value.
  5621. static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  5622.   // Gets the value of the flag as a string.
  5623.   const char* const value_str = ParseFlagValue(str, flag, true);
  5624.  
  5625.   // Aborts if the parsing failed.
  5626.   if (value_str == NULL) return false;
  5627.  
  5628.   // Converts the string value to a bool.
  5629.   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  5630.   return true;
  5631. }
  5632.  
  5633. // Parses a string for an Int32 flag, in the form of
  5634. // "--flag=value".
  5635. //
  5636. // On success, stores the value of the flag in *value, and returns
  5637. // true.  On failure, returns false without changing *value.
  5638. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
  5639.   // Gets the value of the flag as a string.
  5640.   const char* const value_str = ParseFlagValue(str, flag, false);
  5641.  
  5642.   // Aborts if the parsing failed.
  5643.   if (value_str == NULL) return false;
  5644.  
  5645.   // Sets *value to the value of the flag.
  5646.   return ParseInt32(Message() << "The value of flag --" << flag,
  5647.                     value_str, value);
  5648. }
  5649.  
  5650. // Parses a string for a string flag, in the form of
  5651. // "--flag=value".
  5652. //
  5653. // On success, stores the value of the flag in *value, and returns
  5654. // true.  On failure, returns false without changing *value.
  5655. template <typename String>
  5656. static bool ParseStringFlag(const char* str, const char* flag, String* value) {
  5657.   // Gets the value of the flag as a string.
  5658.   const char* const value_str = ParseFlagValue(str, flag, false);
  5659.  
  5660.   // Aborts if the parsing failed.
  5661.   if (value_str == NULL) return false;
  5662.  
  5663.   // Sets *value to the value of the flag.
  5664.   *value = value_str;
  5665.   return true;
  5666. }
  5667.  
  5668. // Determines whether a string has a prefix that Google Test uses for its
  5669. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  5670. // If Google Test detects that a command line flag has its prefix but is not
  5671. // recognized, it will print its help message. Flags starting with
  5672. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  5673. // internal flags and do not trigger the help message.
  5674. static bool HasGoogleTestFlagPrefix(const char* str) {
  5675.   return (SkipPrefix("--", &str) ||
  5676.           SkipPrefix("-", &str) ||
  5677.           SkipPrefix("/", &str)) &&
  5678.          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  5679.          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  5680.           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  5681. }
  5682.  
  5683. // Prints a string containing code-encoded text.  The following escape
  5684. // sequences can be used in the string to control the text color:
  5685. //
  5686. //   @@    prints a single '@' character.
  5687. //   @R    changes the color to red.
  5688. //   @G    changes the color to green.
  5689. //   @Y    changes the color to yellow.
  5690. //   @D    changes to the default terminal text color.
  5691. //
  5692. // FIXME: Write tests for this once we add stdout
  5693. // capturing to Google Test.
  5694. static void PrintColorEncoded(const char* str) {
  5695.   GTestColor color = COLOR_DEFAULT;  // The current color.
  5696.  
  5697.   // Conceptually, we split the string into segments divided by escape
  5698.   // sequences.  Then we print one segment at a time.  At the end of
  5699.   // each iteration, the str pointer advances to the beginning of the
  5700.   // next segment.
  5701.   for (;;) {
  5702.     const char* p = strchr(str, '@');
  5703.     if (p == NULL) {
  5704.       ColoredPrintf(color, "%s", str);
  5705.       return;
  5706.     }
  5707.  
  5708.     ColoredPrintf(color, "%s", std::string(str, p).c_str());
  5709.  
  5710.     const char ch = p[1];
  5711.     str = p + 2;
  5712.     if (ch == '@') {
  5713.       ColoredPrintf(color, "@");
  5714.     } else if (ch == 'D') {
  5715.       color = COLOR_DEFAULT;
  5716.     } else if (ch == 'R') {
  5717.       color = COLOR_RED;
  5718.     } else if (ch == 'G') {
  5719.       color = COLOR_GREEN;
  5720.     } else if (ch == 'Y') {
  5721.       color = COLOR_YELLOW;
  5722.     } else {
  5723.       --str;
  5724.     }
  5725.   }
  5726. }
  5727.  
  5728. static const char kColorEncodedHelpMessage[] =
  5729. "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
  5730. "following command line flags to control its behavior:\n"
  5731. "\n"
  5732. "Test Selection:\n"
  5733. "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
  5734. "      List the names of all tests instead of running them. The name of\n"
  5735. "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
  5736. "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
  5737.     "[@G-@YNEGATIVE_PATTERNS]@D\n"
  5738. "      Run only the tests whose name matches one of the positive patterns but\n"
  5739. "      none of the negative patterns. '?' matches any single character; '*'\n"
  5740. "      matches any substring; ':' separates two patterns.\n"
  5741. "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
  5742. "      Run all disabled tests too.\n"
  5743. "\n"
  5744. "Test Execution:\n"
  5745. "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
  5746. "      Run the tests repeatedly; use a negative count to repeat forever.\n"
  5747. "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
  5748. "      Randomize tests' orders on every iteration.\n"
  5749. "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
  5750. "      Random number seed to use for shuffling test orders (between 1 and\n"
  5751. "      99999, or 0 to use a seed based on the current time).\n"
  5752. "\n"
  5753. "Test Output:\n"
  5754. "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  5755. "      Enable/disable colored output. The default is @Gauto@D.\n"
  5756. "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
  5757. "      Don't print the elapsed time of each test.\n"
  5758. "  @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
  5759.     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
  5760. "      Generate a JSON or XML report in the given directory or with the given\n"
  5761. "      file name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
  5762. # if GTEST_CAN_STREAM_RESULTS_
  5763. "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
  5764. "      Stream test results to the given server.\n"
  5765. # endif  // GTEST_CAN_STREAM_RESULTS_
  5766. "\n"
  5767. "Assertion Behavior:\n"
  5768. # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5769. "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  5770. "      Set the default death test style.\n"
  5771. # endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5772. "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
  5773. "      Turn assertion failures into debugger break-points.\n"
  5774. "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
  5775. "      Turn assertion failures into C++ exceptions for use by an external\n"
  5776. "      test framework.\n"
  5777. "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
  5778. "      Do not report exceptions as test failures. Instead, allow them\n"
  5779. "      to crash the program or throw a pop-up (on Windows).\n"
  5780. "\n"
  5781. "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
  5782.     "the corresponding\n"
  5783. "environment variable of a flag (all letters in upper-case). For example, to\n"
  5784. "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
  5785.     "color=no@D or set\n"
  5786. "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
  5787. "\n"
  5788. "For more information, please read the " GTEST_NAME_ " documentation at\n"
  5789. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
  5790. "(not one in your own code or tests), please report it to\n"
  5791. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  5792.  
  5793. static bool ParseGoogleTestFlag(const char* const arg) {
  5794.   return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  5795.                        &GTEST_FLAG(also_run_disabled_tests)) ||
  5796.       ParseBoolFlag(arg, kBreakOnFailureFlag,
  5797.                     &GTEST_FLAG(break_on_failure)) ||
  5798.       ParseBoolFlag(arg, kCatchExceptionsFlag,
  5799.                     &GTEST_FLAG(catch_exceptions)) ||
  5800.       ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  5801.       ParseStringFlag(arg, kDeathTestStyleFlag,
  5802.                       &GTEST_FLAG(death_test_style)) ||
  5803.       ParseBoolFlag(arg, kDeathTestUseFork,
  5804.                     &GTEST_FLAG(death_test_use_fork)) ||
  5805.       ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  5806.       ParseStringFlag(arg, kInternalRunDeathTestFlag,
  5807.                       &GTEST_FLAG(internal_run_death_test)) ||
  5808.       ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  5809.       ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  5810.       ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  5811.       ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
  5812.       ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  5813.       ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  5814.       ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  5815.       ParseInt32Flag(arg, kStackTraceDepthFlag,
  5816.                      &GTEST_FLAG(stack_trace_depth)) ||
  5817.       ParseStringFlag(arg, kStreamResultToFlag,
  5818.                       &GTEST_FLAG(stream_result_to)) ||
  5819.       ParseBoolFlag(arg, kThrowOnFailureFlag,
  5820.                     &GTEST_FLAG(throw_on_failure));
  5821. }
  5822.  
  5823. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  5824. static void LoadFlagsFromFile(const std::string& path) {
  5825.   FILE* flagfile = posix::FOpen(path.c_str(), "r");
  5826.   if (!flagfile) {
  5827.     GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
  5828.                       << "\"";
  5829.   }
  5830.   std::string contents(ReadEntireFile(flagfile));
  5831.   posix::FClose(flagfile);
  5832.   std::vector<std::string> lines;
  5833.   SplitString(contents, '\n', &lines);
  5834.   for (size_t i = 0; i < lines.size(); ++i) {
  5835.     if (lines[i].empty())
  5836.       continue;
  5837.     if (!ParseGoogleTestFlag(lines[i].c_str()))
  5838.       g_help_flag = true;
  5839.   }
  5840. }
  5841. #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
  5842.  
  5843. // Parses the command line for Google Test flags, without initializing
  5844. // other parts of Google Test.  The type parameter CharType can be
  5845. // instantiated to either char or wchar_t.
  5846. template <typename CharType>
  5847. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  5848.   for (int i = 1; i < *argc; i++) {
  5849.     const std::string arg_string = StreamableToString(argv[i]);
  5850.     const char* const arg = arg_string.c_str();
  5851.  
  5852.     using internal::ParseBoolFlag;
  5853.     using internal::ParseInt32Flag;
  5854.     using internal::ParseStringFlag;
  5855.  
  5856.     bool remove_flag = false;
  5857.     if (ParseGoogleTestFlag(arg)) {
  5858.       remove_flag = true;
  5859. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  5860.     } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
  5861.       LoadFlagsFromFile(GTEST_FLAG(flagfile));
  5862.       remove_flag = true;
  5863. #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
  5864.     } else if (arg_string == "--help" || arg_string == "-h" ||
  5865.                arg_string == "-?" || arg_string == "/?" ||
  5866.                HasGoogleTestFlagPrefix(arg)) {
  5867.       // Both help flag and unrecognized Google Test flags (excluding
  5868.       // internal ones) trigger help display.
  5869.       g_help_flag = true;
  5870.     }
  5871.  
  5872.     if (remove_flag) {
  5873.       // Shift the remainder of the argv list left by one.  Note
  5874.       // that argv has (*argc + 1) elements, the last one always being
  5875.       // NULL.  The following loop moves the trailing NULL element as
  5876.       // well.
  5877.       for (int j = i; j != *argc; j++) {
  5878.         argv[j] = argv[j + 1];
  5879.       }
  5880.  
  5881.       // Decrements the argument count.
  5882.       (*argc)--;
  5883.  
  5884.       // We also need to decrement the iterator as we just removed
  5885.       // an element.
  5886.       i--;
  5887.     }
  5888.   }
  5889.  
  5890.   if (g_help_flag) {
  5891.     // We print the help here instead of in RUN_ALL_TESTS(), as the
  5892.     // latter may not be called at all if the user is using Google
  5893.     // Test with another testing framework.
  5894.     PrintColorEncoded(kColorEncodedHelpMessage);
  5895.   }
  5896. }
  5897.  
  5898. // Parses the command line for Google Test flags, without initializing
  5899. // other parts of Google Test.
  5900. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  5901.   ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5902.  
  5903.   // Fix the value of *_NSGetArgc() on macOS, but iff
  5904.   // *_NSGetArgv() == argv
  5905.   // Only applicable to char** version of argv
  5906. #if GTEST_OS_MAC
  5907. #ifndef GTEST_OS_IOS
  5908.   if (*_NSGetArgv() == argv) {
  5909.     *_NSGetArgc() = *argc;
  5910.   }
  5911. #endif
  5912. #endif
  5913. }
  5914. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  5915.   ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5916. }
  5917.  
  5918. // The internal implementation of InitGoogleTest().
  5919. //
  5920. // The type parameter CharType can be instantiated to either char or
  5921. // wchar_t.
  5922. template <typename CharType>
  5923. void InitGoogleTestImpl(int* argc, CharType** argv) {
  5924.   // We don't want to run the initialization code twice.
  5925.   if (GTestIsInitialized()) return;
  5926.  
  5927.   if (*argc <= 0) return;
  5928.  
  5929.   g_argvs.clear();
  5930.   for (int i = 0; i != *argc; i++) {
  5931.     g_argvs.push_back(StreamableToString(argv[i]));
  5932.   }
  5933.  
  5934. #if GTEST_HAS_ABSL
  5935.   absl::InitializeSymbolizer(g_argvs[0].c_str());
  5936. #endif  // GTEST_HAS_ABSL
  5937.  
  5938.   ParseGoogleTestFlagsOnly(argc, argv);
  5939.   GetUnitTestImpl()->PostFlagParsingInit();
  5940. }
  5941.  
  5942. }  // namespace internal
  5943.  
  5944. // Initializes Google Test.  This must be called before calling
  5945. // RUN_ALL_TESTS().  In particular, it parses a command line for the
  5946. // flags that Google Test recognizes.  Whenever a Google Test flag is
  5947. // seen, it is removed from argv, and *argc is decremented.
  5948. //
  5949. // No value is returned.  Instead, the Google Test flag variables are
  5950. // updated.
  5951. //
  5952. // Calling the function for the second time has no user-visible effect.
  5953. void InitGoogleTest(int* argc, char** argv) {
  5954. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5955.   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  5956. #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5957.   internal::InitGoogleTestImpl(argc, argv);
  5958. #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5959. }
  5960.  
  5961. // This overloaded version can be used in Windows programs compiled in
  5962. // UNICODE mode.
  5963. void InitGoogleTest(int* argc, wchar_t** argv) {
  5964. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5965.   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  5966. #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5967.   internal::InitGoogleTestImpl(argc, argv);
  5968. #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5969. }
  5970.  
  5971. std::string TempDir() {
  5972. #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
  5973.   return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
  5974. #endif
  5975.  
  5976. #if GTEST_OS_WINDOWS_MOBILE
  5977.   return "\\temp\\";
  5978. #elif GTEST_OS_WINDOWS
  5979.   const char* temp_dir = internal::posix::GetEnv("TEMP");
  5980.   if (temp_dir == NULL || temp_dir[0] == '\0')
  5981.     return "\\temp\\";
  5982.   else if (temp_dir[strlen(temp_dir) - 1] == '\\')
  5983.     return temp_dir;
  5984.   else
  5985.     return std::string(temp_dir) + "\\";
  5986. #elif GTEST_OS_LINUX_ANDROID
  5987.   return "/sdcard/";
  5988. #else
  5989.   return "/tmp/";
  5990. #endif  // GTEST_OS_WINDOWS_MOBILE
  5991. }
  5992.  
  5993. // Class ScopedTrace
  5994.  
  5995. // Pushes the given source file location and message onto a per-thread
  5996. // trace stack maintained by Google Test.
  5997. void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
  5998.   internal::TraceInfo trace;
  5999.   trace.file = file;
  6000.   trace.line = line;
  6001.   trace.message.swap(message);
  6002.  
  6003.   UnitTest::GetInstance()->PushGTestTrace(trace);
  6004. }
  6005.  
  6006. // Pops the info pushed by the c'tor.
  6007. ScopedTrace::~ScopedTrace()
  6008.     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  6009.   UnitTest::GetInstance()->PopGTestTrace();
  6010. }
  6011.  
  6012. }  // namespace testing
  6013.