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