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