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