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