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