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