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