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