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